From chris.gonnerman at newcenturycomputers.net Sat Sep 28 02:15:18 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sat, 28 Sep 2002 01:15:18 -0500 Subject: zlib needs the python15.dll on python22 ??? References: Message-ID: <000d01c266b6$6c6785c0$ba01010a@local> ----- Original Message ----- From: "Ralf Claus" <102030405 at gmx.net> > Hello NG, > by importing the zlib module on python 2.2 (windows) > i get a popup that means "python15.dll not found in path > //winnt/system32/......and so on... > > On that computer, there was never installed python 1.5 !? > > What is wrong ? > > Thanks a lot > Ralf You have an old version of the zlib module on your system. Good luck finding it... Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From monnetb at yahoo.com Tue Sep 10 09:20:15 2002 From: monnetb at yahoo.com (bruno Monnet) Date: 10 Sep 2002 06:20:15 -0700 Subject: embedded Python sample Message-ID: <2a0f4cc4.0209100520.1d3a723b@posting.google.com> Hi, I'm trying to call a python script from my c++ code. All I need is to invoke the script and check the return status. does anyone has a simple example ? All I found until now is very complex and ugly code :-(( Regards, Bruno From aahz at pythoncraft.com Sun Sep 29 13:19:52 2002 From: aahz at pythoncraft.com (Aahz) Date: 29 Sep 2002 13:19:52 -0400 Subject: Newbie References Question -> Exemple References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> <3d91d2cf$0$1484$79c14f64@nan-newsreader-01.noos.net> Message-ID: In article <3d91d2cf$0$1484$79c14f64 at nan-newsreader-01.noos.net>, Guy Rabiller wrote: > >What I want to do is simple, and I suppose that this is my 'way of thinking' >regarding Python that is wrong. Yup. >I have a list of points, and a list of polygons that should contain >'references' to points. > >So for me: >-> points list: >p = [] >p.append([0,0]) >p.append([0,1]) >p.append([1,1]) >p.append([1,0]) >-> polygon: >quad = [] >quad.append(p[0]) >quad.append(p[1]) >quad.append(p[2]) >quad.append(p[3]) Make the actual points class instances. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From anthony at computronix.com Fri Sep 13 14:07:19 2002 From: anthony at computronix.com (Anthony Tuininga) Date: 13 Sep 2002 12:07:19 -0600 Subject: calling Oracle functions In-Reply-To: <3d821f71$1@news.mt.net.mk> References: <3d81f811$1@news.mt.net.mk> <3d8210a3@news.mt.net.mk> <3d821f71$1@news.mt.net.mk> Message-ID: <1031940440.472.97.camel@chl0151.edmonton.computronix.com> On Fri, 2002-09-13 at 11:25, ?????? ?. wrote: > > >> Now a simpler question: > >> is it possible to specify the data source name directly not through > >> the alias defined in tnsnames.ora. In perl DBD I can specify a > >> connection string like cs = "dbi:Oracle:host=1.10.100.200;sid=TEST"? > > > cx_Oracle is passing the string directly to Oracle, so whatever it > > accepts, cx_Oracle will accept. Specifically, you can take the entire > > string that is in your tnsnames.ora file and pass it directly as in > > > v_TNS = > > (DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=opus)(PORT=1521)))(CONNECT_DATA=(SID=DEV))) > > > v_Connection = cx_Oracle.connect("user", "pw", v_TNS) > > > and that works just fine. Does that answer your question? > > Yes. Thanks. I would only suggest that you can add a function to > cx_Oracle to make that big ugly string from 3 parameters. > something like: > > def makeDSN(host,port,sid): > return """(DESCRIPTION= (ADDRESS_LIST= (ADDRESS= (PROTOCOL=TCP) > (HOST=%s) (PORT=%s))) (CONNECT_DATA=(SID=%s)))""" % > (host,port,sid) Sounds reasonable. I'll put it on my list of things to do. > > > > > > -- > ?????? > > Intel: where Quality is job number 0.9998782345! > > -- > http://mail.python.org/mailman/listinfo/python-list -- Anthony Tuininga anthony at computronix.com Computronix Distinctive Software. Real People. Suite 200, 10216 - 124 Street NW Edmonton, AB, Canada T5N 4A3 Phone: (780) 454-3700 Fax: (780) 454-3838 http://www.computronix.com From sismex01 at hebmex.com Thu Sep 26 10:10:19 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 26 Sep 2002 09:10:19 -0500 Subject: Python threading? Message-ID: > > I wonder if generators can come to a rescue here? > Still trying to get them into my head... > > Thomas > I was thinking exactly the same thing, generators as cooperative multithreading. I wonder if a "task", or a "service", in an async server could simply initialize and then "yield" when it's ready to be paused, and between yield's do some processing. The core server would simpy call the service factory when it's requested, receive a generator back, add it to it's pool of active services, and iteratively call every generators ".next()" method, so everybody gets a bit of attention and love each cycle. You could even use priorities, something simple, where high- priority services would receive a bit more attention every complete cycle. I dunno, but it's an idea who's time has time, I think. :-) -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From marklists at mceahern.com Tue Sep 17 10:28:15 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 17 Sep 2002 09:28:15 -0500 Subject: newbie-question: private attributes In-Reply-To: <3D873A42.1070400@snafu.de> Message-ID: [T. Kaufmann] > What is the difference between the two attributes in this class? > > class Test: > > def __init__(self): > > self.__var1 = 1 # I think this is a private attribute > self._var2 = 2 # ... and this? Maybe protected? Short answer: Both of them are ways of indicating a variable is private. Both of them are private by convention only. _var requires no hoops to circumvent. __var variables are mangled, but you can access them by jumping through simple hoops. Consider this: #!/usr/bin/env python class Test: def __init__(self): self.__var1 = 1 # I think this is a private attribute self._var2 = 2 # ... and this? Maybe protected? def show(self): print self.__class__.__name__ for k, v in self.__dict__.items(): print "\t%s = %s" % (k, v) def dosomethingwithvar1(self): self.__var1 += 1 class SubclassOfTest(Test): def dosomethingwithvar1(self): try: self.__var1 += 1 except AttributeError: print "expected" self._Test__var1 += 1 t = Test() print t._var2 try: print t.__var1 except AttributeError: print "expected error" print t._Test__var1 t.show() t.dosomethingwithvar1() t.show() s = SubclassOfTest() print s._var2 try: print s.__var1 except AttributeError: print "expected error" print s._Test__var1 s.show() s.dosomethingwithvar1() s.show() - From sholden at holdenweb.com Mon Sep 16 07:47:06 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 16 Sep 2002 07:47:06 -0400 Subject: [ANN] PySQLite 0.3.0 released References: Message-ID: "Bob X" wrote ... > sismex01 at hebmex.com wrote: > > > > > > > Yeesh! You had to quote the whole message just to > > add two words? > > > > :-( > > > > -gus > > My bust on that one. I usually do a like I did above. Sorry bout dat. > > On that note...your two paragraph sig is okay right? ; ) > No, his two-paragraph "sig" is a PITA, but probably it's not aa sig but something that his company's mailer sticks on the end of all message quite gratuitously, just so some corporate lawyer can sleep better (fancying his ass is covered). regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From jim.vickroy at noaa.gov Tue Sep 3 16:32:26 2002 From: jim.vickroy at noaa.gov (j vickroy) Date: Tue, 3 Sep 2002 14:32:26 -0600 Subject: Tk BLT / Pmw 1.1/ Python 2.2.1/ Ms Windows Message-ID: Hello, So far, I have not been able to get the Tk BLT extension package to work with Python 2.2.1 and Pmw 1.1. I have tried placing the BLT24.dll various places, but the error message, when running a sample script, is always: TclError: invalid command name "::blt::graph" Any suggestions would be appreciated. Thanks. From herald at ns1.nabitel.com Mon Sep 30 00:42:37 2002 From: herald at ns1.nabitel.com (herald at ns1.nabitel.com) Date: Mon, 30 Sep 2002 13:42:37 +0900 Subject: (ad)Strong WebRobot/eMailId Collector: Free Download ! Message-ID: Sorry for interrupting you - click refuse for no more mail... ? - Welcome to NabiTel's software products and portal services - Software Products Web Robot: also called web spider or web crawler, collects useful web page informations by navigating world wide web sites. Download free trial version now ! eMail ID Collector: Collects email ids publicly opened on various web pages, with good intention. Download free trial version now ! Portal Services Web Portal: Do you have your own home page and want to broadcast it all over the world ? Register your home page to NabiTel Portal Now !! (nabi=a butterfly) Register your home page now, it's free ! Automobiles: Do you want to sell or buy automobiles ? Cars, trucks, limos, airplanes, ships,.... All That Cars are here ! Register your vehicles now, it's free ! Computers: Do you want to sell or buy computers ? PCs, printers, scanners, servers, mainframes, .... All That Computers are here ! Register your computers now, it's free ! Food & Restaurants: Are you seeking for a nice place to eat ? Or do you run a restaurant ? Foods of the world, restaurants of the world, .... All That Foods are here ! Register your restaurant now, it's free ! Have a nice day. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From magnus at thinkware.se Sun Sep 29 18:58:33 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Mon, 30 Sep 2002 00:58:33 +0200 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: <3D978599.1040206@thinkware.se> Steve Holden wrote: > Of course, none of this is necessarily an argument that f-p is the *best* > representation for money, but I'm always amused to see people arguing > against it on general grounds when it's perfectly acceptable for many such > purposes *when correctly used*. My opinion is that Python has a lot of the features required to become "the next COBOL". Yes, I admit it sounds horrible, I hate COBOL as much as anybody ;) but try to understand what I mean. Python has the potential to be used to quickly and in a practical way build millions of applications and tools by people who aren't always from a CS, math or engineering background. Python also has the potential to become the next BASIC--a simple language for education, autodidacts and power-users. It can also become the next Pascal, but I don't think we need to change any language features for that. But to suit beginners and...well, amateurs...we need to follow the principle of least surprise. It IS surprising for a lot of people that >>> 4/5 0.80000000000000004 You know that Steve, you see it here on c.l.py now and then. It IS surprising for some people that for some numeric values of 'w': >>> 1+w+w+w+w == w+w+w+w+1 0 And >>> 4/5 0 was certainly surprising for many, and that was changed. The other big surprise was obviously >>> w = 5 >>> print W Traceback (most recent call last): File "", line 1, in ? NameError: name 'W' is not defined but that I think, is not so difficult to explain: We don't consider w and W to be the same thing. It's a design decision, and it could have been the other way. Guido choose this way, just like he choose = for assignment and == for equality, instead of := and = as in Pascal. End of story. But we can't explain why floating point arithmetic works the way it does without going into details the groups I refer to feel that they shouldn't have to understand. It's a bit like demanding that a car driver understands the physics and chemistry of combustion engines. You can't sell a lot of cars if you need a degree in science to drive them... Or, to put it the other way around, you can sell a lot more cars if people can drive them without a B.Sc, and you can "sell" Python to a lot more people if they don't need a B.Sc. to understand it... On the other hand, I feel that when you make the tool so simple that it can be handled by any fool, any fool will be put in charge of the tool, and regardless of the quality of the tool, they will make a mess because they lack the required thinking ability. In other words, we who actually understand computers and problem solving will have to clean things up. But a) I'd rather fix real logical problems in the business sphere than correct trivial programming blunders, and b) We shouldn't make life more difficult than needed for those who are clever enough, but just don't have the expertize in our field. Finally, c) we don't think that pen and paper ought to be difficult to use, so that people need to learn a lot of things unrelated to the ideas they want to put in writing. Maybe this not such a big issue as I sometimes think it is, but I do feel that Python is way ahead of the competetition from a pedagogic perspective in most cases, but this is one where it's...average. Perhaps the right trade-off is still to educate the programmers, and to build tools or routines to prevent problems. But I think the issue is worth discussing. It seems to me that a really smooth handling of dates, times and decimal numbers would make Python even more useful for most people who don't program today, but could benefit from it if they did... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus at thinkware.se From chris.gonnerman at newcenturycomputers.net Mon Sep 30 22:12:00 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 30 Sep 2002 21:12:00 -0500 Subject: Decimal arithmetic, with example code References: Message-ID: <001601c268ef$f79980e0$ba01010a@local> Ok, here it is. I have written some Python code which displays the problems with float (floating binary) arithmetic applied to monetary amounts. Run this, and many the places where the simple percentage times amount calculation in floating binary falls down will become obvious. You need the fixedpoint.py module installed to run this. http://fixedpoint.sourceforge.net (code attached) Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: fp-test.py URL: From tdelaney at avaya.com Wed Sep 11 23:52:46 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 12 Sep 2002 13:52:46 +1000 Subject: "str.contains(part)" or alternatives? Message-ID: > From: Joseph A. Knapka [mailto:jknapka at earthlink.net] > > So in 2.3, can I do this and get the expected result? > > >>> "" in "abc" > 1 Yes - this has been hotly debated and defined as true. > >>> for subst in "abc": > ... print subst > ... > > a > ab > abc > b > bc > c No. Iterating over a string is defined to return each single character in turn. Remember: for subst in "abc": is equivalent to for subst in iter("abc"): and iter("abc") returns "a", "b", "c" whilst if subst in "abc": is equivalent to if "abc".__contains__(subst): (falling back to if subst in iter("abc") if "abc" does not define __contains__) and str.__contains__ performs a substring match. Tim Delaney From peter at engcorp.com Tue Sep 17 08:32:06 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 17 Sep 2002 08:32:06 -0400 Subject: faster way for adding many strings References: Message-ID: <3d8720b8$1@news.sentex.net> Ulli Stein wrote: > Hi, > > What is the faster way: appending many strings to a list and then joining > them, or writing to > StringIO and then getvalue()? Alex' detailed response notwithstanding, there's another usual answer to your question: "Premature optimization is the root of all evil in programming" (D. Knuth) It means you usually shouldn't care which is faster until (a) your software is working fully, and (b) you have profiled the code and determined that in fact you have an unacceptable bottleneck which must be optimized to meet your requirements. Don't get me wrong, there _are_ times to optimize. You just shouldn't see them very often... and life is simpler that way. :) -Peter From kroc at blueyonder.co.uk Tue Sep 24 04:18:45 2002 From: kroc at blueyonder.co.uk (Keith) Date: Tue, 24 Sep 2002 08:18:45 GMT Subject: Elementary confusion References: Message-ID: <874rcf242i.fsf@smtp.blueyonder.co.uk> >>>>> "Mark" == Mark McEahern writes: Mark> This is a FAQ. Please read the FAQ. This has to do with Mark> floating point math: Mark> http://www.python.org/doc/FAQ.html#4.98 OK - read it. Thanks. I am reassured that it is not me, my machine, or a bug. However it has rapidly become apparent that there are all sorts of pitfall waiting me :-( I guess thats where the fun is! :-) -- Keith. From cbrown at metservice.com Thu Sep 5 16:38:11 2002 From: cbrown at metservice.com (Colin Brown) Date: Fri, 6 Sep 2002 08:38:11 +1200 Subject: Project idea Message-ID: <3d77c0b4$1@news.nz.asiaonline.net> Hi If you are interested in a Windows platform project for automated testing then read on. There is an excellent freeware package "AutoIt" available from http://www.hiddensoft.com/AutoIt/ that provides a DLL module that could be readily interfaced to Python. "AutoIt" is a simple tool that can simulate key presses, mouse movements and window commands (maximize, minimize, wait for, etc.) in order to automate any windows based task (or even windowed DOS tasks). Combining these features with say the ability to produce checksums of snapshotted screen frames for test comparisons would provide the basis for a nice GUI regression test rig. Unfortunately I do not have the time to follow up on this myself so I though I would pass it on. Colin Brown PyNZ From joconnor at cybermesa.com Fri Sep 6 23:11:13 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Sat, 07 Sep 2002 03:11:13 GMT Subject: Larry Wall's comment on python... References: <3D7958DB.50903@nospam.free.fr> Message-ID: <3d796e2f.44509032@news.cybermesa.com> On Fri, 06 Sep 2002 15:41:52 -0500, "Bradley D. Larson" wrote: >That is what is nice about Vi paren,bracket matching! Vi, Emacs, half a hundred other code editors Jay O'Connor joconnor at cybermesa.com http://www.cybermesa.com/~joconnor "God himself plays on the bass strings first, when he tunes the soul" From see_reply_address at something.invalid Tue Sep 24 22:41:13 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 25 Sep 2002 14:41:13 +1200 Subject: Python Compiling References: Message-ID: <3D912249.6040409@something.invalid> > Jacek Generowicz writes: > > Results from one language don't transfer to another. I don't know > (really) why Lisp compilers work that well, and what restrictions on > the Lisp language had to be made to make them work well. I think Lisp compilers work by a combination of help from optional declarations, and heroic amounts of type inference. Also, Python is even more dynamic than Lisp in some ways -- namespaces can have names added and removed at run time, built-in operators can be overloaded, etc. You can hardly rely on *anything* staying the same from one moment to the next in Python! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From rolf.kalbermatter at citeng.com Mon Sep 2 10:41:59 2002 From: rolf.kalbermatter at citeng.com (Rolf Kalbermatter) Date: Mon, 2 Sep 2002 16:41:59 +0200 Subject: version independant object usage counting In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Martin v. Lowis > Sent: Monday, September 02, 2002 3:38 PM > To: python-list at python.org > Subject: Re: version independant object usage counting > > > "Rolf Kalbermatter" writes: > > > However although this loader works quite fine now, I found out that > > I gained little with it because the current Python architecture is > > not really designed to link dynamically to it. > > Yes, this is the case - mainly because the API changes in slight ways, > and because therefore, extension modules explicitly link to > pythonxy.dll. I realize that extension modules might get other problems with API changes and that this is more likely to be a problem than the layout of the object interface. > > The problem arises in fact with the refcounting of Python > > objects. The macros Py_INCREF and Py_DECREF access directly > > structure members in the object layout and this layout is different > > for debugging and non debugging versions and potentially different > > between Python versions as well. > > That is only a minor problem: those macros are correct across all > released Python versions, back to 1.4 or earlier. But there is a serious difference between the DEBUG and NON-DEBUG PyObject_HEAD structure layout which I would like to not have to worry about if possible. As I'm really embedding Python (in this case into LabVIEW), by trying to access the whole Python core as version independant as possible I want to make it unimportant if the Python DLL is compiled as DEBUG or non DEBUG or actually what version it really is. > > Is there a specific reason that these two API functions are not > > available and one is forced to use the according macros to do proper > > refcounting, or did I miss those functions completely? > > Nobody has proposed to introduce them, because there is no need to do > so, and because other ABI changes break the ABI more often - INCREF > and DECREF have never done so, and it is unlikely that they ever will. > > > Any thought about this? > > Feel free to submit a patch to SourceForge. However, you might want to > consider the following issues: Does anyone see any problems with this code? RCS file: /cvsroot/python/python/dist/src/Include/object.h,v retrieving revision 2.111 diff -c -2 -r2.111 object.h *** object.h 8 Aug 2002 20:55:20 -0000 2.111 --- object.h 2 Sep 2002 13:44:46 -0000 *************** *** 347,350 **** --- 347,352 ---- /* Generic operations on objects */ + PyAPI_FUNC(int) PyObject_IncRef(PyObject *); + PyAPI_FUNC(int) PyObject_DecRef(PyObject *); PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int); PyAPI_FUNC(void) _PyObject_Dump(PyObject *); diff -c -2 -r2.192 object.c *** objects/object.c 24 Aug 2002 06:31:34 -0000 2.192 --- objects/object.c 2 Sep 2002 13:51:37 -0000 *************** *** 166,169 **** --- 166,191 ---- int + PyObject_IncRef(PyObject *op) + { + if (op) { + Py_INCREF(op); + return op->ob_refcnt; + } + return 0; + } + + int + PyObject_DecRef(PyObject *op) + { + if (op) { + int refcnt = op->ob_refcnt; + Py_DECREF(op); + if (refcnt > 1) + return op->ob_refcnt; + } + return 0; + } + + int PyObject_Print(PyObject *op, FILE *fp, int flags) { This interface explicitedly would not require anymore to import _Py_Dealloc and _Py_RefTotal which are only implemented and therefore exported from DEBUG core DLLs. It would still be anybodies own decision if to use the existing macros or the according accessor functions instead. > - various places assume presence of the ob_type field: > * the Py*_Check functions (e.g. PyList_Check) directly access the > ob_type field. Hmm. I see your point in this. However I check this by having a private PyObject_MyCheckType defined which accesses the ob_type field over the PyObject_Type function and then checking for specific type through PyObject_MyCheckType(op, &Py_). > * PyObject_INIT relies on initializing the object members. > - PyType_HasFeature relies on the position of the tp_flags field I'm not using these function at all until now. May have to do so when I start to add an extension module however? > - various accessor macros rely on the internal structure, e.g. > * PyTuple_GET_ITEM > * PyString_AS_STRING > * ... I try to avoid them and use the according function interface instead such as PyString_AsString() which was successful until now. Rolf Kalbermatter CIT Engineering Nederland BV tel: +31 (070) 415 9190 Treubstraat 7H fax: +31 (070) 415 9191 2288 EG Rijswijk http://www.citengineering.com Netherlands mailto:rolf.kalbermatter at citeng.com From maurice at akst.tn.tudelft.nl Fri Sep 13 08:48:14 2002 From: maurice at akst.tn.tudelft.nl (Maurice van de Rijzen) Date: Fri, 13 Sep 2002 14:48:14 +0200 Subject: Evaluating strin composed of multiple parts? Message-ID: Dear all, I'm using numpy. In numpy one can take a part of a multi array just as in matlab. partArray=totalArray[1:10,1;10,:,:,: Now I've encounterd the following problem. I'm using the followoing code: class SubDataMatrix_5D: def SetInput(self,DataInput): self.DataInput=DataInput def SetDimensions(self,dim1,dim2,dim3,dim4,dim5): self.Dim1=dim1 self.Dim2=dim2 self.Dim3=dim3 self.Dim4=dim4 self.Dim5=dim5 def CreateSubMatrix(self): self.Sub=self.DataInput[eval(self.Dim1),eval... (self.Dim2),eval(self.Dim3),eval(self.Dim4),... eval(self.Dim5)] def GetOutput(self): return self.SubMatrix temp2=SubDataMatrix_5D() temp2.SetInput(temp.GetOutput()) temp2.SetDimensions("1:10","1:10","1:10","1:2","1:2") temp2.CreateSubMatrix() Doing this gives the following error: self.SubMatrix=self.DataInput[eval(self.Dim1),eval(self.Dim2),eval(self.Dim3 ),eval(self.Dim4),eval(self.Dim5)] File "", line 1 1:10 ^ I know there goed something wrong with the strings but I have no clue of how to solve it. Preferrebly I would like to set the dimensions as follows: temp2.SetDimensions(1:10,1:10,1:10,1:2,1:2) Can someone please help me? Maurice From igetenoughspamalreadythanksjlr at doctor.com Mon Sep 2 07:23:18 2002 From: igetenoughspamalreadythanksjlr at doctor.com (John La Rooy) Date: Mon, 02 Sep 2002 21:23:18 +1000 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <1030962064.628232@ampungk.ozonline.com.au> Message-ID: <1031008966.343893@ampungk.ozonline.com.au> Carl Banks wrote: >>It would be more likely to look like this (I haven't put too much >>thought into this) > > > No kidding. > > > >>"anything,anything,anything,same_as_3rd,same_as_2nd,same_as_1st" >>or would you like to suggest something else? > > > How about: > > pattern = Group(Any()) + Group(Any()) + Group(Any()) \ > + GroupRef(3) + GroupRef(2) + GroupRef(1) > Err symantically that's exactly the same as the re and my suggestion only the syntax is different. It's still nothing like saying pattern = "6 character palindrome" John From marklists at mceahern.com Fri Sep 20 12:32:19 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 20 Sep 2002 11:32:19 -0500 Subject: isFloat: Without Exception-Handling In-Reply-To: Message-ID: For what it's worth, here's a slightly tweaked version of the test harness. It shuffles the function list before testing and does multiple test runs and then averages the results. I'm posting this mainly so that I can archive this on this list without having to bother figuring out where to put it on my own hard disk. isFloatExcept comes out pretty consistently almost twice as fast as the RE-based approach. Now, wouldn't I feel real dumb to find Python comes with a builtin isfloat? If not, are there other alternatives for doing this? Easy come, easy go. Cheers, // m #!/usr/bin/env python import re import random import operator from time import clock # Compile up front. floatPattern = re.compile(r"^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$") def isFloatExcept(s): try: float(s) return True except (ValueError, TypeError), e: return False def isFloatRE(s): floatRE = r"^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$" return re.match(floatRE, str(s)) is not None def isFloatRECompiled(s): return floatPattern.match(str(s)) is not None def time_it(fn, test_data, n): time_in = clock() for x in xrange(n): for (s, expected) in test_data: actual = fn(s) assert actual == expected time_out = clock() return time_out - time_in def show(fn, r, fastest): avg = average(r) ratio = (avg / fastest) * 100 print "%-20s %1.3f %2.f" % (fn.func_name, average(r), ratio) def average(seq): return reduce(operator.add, seq) / len(seq) def test(): test_data = [(1.2, True), (1, True), (-1, True), (1e+10, True), ("1e-10", True), ("banana", False), ("5j", False), (4+0j, False), (isFloatExcept, False), (__import__, False), (clock, False)] test_runs = 10 n = 100 results = {} functions = [isFloatExcept, isFloatRE, isFloatRECompiled] for t in xrange(test_runs): random.shuffle(functions) for fn in functions: r = time_it(fn, test_data, n) results.setdefault(fn, []) results[fn].append(r) keys = results.keys() keys.sort(lambda x, y: cmp(average(results[x]), average(results[y]))) fastest = average(results[keys[0]]) print "%-20s %s %s" % ("name", "clock", "cmp") for fn in keys: show(fn, results[fn], fastest) if __name__ == "__main__": test() -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: junk.py URL: From remailer at xganon.com Fri Sep 6 03:31:08 2002 From: remailer at xganon.com (xganon) Date: Fri, 6 Sep 2002 02:31:08 -0500 Subject: Timothy Rue Message-ID: <898662b7d85d2c966c0bd45d563d5d2d@xganon.com> Does Timothy Rue still Troll here? If not, how did you get rid of him? We need him out of our group now, maybe we could get him into a Perl group for a while and let them deal with him? (: --- This post was anonymized at http://www.xganon.com --- From dsavitsk at e-coli.net Wed Sep 18 00:50:34 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Wed, 18 Sep 2002 04:50:34 GMT Subject: COM object registration References: Message-ID: "Mark Hammond" wrote in message news:T_Rh9.17227$Ee4.51953 at news-server.bigpond.net.au... > dsavitsk wrote: > > if the module below is run from the command line, it registers and works > > fine. if, however, it is imported and the register() method is executed it > > does not work (giving a 'localserver' error). > > What doesn't work? Registration or subsequent use of the object? Can > you be more specific about the error you got, or else attach code I can > run without modification to see the error. > > Thanks, > > Mark. > here are 2 modules. call the first anything, I called the second REGISTER_MODULE2.py for the example. (I tend to do anything COM related in caps). Place them both on the path on one computer, and place the second on a second computer. the problem is illustrated below. # -------- 1st ------ "module to register Python COM components" import pythoncom class regmodule: _reg_clsid_ = '{7E63BF81-E120-4CD9-A9AE-13B5B6BB4ADB}' _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER _public_methods_ = ['REGISTERM'] _reg_progid_ = 'this_is.MODULE_REGISTER' def REGISTERM(self, mod): exec('import ' + str(mod) + ' as mr') mr.register() if __name__ == '__main__': import win32com.server.register win32com.server.register.UseCommandLine(regmodule) # ------------------- # -------- 2nd ------ import pythoncom class regmodule2: _reg_clsid_ = '{2B1120DD-83F8-4850-91F6-B4F9601C16B7}' _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER _public_methods_ = ['GET_VALUE'] _reg_progid_ = 'ecp.MODULE_REGISTER2' def __init__(self): self.x = 0 def GET_VALUE(self): self.x += 1 return self.x # it needs to do something :-) def register(): import win32com.server.register win32com.server.register.UseCommandLine(regmodule2) if __name__ == '__main__': register() # ------------------- 1. register the first on computer 1 2. register the second on computer 2 3. do the following on computer 1 # instance the server >>> f = win32com.client.Dispatch('this_is.MODULE_REGISTER') # use it to locally register other server >>> f.REGISTERM('MODULE_REGISTER2') # instance the second on server # my server is named camus >>> a = win32com.client.DispatchEx('ecp.MODULE_REGISTER2', 'CAMUS') # works fine >>> a.GET_VALUE() 1 >>> a.GET_VALUE() 2 >>> del a # try instance it locally >>> a = win32com.client.Dispatch('ecp.MODULE_REGISTER2') Traceback (most recent call last): File "", line 1, in ? File "C:\Python\win32com\client\__init__.py", line 92, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python\win32com\client\dynamic.py", line 81, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147467259, 'Unspecified error', None, None) if you go back and regularly register the second module locally (double clicking or what not) the local instancing will work fine. In some sense, this might be useful to only allow remote use, but i suppose this can be done by distributing a shell of the module as well. Thanks, -doug From pedronis at bluewin.ch Tue Sep 17 15:02:51 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Tue, 17 Sep 2002 21:02:51 +0200 Subject: Calling Python from C# - please help References: <6de16ac9.0209130508.5d1b56c6@posting.google.com> <0iCg9.2350$Ee4.6516@news-server.bigpond.net.au> <3D82FA5B.3050003@mxm.dk> <3%Dh9.15217$Ee4.45118@news-server.bigpond.net.au> Message-ID: <3d877db8_5@news.bluewin.ch> Mark Hammond wrote in message 3%Dh9.15217$Ee4.45118 at news-server.bigpond.net.au... > Syver Enstad wrote: ... > > > > Now that J# (Java .NET) has been released, I was wondering about the > > possibility of compiling Jython with the MS J# compiler to create a > > Jython .NET. Has anyone considered the possibility? > > I'd love to see some Jython technology used for .NET. At the time > Python.NET started, there was very strict NDA, so discussing the project > with jython-dev, or even python-dev, was taboo. Greg Stein and I made a > pragmatic decision to go with the p2c tool as a framework over jython as > we alrady had experience with p2c and didnt have the time-lines to > understand jython before embarking on our pilot code. How were you going to support eval and exec? For the moment the unload granularity of .NET is AppDomains only and only upon explicit request, and types/modules/assemblies are not garbage collected but simply live as much as the AppDomain, that's OK for static languages, or environments with a clear run/design time distinction (one can setup an AppDomain and tear it down for each run-cycle), or for running scripts in isolation but not if one wants IL/JIT speed for a enviroment that allows for redefinitions and eval, ... In Jython we create Java bytecode and dynamically load classes for all the code, also eval code because in Java classes are elegible for garbage collection. In .NET it seems one needs a pure interpreter that does not compile to IL for exec and eval support, and that seems what JScript does for jsc compiled code containing eval, that means the script is compiled but the evaluated code is only interpreted, otherwise a long running process using eval could go out of memory. That's something people wanting to write a feature complete impl of Pyhton for .NET should consider or wait MS to implement a more dynamic-environment-friendly unload policy. This is also an issue versus runtime subclassing of framework classes, Jython creates distinct concrete Java subclasses each time a Java class is subclassed, under .NET one should probably limits this ... regards. From gerhard.haering at opus-gmbh.net Fri Sep 20 07:32:20 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 20 Sep 2002 11:32:20 GMT Subject: M$SQL connections from linux References: <1032528860.599940@news.etel.ru> Message-ID: Vasiliy A. Chernoivan wrote: > Hello all > Is there some module for python which performs the task? > Is it possible at allto access data under M$SQL from linux machine? What /I/'d do first is ask Google, like with: http://groups.google.de/groups?q=group%3Acomp.lang.python+microsoft+sql+server+linux&ie=UTF-8&oe=UTF-8&hl=en&btnG=Google+Search I remember reading here that Dave Cole's Sybase module can used to access SQL Server in combination with the FreeTSD library. -- Gerhard From wlfraed at ix.netcom.com Wed Sep 25 23:19:37 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 25 Sep 2002 20:19:37 -0700 Subject: transform strings list in a int lists or other type??? References: Message-ID: <9cutma.ov3.ln@ix.netcom.com> jubafre at brturbo.com fed this fish to the penguins on Wednesday 25 September 2002 04:29 pm: Haven't you asked a version of this /each/ day for the last few days? > Can i tranform a list of strings in a list of int, > or other type in python??? > and also write in a file? I think the open(path,'wb') in __builtin__ > dont?t write in a file other types, just strings, rigth??? > ALL I/O in Python is effectively a stream of bytes. The "b" option on the open ONLY controls the interpretation of line-endings. IE, on Windows reading a file with "b" means you see both the and the character; without the "b" (normal mode) the is converted to just a "newline" () for internal use. To write a "binary" file requires you to either manipulate /each/ byte of your data, OR to use the struct module to pack your data into a string (full of unprintable characters) which can be written. import struct ots = struct.pack(">2L2H12s30pB", 0x10346f89, 563993, 0x0d0a, 32767, "Some Text", "More text with a count byte", ord("\r") print ots Lots of unprintables in that... Cut&Pasted from the terminal window: 4o? ore text with a count byte print repr(ots) '\x104o\x89\x00\x08\x9b\x19\r\n\x7f\xffSome Text\x00\x00\x00\x1bMore text with a count byte\x00\x00\r' I used the ">" in the pack format string to ensure that the byte sequence for output is "big-end first" so the output representation is the same as the input numbers -- default on my machine is "little-end first". Compare: 0x10346f89 to the output... You have to take into account that printable characters show up as single byte characters rather than an encoded \xnn set. 0x10 34 6f 89 \x10 4 o \x89 -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From k.robert at gmx.de Thu Sep 26 16:39:36 2002 From: k.robert at gmx.de (Robert) Date: Thu, 26 Sep 2002 22:39:36 +0200 Subject: http file upload from Python (multipart/formdata) how-to? Message-ID: <3d937091$0$181$9b622d9e@news.freenet.de> want to upload file data (multipart formdata) - same as upload from web-browser urllib.urlencode + urlopen takes only simple name/value tuples how do I render multipart formdata ? Robert From syver-en+usenet at online.no Mon Sep 9 17:22:52 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Mon, 09 Sep 2002 21:22:52 GMT Subject: win32com.client.gencache and py2exe References: Message-ID: "Thomas Heller" writes: > It's already fixed in CVS. It should be sufficient if you replace > the existing build_exe.py by the new one which you can grab > from the CVS repository: > http://cvs.sourceforge.net/cgi-in/viewcvs.cgi/py2exe/py2exe/py2exe/build_exe.py Cool, I'll check it out. -- Vennlig hilsen Syver Enstad From sholden at holdenweb.com Fri Sep 13 07:43:31 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 13 Sep 2002 07:43:31 -0400 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> <3D7FFC43.10002@something.invalid> Message-ID: <%ckg9.3117$WV.1764@fe03> "GerritM" wrote ... > "Russell E. Owen" schreef ... > <...snip...> > > True. It would help if the command callback sent an arguement that > > identified the widget (making it look a bit more like an event binding). > > In any event, it doesn't and command is unfortunately still the best way > > to handle button widgets. > > In a recent thread it was pointed out that you can also bind to s function > of a specific object instance. Out of the top of my head: > > Class A: > def printarg( self, arg ): > print arg > > anA = a() > functionBoundToInstance = anA.printarg > > functionBoundToInstance("Hello Python") > > Hello Python > > this would work also for widgets, command = aWidget.activate > It also works for widget subclasses, which means that you have "self" available to access various attributes of the widget. But it still doesn't get you the event data, which only get explicitly passed when you establish a binding for an event rather than using the command argument. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From astrophels at yahoo.com Fri Sep 6 12:48:40 2002 From: astrophels at yahoo.com (Micah Mayo) Date: Fri, 06 Sep 2002 16:48:40 GMT Subject: Getting a proccesses ID References: Message-ID: Sean 'Shaleh' Perry wrote: > On Friday 06 September 2002 08:05, Micah Mayo wrote: > >>Hi, >> >>I'm writing a little tool for SysAdmins on FreeBSD - I'm trying to make >>it as portable as possible(as far as the unices go), and have come upon >>a problem - one of the things this tool does is restarts various deamons >>on the system, in order to do that I have to send a killsignal to the >>pid. The problem is getting the process id - right now I've got a hack >>using ps, grep, and awk, which I doubt will translate well to other >>flavors of *nix because they all seem to have their own method of >>delivering info via ps. Can anyone tell me a cross platform way of >>grabbing a particular processes ID >> >>Here's what I'm doing now, by the way: >> >>pid = os.popen("ps -x | grep sshd | grep -v grep | awk '{ print $1 }'") >>pid = pid.atoi() > > >>>>import os >>>>os.getpid() >>> > 29421 > > (-: > Ah, but os.getpid get's my pid, I need to get another programs, and in fact, several other program's pid. :) Thnx, Micah From marklists at mceahern.com Wed Sep 25 10:50:38 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 25 Sep 2002 09:50:38 -0500 Subject: List/Tuple bug or feature? In-Reply-To: <87ofamgnbh.fsf@nospam.eml.cc> Message-ID: [Mahesh Padmanabhan] > It is simply a list of constants so I could not generate it > automatically. I then use this list to filter out one element of the > list using the builtin filter function. I don't think I can break down > the list so that I can view missing commas easier because all > constants seem to logically group together. Something like this: > > constantList = [1,2,3,4,5] > > filteredList = filter(some_function, list) How does the above example resemble your original problem, though? You said it's a list of constants. Are they stored in a file? In what format? Do you see where my questions are leading? I'm basically trying to find out how you happened to get: ['constant1', 'constant2' 'constant3', 'constant4', ..., 'constantn'] ^ \-- missing comma Cheers, // mark From whisper at oz.net Wed Sep 25 02:51:00 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 24 Sep 2002 23:51:00 -0700 Subject: PythonWin CVS problem In-Reply-To: Message-ID: I'm using the same repository I've been using for the past 6 months or more: :pserver:anoncvs at cvs.pythonpros.com:/home/cvsroot Just tried it again and got the same: "permission denied". David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Dilton McGowan II > Sent: Tuesday, September 24, 2002 20:30 > To: python-list at python.org > Subject: Re: PythonWin CVS problem > > > David LeBlanc wrote: > > > Second day it's inaccessable with "permission denied" > > > > David LeBlanc > > Seattle, WA USA > > Are you using cvs.pythonpros.com? It worked for me yesterday and > again just > now. They seem to have the latest source. Just a friendly suggestion. > -- > http://mail.python.org/mailman/listinfo/python-list From kkuroda at crl.ucsd.edu Tue Sep 3 12:31:37 2002 From: kkuroda at crl.ucsd.edu (Kow Kuroda) Date: Tue, 3 Sep 2002 09:31:37 -0700 Subject: RedHat 7.3 and Python2.2.1 In-Reply-To: <3d74a6e8@news.sentex.net> Message-ID: <9DF2DF67-BF5A-11D6-8D0D-00050287C0A6@crl.ucsd.edu> On Tuesday, September 3, 2002, at 05:11 , Peter Hansen wrote: > Kow Kuroda wrote: >> As a last thought, doesn't Red Hat have different versions of the 7.3 >> distribution? > > Maybe you installed a beta? I don't know because I just used the installer available at an institute I' m working, and I'm back to RHL 7.2 now. > I'm pretty sure there's only one release version to date. I could be > wrong. The one I installed I took from > their web site just two weeks ago. uname says it's version: > > 2.4.18-3 #1 Thu Apr 18 07:37:53 EDT 2002 i686 > > and /etc/redhat-release says "release 7.3 (Valhalla)" I'm not on 7.3 now, so I can't tell exactly which version/release it was. Nevertheless, it was surely release 7.3 Valhala, though the kernel version was different, I suspect. > > Oh well, there's no telling with software. :) Very true ;-) kOw From joconnor at cybermesa.com Tue Sep 3 11:53:42 2002 From: joconnor at cybermesa.com (Fearless Freep) Date: 3 Sep 2002 08:53:42 -0700 Subject: Why it is so dramatical? References: <20020902.104707.1789376348.1554@cybermesa.com> Message-ID: <7d3dc526.0209030753.27bf08a8@posting.google.com> "Bo M. Maryniuck" wrote in message news:... > On Monday 02 September 2002 05:47, Jay O'Connor wrote: > > As a result Perl is much faster at some kinds of operations than > > Python, and vice-versa. > > Yeah, actually, but I just would like to find some optimal Python solutio > n :) Well..is it more efficient to treat it as a list of characters? >>> x = " " * 10 >>> x = list (x) >>> y = 'test str' >>> x[0:len(y)] = list (y) >>> z = 'another test string' >>> x.extend(list(z)) >>> s =''.join (x) >>> print s 'test str another test string' Treating a string as a list of character elements would allow you to append to it and change the internals. May be an improvement in performance. This assumes you are having a noticeable performance problem with concatenating strings. Beware of premature optimization. Just because an fairly simple operation in one language is slower than the equivalent in another language doesn't mean that the program as a whole will be slower enough to matter Take care, Jay From fromclay at maxitec.co.za Tue Sep 3 10:36:40 2002 From: fromclay at maxitec.co.za (Morne) Date: Tue, 3 Sep 2002 16:36:40 +0200 Subject: heeelp Message-ID: <001f01c25357$53cb7ca0$2500a8c0@maxitec.co.za> Could someone please help me with this? Im really new to any kind of programming If posible would you be able to answer in detail. Thanx morne is it wrong of me to send the ppp.log file to just anyone? HERE IS WHAT I HAVE: import re import string secondsMatcher=re.compile("Connect time: (\d+) secs") def getStuff(file): closeline = 0 errorcount = 0 secondscount = 0 connectcount = 0 data_outcount = 0 data_incount = 0 ppplist = file.readlines() for line in ppplist: if string.find(line,"LayerUp") >= 0: print "found connect" connectline = string.split(line) connectcount = connectcount + 1 elif string.find(line,"ERROR") >= 0: print "found error" errorcount = errorcount + 1 elif string.find(line,"Connect time") >= 0: print "found close" connectSecs=secondsMatcher.search(line).group(1) print "Connected for",connectSecs closeline = string.split(line) secondscount = secondscount + string.atoi(connectSecs) def main(): f=open("C:/my documents/ppp.log","r") getStuff(f) return None if __name__=="__main__": main() THIS IS WHAT I NEED THE PROGRAM TO DO: I want the program to read the attached ppp.log file and give me the following type of report: PPP Log file summary for 5 Jul 2002 ----------------------------------- Jul 5 18:15:01 Connected to internet (IP 155.239.150.146) Jul 5 18:18:08 Closed connection. ( Connect time: 197 secs: 5091 octets in, 1864 octets out ) ----------------------------------- Successful connections: 5 Failed connections: 2 Total time online: 456 seconds Total data in: 66576 octets Total Data out: 66349 octets -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ppp.log Type: application/octet-stream Size: 33059 bytes Desc: not available URL: From sismex01 at hebmex.com Wed Sep 4 09:36:57 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 4 Sep 2002 08:36:57 -0500 Subject: Daemonize? Message-ID: Sorry to ask here, but I don't have any "unixy" python documentation at hand. Normally, I put an app into "daemon" mode, by first forking, then reopening stdin/out/err to /dev/null, and then forking again. Works good enough for my purposes. But, am I right? Is this the correct way to do this? Also, I can't find any "reopen" in python to apply to sys.stdin/out/err. Any help will be most appreciated. Thanks. -gus -- Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From marklists at mceahern.com Wed Sep 18 07:16:43 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 18 Sep 2002 06:16:43 -0500 Subject: Parsing Logs...Please Advise In-Reply-To: Message-ID: [sensei zeki] > I am looking for a good tool to parse system logs. You provided a sample log, which is great. How about fleshing out what you mean by 'parsing'? I.e., what output/results do you want? Or are you hoping we fill in that blank for you? Cheers, // m - From TOGLIMIcuni at programmazione.it Fri Sep 20 10:19:01 2002 From: TOGLIMIcuni at programmazione.it (Antonio Cuni) Date: Fri, 20 Sep 2002 14:19:01 +0000 Subject: Copy with __slots__ References: Message-ID: Alex Martelli wrote: > This doesn't deal with inherited __slots__. [cut] you're right, I couldn't think of it :-( > Some care > is needed, though (I can think of several possible anomalies). what kind of anomalies? Anto -- "Computer science is not about computers any more than astronomy is about telescopes." -- EW Dijkstra From tdelaney at avaya.com Wed Sep 4 19:16:12 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 5 Sep 2002 09:16:12 +1000 Subject: How to force built-in commands over imported. Message-ID: > From: Simon Brunning [mailto:SBrunning at trisystems.co.uk] > > You are, I assume, importing 'os' as follows: > > from os import * > > *Don't* *do* *this*. Use: > > import os > > instead. There *are* reasons for using the former method, but > they are few > and far between. The latter form should always be the one you > use unless you > have a good reason. Indeed. The only time I have *ever* found to do this (I don't use TKinter ;) is in the following scenario: # UnitTests.py import unittest from tests1 import * from tests2 import * if __name__ == '__main__': unittest.main() # tests1.py import unittest class Test1 (unittest.TestCase): def test1 (self): pass if __name__ == '__main__': unittest.main() # tests2.py import unittest class Test2 (unittest.TestCase): def test2 (self): pass if __name__ == '__main__': unittest.main() which allows me to perform each set of tests independently, and run them all through a single command. Even so, it should probably specify the actual names of the test cases in case there is a conflict somewhere, but that would fail to pick up any new test cases. Tim Delaney From a at b.c Sun Sep 29 02:29:12 2002 From: a at b.c (Michael Bakkemo) Date: 29 Sep 2002 06:29:12 GMT Subject: Why doesn't this work? Message-ID: Why doesn't the rectangle start somewhere in the middle of the canvas (where one would expect (40,40) to be, instead of all the way over on the left? --- import Tkinter import Pmw import tkFont class MovingRect: def __init__(self, master, sc, x, y,width, height): self.master = master self.sc = sc self.x = x self.y = y self.width = width self.height = height self.rectID = self.sc.create_rectangle(self.x, self.y, self.x+self.width, self.y+self.height,fill="black", outline="black") self.poll() def poll(self): sc.move(self.rectID, 4, 0) self.timerID = self.master.after(500, self.poll) def width(self, width): self.width = width def height(self, height): self.height = height def Destroy(self): self.master.after_cancel(self.timerID) def bail(): menu.quit() rect.Destroy() root = Tkinter.Tk() # create a menu menu = Tkinter.Menu(root) root.config(menu=menu) Quitmenu = Tkinter.Menu(menu) menu.add_cascade(label="Quit", menu=Quitmenu) Quitmenu.add_command(label="Quit", command=bail) sc = Pmw.ScrolledCanvas(root, borderframe=1, hscrollmode='dynamic', vscrollmode='dynamic') sc.xview("moveto", 0) sc.yview("moveto", 0) sc.resizescrollregion() sc.pack(fill='both',expand=1) rect = MovingRect(root, sc, 40,40, 10, 10) root.mainloop() From greek_bill at yahoo.com Wed Sep 18 16:58:13 2002 From: greek_bill at yahoo.com (Morfeas) Date: Wed, 18 Sep 2002 21:58:13 +0100 Subject: SWIG and C++ References: Message-ID: Morfeas wrote: > I don't know if this is the right place to post this, but I couldn't find > anywhere better. > ... > > Thanks! > Morfeas > It's ok I got the answer now! I was reading the documentation for an earlier version of SWIG and I didn't name the shared library correctly (missed the underscore!) Morfeas -- www.freecfm.com/m/morfeas From aleax at aleax.it Tue Sep 24 03:33:00 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 07:33:00 GMT Subject: Python threading? References: Message-ID: Mark Hammond wrote: ... > I would have thought that a brave call. If you are performing lots of > IO and need many many connections, you are almost certainly better off > using an "asynchronous" approach, much like asyncore. With a large Yes BUT -- as of course you know, select, on Windows, can only deal with sockets. Other kinds of asynchronous I/O require a completely different architecture on Windows wrt Unixoid systems -- file I/O, specifically, has the best performance with Windows' on asynchronous-IO-with-callbacks- on-completion, an arrangement very reminiscent of old VMS systems. Even for sockets, I benchmarked back in NT 3.something times that "native" (async-with-messages) winsock was vastly more scalable than "BSD emulating sockets and select" (not sure if that's still true these days). twisted.internet does have multiple implementations of the Reactor design patterns, including among others both a portable one based on select, and a Windows-specific one with a specialized message loop at its core (and others yet, such as ones working with GUI frameworks' events, poll in lieu of select, etc) -- haven't examined implementation in detail, but that does seem like the only sane approach if you need servers that are BOTH cross-platform AND highly scalable. > number of threads (where "large" can be as low as single figures) the OS > overhead of switching will be greater than your internal overhead of a > more complicated design. I guess so, depending of course on the OS -- threading is more and more likely to be well-optimized these days, but still the context switch has to cost something compared to a "cooperative" asynchronous architecture you can implement within one thread (or a very few threads of your own -- twisted lets you do that, too). > A "one thread per connection" model is doomed from the start - Hear, hear. > therefore, in most applications, I would consider 5 threads a large > number - particularly when all are actively doing something. OTOH, if > you are willing to accept that your first version will accept a max of > ~20 connections, the brain-power saved by using threads beats the > additional OS overhead by a mile ;) I think it only LOOKS simple if you don't look into it deeply enough. If the threads have almost no need to cooperate or share resources, then you may well be right. If the cooperation needs are limited enough that you can smoothly deal with them with Python "Queue" instances, you still have a chance to be right. But generally, I find that Ousterhout was right -- I'm sure you're familiar with his talk on "Why threads are a bad idea for most purposes" (I guess one can still find the slides on the net)... his point is more about "brain-power saved" (or consumed by debugging in a just-too-hard environment, with transient errors, race conditions, etc, etc) by using event-driven (i.e., async) approaches rather than threading, rather than about performance and scalability. Python may not yet support event-driven programming quite as smoothly and seamlessly as Ousterhout's Tcl, but, thanks to such developments as twisted, I think we're drawing progressively closer. With a solid enough underlying framework to dispatch events for you, I think event driven programming (perhaps with a few simple specialized threads off to one side, interfacing to some slow external resource, and getting work requests off a Queue, posting results back to a Queue...) can be made conceptually simpler as well as more scalable than threading. After all, in event-driven / async programming, ONE thing is happening at a time -- you only "switch" at known points, and between two such points you need not worry about what is or isn't atomic, locking, &c. It's also easier to debug, I think... Alex From Janssen at rz.uni-frankfurt.de Tue Sep 17 04:37:37 2002 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Tue, 17 Sep 2002 10:37:37 +0200 Subject: pickle magically not working References: <3d865dac@nntp.server.uni-frankfurt.de> Message-ID: <3d86ea57@nntp.server.uni-frankfurt.de> Martin v. Loewis wrote: > jepler at unpythonic.net writes: > >> If I had to guess, I'd say the "fix" was in Pickle itself, you might >> turn >> something up by investigating Python's CVS tree. Or somebody else >> might be able to immediately indicate the relevant code... > > It's in structseq.c:structseq_reduce (rev. 1.4 and 1.5), also fixed in > Python 2.2.1. > > Regards, > Martin thanks much, now i can comment out my workaround and be sure it won't happen with any other object's. Michael PS: happy to see that every "black magic" is downtrackable :-) From martin at v.loewis.de Fri Sep 20 03:37:45 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 20 Sep 2002 09:37:45 +0200 Subject: Suggesting a filename on a HTTP-request by sending someting in the header of the reply References: Message-ID: "Thomas Weholt" <2002 at weholt.org> writes: > It seem to be the "dl"-part of the url above. I've tried to read the > RFC 2616-document and sent "Content-Disposition"-headers etc. but > with no luck. You had no luck reading a document ?-) What browser are you using? Many Mozilla releases ignore the Content-Disposition field. Try downloading a patch from SourceForge with your browser, and see whether it uses the SF file name, or "download.php". SF works correctly in this respect, so if it won't work for you, it's a browser bug. Regards, Martin From syver-en+usenet at online.no Wed Sep 25 10:57:18 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Wed, 25 Sep 2002 14:57:18 GMT Subject: help References: Message-ID: "Juliana Braga" writes: > I need help. > For example: > x = ?name1? > How can I get the value of variable x (in this case the value of > variable x > > is ?name1?). After , I?d like to do this: > value of variable x = ?teste?. I am not sure I understand what you mean, but here's a shot: x = 'name1' saved = x x = 'teste' print x teste print saved name1 Hope this helps. -- Vennlig hilsen Syver Enstad From jonathan at onegoodidea.com Mon Sep 30 03:32:49 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Mon, 30 Sep 2002 08:32:49 +0100 Subject: [Mac] Editor on Macintosh? References: <1fj7za2.1erbqps1uvzpj8N%news@agapow.net> <290920020905027300%pecora@anvil.nrl.navy.mil> Message-ID: On 29/9/2002 14:05, in article 290920020905027300%pecora at anvil.nrl.navy.mil, "Louis M. Pecora" wrote: > From the looks of it this is OS X only, right? -- Lou The shell stuff is OS X only (though you could always get MPW for the authentic experience under 9). Otherwise, BBEdit is a Carbon app that runs fine on 9. Jonathan From aleax at aleax.it Wed Sep 18 11:26:31 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 17:26:31 +0200 Subject: monetary applications [was: Python GUI app to impress the bos s?] In-Reply-To: <31575A892FF6D1118F5800600846864DCBD817@intrepid> References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> Message-ID: On Wednesday 18 September 2002 04:34 pm, Simon Brunning wrote: > > From: Alex Martelli [SMTP:aleax at aleax.it] > > > > > Perhaps the lack of a FixedPoint type? > > > > http://starship.python.net/crew/aahz/FixedPoint.py > > A candidate for the standard library, perhaps? I use it all the time, and Definitely (Aahz's Decimal may be a better alternative), but it needs a paladin to convince the BDFL to include it in the core. Right now, it seems to me that FixedPoint and Decimal are not even among the most popular extensions -- Numeric, mxDateTime and other Lemburg extensions, and many others, seem to be vastly more popular. > if nothing else, it would be nice for DB-API modules to know that it was > there, so that they could return instances of it for NUMERIC and DECIMAL > values. To play devil's advocate: DB-API compliant modules have long used mxDateTime happily, for date-time values, even though mxDateTime was not (and likely will never be) in the core. Why is FixedPoint (or Decimal or some future Currency -- whatever) different from mxDateTime in this regard? How come DB-API compliant modules seem not to even have felt any need to fish around for a type with which to represent NUMERIC and DECIMAL, as they did for dates and times? I don't know the answers, but if "help out the DB-API" is among the arguments you plan to muster to convince the BDFL, you might want to be prepared in case these questions get raised. No, sorry, I won't volunteer as a paladin for this PEP -- I'll gladly help out with code and even drafting the PEP if need be, but this isn't really my own crusade... Alex From rajarshi at presidency.com Mon Sep 16 10:05:30 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Mon, 16 Sep 2002 10:05:30 -0400 Subject: getting username from uid Message-ID: Hi, when I do a stat on a file I can get the UID of the owner. IS there anyway to get from UID to username (or directly to username for that matter)? From aleax at aleax.it Thu Sep 26 09:08:36 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 13:08:36 GMT Subject: object changing itself to another object References: Message-ID: Glen Murphy wrote: ... > that input goes. In the highly simplified example below, I would like the > output to be "Obj1","Obj2","Obj1" - but not suprisingly, I just get Obj1, > Obj1, Obj1 > > > ### code begin ### > > class Obj1: > def key1(self): > # do obj1 specific stuff > self = Obj2() > print "Obj1" > > class Obj2: > def key1(self): > # do obj1 specific stuff > self = Obj1() > print "Obj2" > > a = Obj1() > > # simulate user keypresses > a.key1() > a.key1() > a.key1() Then change the classes to: class Obj1: def key1(self): # do obj1 specific stuff self.__class__ = Obj2 print "Obj1" class Obj2: def key1(self): # do obj1 specific stuff self.__class__ = Obj1 print "Obj2" > I know I could achieve the result I want by doing horribly complicated > trees of ifs and such, but I'd like my code to be nice and expandable (in > this example, to easily add new Objs). I've looked through the Python FAQ, > Google Groups and Various O'Reilly books, but I don't really know the > terminology for what I'm looking for, so I haven't found anything so far, > so does anyone have any pointers? You have not checked O'Reilly's Python Cookbook, I think, because this particular idea of changing an object's __class__ is exemplified there. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429 in the online version, but I think you'll find the discussion more complete, &c, in the printed version. Alex From gerhard.haering at opus-gmbh.net Thu Sep 5 07:36:42 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 5 Sep 2002 11:36:42 GMT Subject: newbie problem: use socke lib to retrieve one web page: References: Message-ID: koko wrote: > I write this to retrieve one web page using socket lib. > > # retrieve webpage > import socket > HOST='www.uic.edu' # remote host > PORT=80 # remort port > s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > m="""GET /home/events.shtml HTTP/1.0 > From: hh at uic.edu > User-Agent: test/1.0 > """ > [...] You're missing the empty line that terminates a HTTP 1.0 or later HTTP request. -- Gerhard From jk3380 at naida.org Sun Sep 22 12:02:46 2002 From: jk3380 at naida.org (Pino Gargiulo) Date: Sun, 22 Sep 2002 18:02:46 +0200 Subject: Smalltalk vs. Python and COM was Re: Byte Magazine and Smalltalk References: <3d87a686@tobjects.> <3d87dd7c$1@tobjects.> <20020918.115128.1605894428.1527@cybermesa.com> Message-ID: "Jay O'Connor" wrote in message > ... snip ... > I use Python in a lot of places where others would probably use Perl. > Pythons regex support is not a strong as Perl's, but its support for data > abstraction(and hence, more complicated problems) is much more powerful. This brings up a question I was about to ask. I'm getting involved in a small project that requires a couple of COM servers, whatevere these are exactly... the nice thing is that any developmente language can be chose. My backgroung is Unix & CORBA, dabble a bit with VWNC (no serious work) and this is my second time I write something on m$ platform. For this project I was considering Smalltalk and Python. The first so I could be some real stuff done and Python because apparently it permits quite easy access the the mysterious (to me) m$ APIs. I really would want to stay away from VC++, and I'm looking for some quite turnaround environment since I'll be learning COM on the job. Anybody care to give some advice? I played around with DST but never looked much at the existance of a COM wrapper/interface. TIA Pino From Nicola.Musatti at ObjectWay.it Fri Sep 20 10:36:00 2002 From: Nicola.Musatti at ObjectWay.it (Nicola Musatti) Date: Fri, 20 Sep 2002 16:36:00 +0200 Subject: general thoughts References: Message-ID: <3D8B3250.BA964BCF@ObjectWay.it> Alex Martelli wrote: [...] > I think you need substantial capacity and appetite for abstract thought > to really _enjoy_ SICP -- it doesn't spoon-feed you, nor does it use > baby-talk, lots of somewhat-repetitive examples, and other standard > didactical techniques. But if the book's style does match your own > character and inclination, you're likely to fall in love with it. Or, to put it in another way, gurus like this book. ;-) Cheers, Nicola Musatti From altis at semi-retired.com Fri Sep 13 20:10:00 2002 From: altis at semi-retired.com (Kevin Altis) Date: Fri, 13 Sep 2002 17:10:00 -0700 Subject: Python GUI/graphics package recommendation? References: Message-ID: I don't think it is very nice to make your aunt do your programming for you , but she can see if the instructions below are easy enough to give PythonCard a try. http://pythoncard.sourceforge.net/installation.html There are some walkthroughs to help you along once you have everything up and running. ka "David Ehrens" wrote in message news:Xns9288738D9E9EEnospamanytime at 216.148.227.77... > I am using Python 2.2 on Win32 for an AI class and would like to > be able to display a graphical representation of an agent-based > game I am developing. I have seen a number of GUI and graphics > packages for Python, and would appreciate some recommendations > since I really don't have the time to install, learn, and try all > of them. > > My main criteria are: (1) my great aunt should be able to install > it and immediately use it; (2) it should work with Win32; (3) it > should do menus and graphics. > > If it happens to be the #1 tool of its kind, that would be nice > too. > > Thanks, David From jpm at papercut.org Mon Sep 30 17:51:16 2002 From: jpm at papercut.org (Joao Prado Maia) Date: Mon, 30 Sep 2002 17:51:16 -0400 (EDT) Subject: Question about __getattribute__/__getattr__ In-Reply-To: <20020930234554.Y30315@prim.han.de> Message-ID: On Mon, 30 Sep 2002, holger krekel wrote: > The important lines from the above link are: > > def __call__(self, *args): > if not self.memo.has_key(args): > self.memo[args] = self.fn(*args) > return self.memo[args] > > and 'args' is a tuple of arguments. > 'args[0]' would give you the first argument, for example. > Correct. However, the same is not valid for __getattr__. The first and only parameter of this magic method is the attribute/method name that you are trying to access. It doesn't give you the list of arguments passed to a method. So on my example: """ class Real_Class: def real_method(self, name): print name class Cache: r = None def __init__(self): self.r = Real_Class() def __getattr__(self, attr): cached_value = self.get_cache(attr) if cached_value == None: return getattr(self.r, attr) else: return cached_value def get_cache(self, attr): return None if __name__ == '__main__': t = Cache() t.real_method('spam') """ 'attr' is the actual method name I was trying to call, using the 't.real_method('spam')' line in there. My question is, how do I get the actual argument list from inside __getattr__, so I can create an unique method/argument list signature for the cached files ? :) I'm guessing there must be some deep magic to do this, but I couldn't find this anywhere. Cheers, Joao From irmen at NOSPAMREMOVETHISxs4all.nl Mon Sep 23 13:38:58 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Mon, 23 Sep 2002 19:38:58 +0200 Subject: UpToDate SOAP-module ?? References: Message-ID: Thomas Weholt wrote: > I've looked around for a SOAP-module to use in a WebService-based project, > but the SOAP-implementations in python seem to be a bit ... unstable ?? [...] > Any opinions, hints or ideas are welcome. Thoughts on ease of use, list of > features, comparisons etc. are also interesting. I've had good results with the updated SOAP.py found in the PyGOOGLE library, http://diveintomark.org/projects/#pygoogle But I find XML-RPC much easier to use. It has a lot less features than SOAP has, but in this particular case that is a *good* thing. Plus the xmlrpclib module that comes installed is very good. Irmen de Jong From owen at nospam.invalid Fri Sep 13 15:55:29 2002 From: owen at nospam.invalid (Russell E. Owen) Date: Fri, 13 Sep 2002 12:55:29 -0700 Subject: Tkinter listbox clicking problem References: Message-ID: In article , "Matthew Bonig" wrote: >Right now I have it bound so when a Tkinter listbox gets a >(lb.bind("", someFunc)) it calls function someFunc. Now, >someFunc() simply prints the curselection(). The problem is it's lagged... >if I first select list item 1 (index 0), and then 2, and then 3 (array >indexes 0,1,2) it prints out themout incorrectly. >(I have someFunc actually do some try, except stuff so I don't get uncaught >exceptions) Instead of printing 0,1,2 it prints "nothing selected", 0, 1. >The function get's called before the listbox updates it's selection markers! > >Does anybody know how I could force listbox to update it's selection markers >so instead of printing "nothing selected, 0,1 it prints 0,1,2 like it >should? I'm hoping somebody has better ideas, but here are some to try: Call update_idletasks before you ask for the selection. I have no idea if this will work, but it might. An ugly solution that would probably work: - extract the y coordinate from the event callback - call nearest(y_coord) to get the item closest to the mouse click - explicitly select that index item. You could try skipping this step, but you risk a possible error between what you think they clicked on and what is hightlighted. Unfortunately, this step will may be a real pain for a list that supports multiple selected items. Poll for selection changes -- thus it may take a bit of time before your code notices a change, but it will always be right once it gets there. -- Russell From maxm at mxm.dk Tue Sep 17 03:48:10 2002 From: maxm at mxm.dk (Max M) Date: Tue, 17 Sep 2002 09:48:10 +0200 Subject: Windows AutoRunning Python Hello -- feedback requested References: Message-ID: <3D86DE3A.2040903@mxm.dk> Dennis Reinhardt wrote: > 1) Is this the right group to discuss/get feedback? Yes > 2) Is this functionality useful enough to others to pursue? It is probably to "in-between" to be of interrest to a lot of people. To high level to be a short learning example, and to low level to be of real use. It will probably be interresting to only a small subset of developers. But here is the place to look for them ;-) regards Max M From gerhard.haering at opus-gmbh.net Mon Sep 2 07:55:45 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 2 Sep 2002 11:55:45 GMT Subject: Does IDLE handle unicode? References: Message-ID: Edward K. Ream wrote: > IDLE took an exception writing a .py file containing the copyright > character. This happened a while ago; IIRC, I lost the file. > > Is this a known problem? Yes. > I see nothing about this in the FAQ. http://www.faqts.com/knowledge_base/view.phtml/aid/11712 has a workaround. -- Gerhard From tjabo.kloppenburg at unix-ag.org Tue Sep 10 14:28:23 2002 From: tjabo.kloppenburg at unix-ag.org (Tjabo Kloppenburg) Date: Tue, 10 Sep 2002 20:28:23 +0200 Subject: Trouble upgrading to 2.2.1 In-Reply-To: References: Message-ID: <20020910202823.2bff6572.tjabo.kloppenburg@unix-ag.org> On 10 Sep 2002 16:39:19 GMT Gerhard H?ring wrote: GH> > libcrypto.so.2 GH> > libsel.so.2 GH> GH> That should probably be libssl... on a suse system, you find a file ARCHIVES.GZ on the first cdrom. copy it to the hard disk, and do a "zgrep libcrypto ARCHIVES.GZ" -- you'll see the packages with files with this name... I allways have/had:) a small script called "wofile (wherefile)" on my suse linux systems to find the right packages -- yast1/2 was not my friend... :) -- Tjabo Kloppenburg --=- In 104.16 Tagen ist Weihnachten! -=-- -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bridgman at wyeth.gsfc.nasa.gov Mon Sep 23 16:22:24 2002 From: bridgman at wyeth.gsfc.nasa.gov (Tom Bridgman) Date: Mon, 23 Sep 2002 16:22:24 -0400 Subject: Saving & Restoring Python objects in XML? Message-ID: <3D8F7800.F757A72D@wyeth.gsfc.nasa.gov> Hello, I'm setting up some codes where I want to save the state of the code in an XML file at some time and reload it later to continue the processing. It's relatively easy to save out the innards of Python objects into XML regardless of how the objects are nested. But what about loading this state information back in from the XML file? Is there a way to write the parser handlers and/or other components (I'm using PyXML 0.7 and higher) such that they can assemble the required objects as they read in the file? I'm wondering if there is an elegant solution that might not be immediately obvious from the 'brute force' method I keep coming up with. I'd prefer to do this using SAX (since I've worked with it some), but using DOM is not out of the question if it solves the problem in a straightforward way. Thanks, Tom -- Dr. William T."Tom" Bridgman Scientific Visualization Studio Global Science & Technology, Inc. NASA/Goddard Space Flight Center Email: bridgman at wyeth.gsfc.nasa.gov Code 935 Phone: 301-286-1346 Greenbelt, MD 20771 FAX: TBD http://svs.gsfc.nasa.gov/ From soodvarun at janu.info Sat Sep 28 05:02:00 2002 From: soodvarun at janu.info (Varun Sood) Date: 28 Sep 2002 02:02:00 -0700 Subject: problem with GUI editor Message-ID: hi there !!!! i am very new to python and to this world of developers I need help !! 1) TUTORIALS which could be downloaded. 2) PYTHON's GUI (SHELL) editor is not good. As it does not shows SECONDARY PROMPT and it do not run "if....elif" statement as it gives errors on it. "INDENTATION NOT SET" but the same works properly in python's COMMAND LINE shell. Wts the problem?? I am using python 2.2 varun From pinard at iro.umontreal.ca Tue Sep 3 21:11:06 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Tue, 03 Sep 2002 21:11:06 -0400 Subject: winsound.Beep() frequencies In-Reply-To: (bokr@oz.net's message of "4 Sep 2002 00:55:57 GMT") References: <3ab719f7.0209031229.33667461@posting.google.com> Message-ID: [Bengt Richter] > But I believe the best sounding scale will not have 12 equal ratios of > 2**(1/12). How to tune has been the source of hot debates for centuries. When the equal tuning established itself and won, the debates progressively faded out, and we now take that a dull equal tuning for granted. Most people never heard a good tuning, and would feel astonished or uncomfortable at first, hearing something like a perfect third. It take some time to rediscover the pleasure of such things, after what, todays's ubiquitous equal tuning appears even more dull... For beeping a computer however, it might not matter so much! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From imbosol at vt.edu Sun Sep 1 19:17:19 2002 From: imbosol at vt.edu (Carl Banks) Date: Sun, 1 Sep 2002 19:17:19 -0400 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: Gerson Kurz wrote: > So basically, couldn't one come up with > a *human readable* syntax for re, and compile that instead? Python > prides itself on its clean syntax, and human readability, an bang - > import re, get perl-ish code instantly! You might want to look at the Plex package. It defines patterns by constructing data structures. Something like this: symbol = Range("A-Za-z") + Any(Range("0-9A-Za-z") | Char("_")) However, three points: First, this will certainly be slower than regular expressions, since there are many Python calls needed to build the structure. (Of course, after you've compiled it, it can be as fast as regexps.) Second, even if you use re module, it is still nowhere near Perl-ish ugliness. You still have Python's clean syntax outside of the pattern. Third, readability is not a unilateral good thing; conciseness is also important, and sometimes opposed to readability. Sacrificing a little readability to get a lot of conciseness is usually a good thing. I think, as long as the regexp is not too obnoxious, it is probably better to keep it concise. (Of course, this depends a lot on what you're doing and how flexible you need to be.) -- CARL BANKS http://www.aerojockey.com From ezcoder at mailcity.com Fri Sep 13 23:20:52 2002 From: ezcoder at mailcity.com (Glenn Scott) Date: 13 Sep 2002 20:20:52 -0700 Subject: Question regarding mysqldb module and variable table names Message-ID: <45ac92e5.0209131920.23b1c22a@posting.google.com> Hi all, I'm currently using the MySQLdb module to write data to a mySQL database. I've run into a problem while changing my code that I was hoping someone might have some suggestions on. Originally I had code that looked like this: c.execute("""INSERT INTO mytable \ SET playerkey=%s, link=%s, snippet=%s, time_created=%s, \ last_seen=%s, relevancy=%s, doc_title=%s """, \ (playerKey, urlLink, snippetText, self.getCurrentTime(),self.getCurrentTime(),\ noOfMentions, re.escape(str(self.doc_title))) ) I liked using the function of this type rather than that using the "%" string formatter since it automatically fixed problems with odd characters in my data. Worked great! I want to change it so that the "mytable" value in this example is a variable rather than a constant. So the code would look like this: c.execute("""INSERT INTO %s \ SET playerkey=%s, link=%s, snippet=%s, time_created=%s, \ last_seen=%s, relevancy=%s, doc_title=%s """, \ (infoTable, playerKey, urlLink, snippetText, self.getCurrentTime(), self.getCurrentTime(),\ noOfMentions, re.escape(str(self.doc_title))) ) But this doesn't work...for whatever reason, using "%s" in an assignment SET variable works, but as a table name it doesn't. I suppose I can use the "%" string formatter at the end of the triplq-quotes to fix this problem, but I'll have to jump through other hoops to deal with oddness with my data that is taken care of for me by using the "," alternative. Any ideas as to how I might approach this? TIA From heikowu at ceosg.de Sat Sep 7 17:25:10 2002 From: heikowu at ceosg.de (Heiko Wundram) Date: 07 Sep 2002 23:25:10 +0200 Subject: Killing/Terminating a running thread In-Reply-To: References: Message-ID: <1031433910.17902.107.camel@d168.stw.stud.uni-saarland.de> Am Sam, 2002-09-07 um 22.42 schrieb Chris Liechti: > sound like the news thread "Interrupting Python" could be interresting for > you... I've looked at that, but the main problem is that this thread deals with interrupting fullblown processes on the fly (from within the code), not with interrupting a process by an exterior signal. > the clean solution is to test for a flag and terminate if the flag is set. > > e.g. you could provide a function: > > def interrupted(): > return global_flag_if_user_wants_to_abort > > and in you function in the queue: > > def worker(): > while not interrupted(): > do_stuff() This is what I do to shutdown the worker cleanly. The problem is: do_stuff() doesn't return until it's complete, and I have no control whatsoever about the internal workings of do_stuff(). What I actually wish to do is while the worker still is in do_stuff(), to kill the worker as a whole, to discard all its data, when a timeout on returning a value from do_stuff() occurs. It's not about clean termination of a thread, but about killing the thread in case it takes too long (in case do_stuff() takes to long). Thanks for the advice anyway! :) I guess I at least did the general interrupt on the worker right then... :) Yours, Heiko Wundram Netzwart Wohnheim-D Zimmer 2206 - Universit?t 18 - 66123 Saarbr?cken -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From Padraig at Linux.ie Fri Sep 13 12:33:23 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Fri, 13 Sep 2002 16:33:23 GMT Subject: question about dictionary type.. References: Message-ID: <3D82132C.1020203@Linux.ie> eugene kim wrote: > hi.. > > i'd like to have a dictionary which looks like > table = { category1 : { category2 : { category3 : 'garbage value' } } } > > category1 has many category2 > category2 has many category3 > > i expected > table[ 'computer' ][ 'language' ][ 'python' ] = 0 > to create {computer : { language : { python :0 }}} > table[ 'computer' ][ 'language' ][ 'java' ] = 0 > to becomes { 'computer' : { 'language' : { 'python' :0 , 'java' :0 }}} > > but python doesn't allow me to do this.. > can anyone help me? > It only creates 1 level at a time because ypur not acutally assigning to table[ 'computer' ] or table[ 'computer' ][ 'language' ], you're only referencing them. I guess you have to do something like: table.setdefault('computer',{}).setdefault('language',{})['python']=0 P?draig. From pyth at devel.trillke.net Wed Sep 11 16:56:31 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 11 Sep 2002 22:56:31 +0200 Subject: Any C++/Python sig members here? In-Reply-To: ; from Oschler@earthlink.net on Wed, Sep 11, 2002 at 04:18:25PM +0000 References: Message-ID: <20020911225631.T3893@prim.han.de> Robert Oschler wrote: > I joined the C++ sig for Python, to talk with others about BoostPython. I > joined more than a day ago and got my subscription confirmation request from > the sig server. I have not seen any messages yet, is it a very low traffic > sig or something? I don't think so. but to be sure you can look at the archives. the link should have been sent with your welcome-message. holger From aleax at aleax.it Wed Sep 25 17:15:46 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 21:15:46 GMT Subject: help with print function in extension References: <4jfk9.163306$pX1.5842487@news2.tin.it> Message-ID: <6Ipk9.143767$ub2.3151188@news1.tin.it> Eric Hagemann wrote: ... > Alex, Thanks -- missed that section in the manual. I blindly assumed that > I could use the repr() as the print func...... You can! Just leave the tp_print slot to 0 and all should be fine. > ok so for the next trick question. I implemented a function that has the > proto > int print_func(PyObject *obj, FILE *fp,int flags) > > when I try to print to fp -- as in --> fprintf(fp,"", , )... I crash > the program. I'll have to admit that I never filled tp_print myself (oh the shame), always relying on other slots, so I can't help you here... Alex From cben at tx.technion.ac.il Tue Sep 10 15:35:50 2002 From: cben at tx.technion.ac.il (Beni Cherniavksy) Date: Tue, 10 Sep 2002 22:35:50 +0300 Subject: "str"(expr)"str" interpolation syntax Message-ID: Hi all. I was searching for a new interpolation syntax that would use quotes for starting/ending the interpolated part (I don't feel comfortable putting code inside unclosed quotes...) After contemplating some horrors like $"""str"expr"str""" or $("str" expr "str"), I noticed that currently both "( and )" are illegal (first because strings are not callable, second is a syntax error). So I propose that a parenthesized expresion near a string would imply concatenation. In other words, "foo"(x * 3)"bar" would be equivallent to "foo" + str(x * 3) + "bar". This works of course with only one side, e.g. "foo"(x) or (y)"bar" but in longer cases it would be good style to add empty strings on either end, e.g. ""(y)"bar". And of course it all works with single quotes too. One of the benefits over current interpolation PEPs is that you can change the quote type in the middle... It is slightly more verbose (especially when interpolating into tripple quote strings: """foo"""(x)"""bar""") but it is more readable and understandable (just extends the current concatenation of constant strings), allows clear nesting of strings into the expr: "foo"('%3d' % x)"bar" and most importantly, you never need to remember arbitrary rules where the interpolation ends... What do you think? -- Beni Cherniavsky Awake! Awake! Fear, Fire, Foes! Awake! Fire, Foes! Awake! [Tolkien, LOTR] Fight software patents: http://lpf.ai.mit.edu/ BTW, does somebody know what's the situation in Israel concerning software patents? From greek_bill at yahoo.com Sat Sep 21 19:55:13 2002 From: greek_bill at yahoo.com (Morfeas) Date: Sun, 22 Sep 2002 00:55:13 +0100 Subject: [newbie] Calling Python from C++ References: <8L5i9.841$Ew4.62552@newsfep2-gui> <3D8B3EA0.6050500@thinkware.se> Message-ID: David Abrahams wrote: > While I appreciate the plug and I do think Boost.Python is a great > solution for C++, SWIG has evolved since I first did my analysis and it > understands a lot more of C++ than it used to, though it is still missing > the ability to instantiate templates. The Boost comparisons page is > woefully outdated and I've been waiting for David Beazley to write a new > blurb for SWIG. > I concur. I've managed to do what I want in the end, using SWIG. Altough, I must admit I'm not using it (SWIG) the way it was designed to be used! If I understand correctly, SWIG (and probably a lot of other similar tools) has been designed to make your C (or C++) code visible to Python (and other interpreted languages) code. i.e. it helps you write extensions to Python. What I was trying to do (and finally succeeded) was : 1. to extend an embedded Python interpreter, and 2. allow the python code to interact with existing instances of C++ objects It took a bit of messing about and hacking at code, but it worked (hey, what's another couple of 16 hours days in front of the computer? :) Morfeas -- www.freecfm.com/m/morfeas From aleax at aleax.it Tue Sep 24 11:19:31 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 15:19:31 GMT Subject: Getting started References: <0%Aj9.129252$ub2.2813083@news1.tin.it> <877khb7884.fsf@pcdh91.cern.ch> Message-ID: <7o%j9.159168$pX1.5714084@news2.tin.it> Tibor Simko wrote: > Hello > > On Mon, 23 Sep 2002, Alex Martelli wrote: >> as far as I know, the CAML dialect of ML (also in the O'Caml >> extension, last I looked) is one of the very few programming >> languages that doesn't have a polymorphic + operator -- you have to >> use + for integers only, +. for floating-point. > > There is a good reason why OCaml does not overload the + operator: There is a reason -- whether it's a GOOD one is more debatable:-) > type inferring. In OCaml you do not need to declare variables > explicitly in the program because OCaml infers types for you. > However, this does not match well with operator overloading, since the > compiler would not understand whether "a + b" stands for float or > integer. Unlike SML, OCaml decided to avoid this kind of type > inferring problem by not overloading the + operator. Compare this "solution" to Haskell's typeclasses to see why I love Haskell so:-). While SML doesn't seem to suffer unduly from "overloading" (as you say) `+` , Haskell generalizes this to a kind of generic-programming ability -- no overloading, just the right amount of generality. And without any damage at all to strong compile-time type safety, nor to type inferencing (or inferring), of course. Alex From skip at pobox.com Wed Sep 18 17:19:00 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 18 Sep 2002 16:19:00 -0500 Subject: linux python ideas In-Reply-To: <200209181347.39562.shalehperry@attbi.com> References: <3D88E578.6010001@diespammerdieuselesspython.com> <200209181347.39562.shalehperry@attbi.com> Message-ID: <15752.60868.893189.395705@12-248-11-90.client.attbi.com> >> I'll be giving a presentation on Python to my local LUG >> (http://lugoj.org) in a few weeks, and would like to point out at >> least a few things that would be of particular interest to linux >> users. Sean> obvious ideas are things like zope and mailman as well as cheetah. Also rdiff-backup: Skip From fb at frank-buss.de Thu Sep 5 07:45:52 2002 From: fb at frank-buss.de (Frank Buss) Date: Thu, 5 Sep 2002 11:45:52 +0000 (UTC) Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> Message-ID: "G. Willoughby" wrote: > I would really like to know how to do this too, basically i want to > print to a standard bubblejet print (non postscript) from a Tkinter > Text widget, any ideas? Perhaps you can draw a PDF file with Reportlab (http://www.reportlab.com/) and printing it. Because you are using Outlook Express, I assume you need it for Windows. An example: from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import A4 c = canvas.Canvas('c:\\tmp\\test.pdf', pagesize=A4, bottomup=0) c.setFont('Helvetica', 14) c.drawString(10, 20, 'Hello World!') c.save() If you want direct printing, without user interaction and you know the path of the Acrobat Reader, you can use this line: system('"C:\\Programme\\Adobe\\Acrobat 5.0\\Reader\\AcroRd32.exe" /p /h c: \\tmp\\test.pdf') Perhaps it's easier with the ShellExecute command, because then you don't need to know the path of AcroRd32.exe, but then you need this, if you don't have ActiveState Python installed: http://starship.python.net/crew/mhammond/win32/Downloads.html If you just want to show the user the page and let the user decide to print or close the document, this lines are sufficient: from os import startfile startfile('c:\\tmp\\test.pdf') -- Frank Bu?, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From blalor at insight.com Fri Sep 6 11:39:58 2002 From: blalor at insight.com (Brian Lalor) Date: Fri, 06 Sep 2002 15:39:58 GMT Subject: help needed creating xml document with xml.dom Message-ID: Good morning, all. Several times, now, I've used xml.dom.minidom to create raw XML documents, but I don't think I've ever really done it the "right" way. I blame that on my seeming inability to find documentation on the "right" way to do it in Python, or in any language, for that matter. Pointers to said documentation are welcomed. :-) That out of the way, here's my current problem. I'm trying to write a script that will spin through a set of images taken with my digital camera, pull out the EXIF data and save it to an XML document and also extract the JPEG thumbnail from those images. Gene Cash's excellent EXIF.py[1] does the dirty work with getting the EXIF data. I also want to create an XHTML document that is the index of all of these thumbnails, and that's where things started going downhill. A "proper" XHTML document requires a well-formed XML document along with a doctype definition(?) below the declaration and an xmlns attribute to the tag. Using minidom, I cannot seem to get either the namespace or doctype to print out. Here's the relevant code snippet: import xml.dom # is this the right way, instead of directly importing xml.dom.minidom? DOM = xml.dom.getDOMImplementation() # now create the doctype and the document element doctype = DOM.createDocumentType('html', '-//W3C//DTD XHTML 1.0 Strict//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd') index_page = DOM.createDocument(xml.dom.XHTML_NAMESPACE, 'html', doctype) index_page.documentElement.setAttribute('xml:lang', 'en') index_page.documentElement.setAttribute('lang', 'en') So, now if I do a index_page.toprettyxml(), I only get ... but I *want* Is this a bug in minidom, or (more likely) am I doing something wrong? I'm using Python 2.2.1 but I have PyXML 0.7 installed, so that's where minidom.py is coming from. Thanks, B [1] http://home.cfl.rr.com/genecash/digital_camera.html -- Brian Lalor | http://introducingthelalors.org/ blalor at ithacabands.org (email) | blalor at jabber.ithacabands.org (jabber) N33?27.369' W111?56.304' (Earth) From pedronis at bluewin.ch Sat Sep 7 07:32:20 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Sat, 7 Sep 2002 13:32:20 +0200 Subject: [curiosity/info] Parrot long-term goals/prospects Message-ID: <3d79e4c5_4@news.bluewin.ch> http://archive.develooper.com/perl6-internals%40perl.org/msg12437.html [ For people prone to just skim the pointed message, it is worth to repeat that it is talking about things that should become real in the "distant" future, for some value of "distant".This link is posted just as curiosity/information, no negative/positive opinion from my part on Parrot should be inferred from me posting this, I'm not involved with Parrot, apart from skimming their mailing list from time to time. ] regards. From sholden at holdenweb.com Sat Sep 7 17:30:49 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 7 Sep 2002 17:30:49 -0400 Subject: about parse a link References: Message-ID: "Fredrik Lundh" wrote in message news:HXXd9.9644$HY3.2204710 at newsc.telia.net... > "koko" wrote: > > > if I have extracted the links on the page: > > e.g: > > > > http://www.uic.edu/index.htm > > on this page: there are > > a.htm > > b.htm > > c.htm > > http://www.uic.edu/home/e.htm > > > > how can I log the a.htm, b.htm, c.htm with the full web address? > > base = "http://www.uic.edu/index.htm" > > url_list = [ > "a.htm", > "b.htm", > "c.htm", > "http://www.uic.edu/home/e.htm" > ] > > import urlparse > > for url in url_list: > print urlparse.urljoin(base, url) > > prints > > http://www.uic.edu/a.htm > http://www.uic.edu/b.htm > http://www.uic.edu/c.htm > http://www.uic.edu/home/e.htm > > > > > In case you haven't done much of this kind of stuff, note tha you should use the URL of the page you are inspecting as the base, unless it contains a tag, in which case you need to use the URL from that. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From sgclift at earthlink.net Sun Sep 1 22:47:25 2002 From: sgclift at earthlink.net (Steve Clift) Date: Sun, 01 Sep 2002 19:47:25 -0700 Subject: urllib bug? Message-ID: <3.0.6.32.20020901194725.007d4cd0@mail.earthlink.net> Is this *really* a urllib bug, or am I missing something blindingly obvious? Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> import urllib >>> f = urllib.urlopen('http://www.python.org') Traceback (most recent call last): File "", line 1, in ? urllib.urlopen('http://www.python.org') File "C:\PROGRAM FILES\PYTHON22\lib\urllib.py", line 73, in urlopen return _urlopener.open(url) File "C:\PROGRAM FILES\PYTHON22\lib\urllib.py", line 178, in open return getattr(self, name)(url) File "C:\PROGRAM FILES\PYTHON22\lib\urllib.py", line 276, in open_http if not host: raise IOError, ('http error', 'no host given') IOError: [Errno http error] no host given Fails the same way with 2.1. Works OK with 1.5.2 and (IIRC) 2.0. -Steve From joconnor at cybermesa.com Sat Sep 7 12:43:05 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Sat, 07 Sep 2002 16:43:05 GMT Subject: None or 0 References: Message-ID: <3d7a2b6b.92959728@news.cybermesa.com> On Sat, 07 Sep 2002 09:08:08 -0700, John Baxter wrote: >In article , > Michael Stroder wrote: > >> >>> repr(0 or None) >> 'None' >> >>> repr(None or 0) >> '0' >> >>> repr('' or None) >> 'None' >> >>> repr(None or '') >> "''" >> >>> >> >> Is it guaranteed to work like this or should that be avoided? > >It seems very convenient to implement or (and and) by returning the >first object which decides the answer. I noticed that happening. It seems sensible for short-circuiting that in an "or", you just return th second term , regardless of what it is >My guess is that enough people are counting on the behavior that even if >the underlying hardware or implementation language were to shift enough >to make this implementation quite inconvenient, it would nonetheless >survive. > >Having said that, I tend not to like counting on it, because it >stretches the extra-Python definition of the operators quite a bit. >Particularly on the "and" side: > >>>> print 5 and 1 >1 > >Go into (English-speaking) classrooms, and you're going to hear chants >of "5 and 1 is 6" not "5 and 1 is 1". Because in that contexts "and" means "plus" and in this context "and" means "logical and" Take care, Jay O'Connor joconnor at cybermesa.com http://www.cybermesa.com/~joconnor "God himself plays on the bass strings first, when he tunes the soul" From anton at vredegoor.doge.nl Sat Sep 14 09:22:50 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 14 Sep 2002 15:22:50 +0200 Subject: How to represent sets Message-ID: Hello All, In the past there have been some discussions on various platforms about whether sets should be implemented using long integers (possibly leading to longs becoming iterable arrays of booleans), or by using dictionaries. The matter seems to be mostly settled and there is a sets.py script in the CVS directory at sourceforge which uses dictionaries. I would like to reopen this discussion. Starting this discussion again when the CVS script is already very mature seems a bit inappropriate, but I believe there is a way to make sets faster. I only recently realized this so I could not act earlier. To give some material for the discussion I am providing a beta version of a possible implementation af a set class using long integers to represent sets. It is basically the same script I presented a year ago but I have made several improvements to this script so that it is now a bit faster, and I hope the docstring is a bit better now. Please keep in mind this is just a test script, for a safer and more complete implementation the script in CVS is preferable. http://home.hccnet.nl/a.vredegoor/universe/universe.py or the html version: http://home.hccnet.nl/a.vredegoor/universe/universe.html Anton. From bdesth at nospam.free.fr Fri Sep 6 21:39:39 2002 From: bdesth at nospam.free.fr (laotseu) Date: Fri, 06 Sep 2002 21:39:39 -0400 Subject: Larry Wall's comment on python... References: Message-ID: <3D7958DB.50903@nospam.free.fr> Rod Stephenson wrote: > Slashdot has a list of questions posed to Larry Wall (perl). When > asked his thoughts on other scripting languages, he makes the > following observation about python > > "Python is cool to look at small bits of, but I think the "outline" > syntax breaks down with larger chunks of code. I'm with Aristotle on > the structure of discourse--a story should have a beginning, and > middle, and an end. So should blocks" > > I'm not quite sure what he's trying to get at here - I guess that for > a long heavily indented chunk of code, you could lose track of the > overall structure, but I don't write code this way. > > Any comments? def fun(args): #BEGIN if ceci or cela: #BEGIN do_this(with_that) [snip a lot of code] #END #END So what the problem with blocks ? laotseu From stephen.boulet at motorola.com Fri Sep 27 15:23:35 2002 From: stephen.boulet at motorola.com (Stephen Boulet) Date: Fri, 27 Sep 2002 14:23:35 -0500 Subject: Better terminal for windows? Message-ID: <3D94B037.2020202@motorola.com> I'm using python 2.2.1 on winnt. If I want to run python interactively (and perhaps using ipython), is there something better than the "cmd" terminal? I'm used to bash on linux at home, but I'd like to avoid installing cigwin for now. Thanks. -- Stephen From abuse at nospamtron.riot.com.au Thu Sep 26 09:43:00 2002 From: abuse at nospamtron.riot.com.au (Glen Murphy) Date: Thu, 26 Sep 2002 13:43:00 GMT Subject: object changing itself to another object References: Message-ID: > You have not checked O'Reilly's Python Cookbook, I think, because > this particular idea of changing an object's __class__ is exemplified > there. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429 > in the online version, but I think you'll find the discussion more > complete, &c, in the printed version. Thanks Alex, I have actually subscribed to the book on Safari, but it's kinda hard to flick through there :D And thank you to everyone who submitted answers - very much appreciated, ~ Glen From Steven_Shaw at adc.com Tue Sep 10 01:19:26 2002 From: Steven_Shaw at adc.com (Steven_Shaw at adc.com) Date: Tue, 10 Sep 2002 15:19:26 +1000 Subject: dynamism Message-ID: <4A256C30.001DA17F.00@ssxrgw01.aus.ssd.adc.com> >> I've been away from Python for awhile and I'm wondering whether Python got >> less "dynamic" while I was away. >> >> I thought you could just extend an object's attributes at >> run-time like this: >> >> >>> p = object() >> >>> p.x = 1 >> Traceback (most recent call last): >> File "", line 1, in ? >> AttributeError: 'object' object has no attribute 'x' > >object is the base type of new-style classes. Try something like this >instead: > >>>> class foo:pass >... >>>> f = foo() >>>> f.x = 1 >>>> f.x >1 Thanks! > >Or 'class foo(object):pass' works too. > >// m From chris.gonnerman at newcenturycomputers.net Sat Sep 21 12:31:50 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sat, 21 Sep 2002 11:31:50 -0500 Subject: Local Python Server Installation References: <3d8b47c6.277669@news.jaring.my> <3d8c993c.2190426@news.jaring.my> Message-ID: <003f01c2618c$67e3e720$0101010a@local> ----- Original Message ----- From: "Kenneth Gomez" > I tried your method. But instead of getting a cgi listing of > my environmental listings, all I saw on my browser was the > two input lines ..i.e. import cgi and cgi.test() Your cgi is being displayed rather than executed. The configuration options for Apache are so complex, that entire books have been written about configuring it... and Gerhard's suggestion only works on Windows platforms (AFAIK). You didn't name your platform, did you? Or did I just miss it? You need to verify that Apache 1) recognizes .py files as CGI scripts, and 2) allows you to run a CGI in the folder you're putting it in. You probably should put your script in the cgi-bin directory to start with. If you are on a Unix/Linux system, you need to make sure that the script is marked executable. Really, I think you need to spend some time with the Apache docs. It isn't a Python problem per se. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From martin at v.loewis.de Mon Sep 16 01:43:05 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Sep 2002 07:43:05 +0200 Subject: Source code References: Message-ID: Gerhard H?ring writes: > You should perhaps reconsider if and why you need to hide your source > code. You should also recognize that, if your computer can execute and perform a certain algorithm, users can always observe simulate the computer operations, thus breaking any protection scheme. You'll have to give your customers a sealed computer and no permission to install additional software, or communicate with the internet, if you want to reliably prevent them from analysing your program. Regards, Martin From walterm at parque.homelinux.net Thu Sep 19 20:01:48 2002 From: walterm at parque.homelinux.net (Walter Moreira) Date: Thu, 19 Sep 2002 21:01:48 -0300 Subject: RPy for Windows (unstable version) Message-ID: <20020920000148.GA5899@parque.homelinux.net> Hi. I have uploaded a Windows version of RPy to SourceForge. It is very unstable (I'm not sure whether it even works on a Windows other than mine :-) Please, send me your comments or problems. The next release (mid or end of october) will be a real one. Download at http://sourceforge.net/projects/rpy Two important problems with this release: 1. It doesn't locate the R dll's. You may need to copy R.dll to some location. Mine is 'Program Files\r\rw1404\bin\R.dll' 2. It only works from the DOS prompt, because the I/O is directed to console. Regards: Walter 1. WHAT IS RPy? RPy is a very simple, yet robust, Python interface to the R Programming Language (http://www.r-project.org). It can manage all kinds of R objects and can execute arbitrary R functions (including the graphic functions). All the errors from the R language are converted to Python exceptions. Any module that later were installed on the R system, can easily be used from within Python, without introducing any changes. From brian at sweetapp.com Thu Sep 26 17:38:14 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 26 Sep 2002 14:38:14 -0700 Subject: Who knows somefunction? In-Reply-To: <3D937B08.4090704@aon.at> Message-ID: <00d701c265a5$053d0710$df7e4e18@brianspiv1700> > Is there a function in Python > for which > > something is (id(something)) > > returns invariably true? Nope. You might want to consider creating your own dictionary to map ids to the objects that you are interested in. Cheers, Brian From thorsten at thorstenkampe.de Fri Sep 13 16:05:45 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 13 Sep 2002 22:05:45 +0200 Subject: Coding Style: Quotes References: Message-ID: * John Waycott > I'm curious if others have adopted any standards for choice of single vs. > double quotation marks to delimit strings. A look through the standard > library reveals the choice of one over the other is rather arbitrary. I > suspect it really makes no difference, but the question has come up during a > code review. Python itself seems to "prefer" single quotes slightly: 1: >>> "String" 1: 'String' 2: >>> Thorsten From martin at v.loewis.de Wed Sep 18 17:24:26 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Sep 2002 23:24:26 +0200 Subject: Remarks to Python 2.3 References: <20020918222421.328088eb.use-net@schabi.de> Message-ID: aahz at pythoncraft.com (Aahz) writes: > Normally, I tell people posting to python-dev that they're in the wrong > place and should go to c.l.py. However, this time, I think the reverse > suggestion is in order: you should post your questions to python-dev. Or, better yet, submit bug reports. Regards, Martin From sross at connectmail.carleton.ca Wed Sep 25 23:18:59 2002 From: sross at connectmail.carleton.ca (Sean Ross) Date: Wed, 25 Sep 2002 23:18:59 -0400 Subject: Removing all occurences of a character from a string. References: Message-ID: <3%uk9.7131$l44.1367805@news20.bellglobal.com> True. In fact, I will be using a dictionary as you say. However, before I could use the dictionary in the manner you've indicated it was first necessary, or at least preferred by me, to remove the single quotes around the attribute name and attribute values. Thanks to the suggestions here, that is accomplished. And, yes, the list of lists has since been converted into a dictionary with attribute name keys and list of attribute values. Although, I'm still working on my solution to the larger problem (making a decision tree), and I may choose to change the dictionary keys to indexers into my data set. Anyway, that's neither here nor there. For now, let me thank you all again for your time, Thanks, Sean "John Hunter" wrote in message news:mailman.1032965672.24886.python-list at python.org... > > From the example you gave, I was wondering if a dictionary might be a > more suitable data structure: > > attr = { "gill-attachment" : ["a", "d", "f", "n"], > "gill-spacing" : ["c", "d", "w"], > "gill-size" : ["b", "n"] > } > > print attr["gill-size"] > > John Hunter > From bloke at ii.net Tue Sep 17 21:17:01 2002 From: bloke at ii.net (Rob Hall) Date: Wed, 18 Sep 2002 09:17:01 +0800 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <6_Ph9.479711$q53.16315681@twister.austin.rr.com> Message-ID: <3d87d3f9$0$28706@echo-01.iinet.net.au> > Well, our shop is win32 only, but on a personal level I'd like to be more > flexible (I mostly use Linux at home). Isn't Tk still considered the > "official" GUI lib? > > For a newbie, what's easier, Tk or wxWindows? Yes, tkinter is the official one, but many believe it should be wxPython (www.wxpython.org) . wxPython is an extremely good x-platform implementation. It is fast, with a native look and feel. wxpython also has some good ide packages. Boa is pretty good. PythonCardPrototype is also very good. If you use rational rose, I've started work on a python implementation. It will also work with visual modeller. Rob From gmuller at worldonline.nl Thu Sep 12 16:20:37 2002 From: gmuller at worldonline.nl (GerritM) Date: Thu, 12 Sep 2002 22:20:37 +0200 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> <3D7FFC43.10002@something.invalid> Message-ID: "Russell E. Owen" schreef in bericht news:alqiue$1ejo$1 at nntp6.u.washington.edu... <...snip...> > True. It would help if the command callback sent an arguement that > identified the widget (making it look a bit more like an event binding). > In any event, it doesn't and command is unfortunately still the best way > to handle button widgets. In a recent thread it was pointed out that you can also bind to s function of a specific object instance. Out of the top of my head: Class A: def printarg( self, arg ): print arg anA = a() functionBoundToInstance = anA.printarg functionBoundToInstance("Hello Python") Hello Python this would work also for widgets, command = aWidget.activate Sorry didnot try it out yet :-) regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From Oschler at earthlink.net Fri Sep 6 15:15:37 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Fri, 06 Sep 2002 19:15:37 GMT Subject: Interapp communication under Python[Linux]? References: Message-ID: wrote in message news:mailman.1031334429.8860.python-list at python.org... > On Fri, 6 Sep 2002, Robert Oschler wrote: > > It _sounds_ like you want the separate pieces to act as if they were all > one giant process, so maybe really linking them together is the way to go. > Personally I really like a socket-based approach (roll your own protocol > or use XML-RPC/SOAP/etc). > > Putting such questions aside, I'd first evaluate your solutions in terms > of difficulty in Java and C++ because all of the ones you listed are > pretty easy in Python. > > -Dave Dave, Currently, most of the modules external to Python will either do a large intensive database lookup, or a heavy esoteric calculation. There will be frequent calls to them, but based on what I just said you can see that the percentage ratio of the time it takes to receive the request and then return an answer to Python, versus the lengthy operation itself, will be quite large. (So pretty much any of the communication strategies I outlined won't be signicant when it comes to the overhead of the call itself, regardless of the protocol used.) Yes I too really like the socket approach, although setting up the data object transmission format, especially the quality control and validation parts of it, and creating a robust async receipt mechanism on the client side, is a headache. thx From roffe at aqualene.uio.no Sun Sep 1 03:12:36 2002 From: roffe at aqualene.uio.no (Rolf Marvin Bøe Lindgren) Date: Sun, 01 Sep 2002 09:12:36 +0200 Subject: [Q] win32com/Excel Message-ID: I would like to emulate this Visual Basic statement from Python, using Com: Range(Range("A1"), ActiveCell.SpecialCells(xlLastCell)).Select this statement selects the active worksheet (which is, incidentally, not similar to UsedRange). any clues? thank you, -- Rolf Lindgren http://www.roffe.com/ roffe at tag.uio.no From loewis at informatik.hu-berlin.de Fri Sep 13 06:12:27 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 13 Sep 2002 12:12:27 +0200 Subject: no RHL 7.1 RPMs for python2.1 References: Message-ID: "Ben Gerblich" writes: > Why now does the RPMs for Python2 not appear on python.org? Because they are contributed, instead of being released by Python Labs. > Is there a known problem? No. Regards, Martin From peter at engcorp.com Wed Sep 18 18:56:10 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Sep 2002 18:56:10 -0400 Subject: Source code References: Message-ID: <3d89047d$1@news.sentex.net> Bradley D. Larson wrote: > I might have missed it... (I read most of the posts on this subject). > Why not just use a significant info registration key. The registration > key would be sensative to date, registered name and/or some other > piece of information that would be required to get the software to work. > > At least then (if the person buying the pirated software) would have to: > > 1. Set their computer date BACK to the DATE of the original reg key use. > 2. Enter the name of the original owner. > 3. Enter the other information (ie. version, address -- if they move they get a > new regkey). > > This would do several things. > > 1. Become pretty obvious to the purchaser that the software is pirated. > 2. The pirater and/or purchaser would have to know all items relating to > the reg key. You overlook the very common situation of pirates seeing this as a challenge and breaking the program enough to install a fake registration key that has user name "Johnny H4X0R" etc, and posting it to a dozen warez sites. Then all the other pirates download it and us it without any original registry key involved. Given the speed with which every program with such protections makes it onto the warez sites with broken protection, you have to wonder why people still think this is of much use. -Peter From fredrik at pythonware.com Thu Sep 5 13:27:13 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Sep 2002 17:27:13 GMT Subject: Max line coords canvas.create_line() can display? References: <5pid9.5885$e5.1033551@newsb.telia.net> <117880a1.0209042325.68193ca7@posting.google.com> Message-ID: J?rgen Hansen wrote: > the small program below fails to draw the line, when it is called with > an integer larger than or equal to 16384. I only tested the script on > a Windows 98 machine with Python 2.1.3. this works just fine under Windows 2K. a little digging reveals that this is a limitation of the Windows 9X GDI implementation: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/linecurv_10bp.asp Windows 95/98/Me: Polyline cannot draw more than a certain number of points. The limit depends on the line width (that is, the width of the pen selected into the DC), as shown in the following table. Line width -- Maximum points allowed line width is 1 -- 16K line width > 1 (that is, wideline) and device supports wideline -- 16K line width > 1 but device does not support wideline -- approximately 1360 (that is, approximately 16K / 12) Any extra points are ignored. To draw a line with more points, divide the data into groups that have less than the maximum number of points and call the function for each group of points. Remember to connect the line segments. (looks like a 64k limit somewhere in the device driver interface) From richiereynolds at GETRIDOFTHISntlworld.com Sun Sep 29 18:10:48 2002 From: richiereynolds at GETRIDOFTHISntlworld.com (Richard Reynolds) Date: Sun, 29 Sep 2002 23:10:48 +0100 Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> Message-ID: check out www.zoneedit.com "mike henley" wrote in message news:576c1752.0209291326.56dcdf31 at posting.google.com... > I remember a while ago reading about tim burners-lee and how his > vision of the WorldWideWeb as a medium where all can freely and easily > publish information has not materialized properly, and i felt it so > strongly over the past week when trying to look at options for hosting > a website. Hosts are either expensive or limit you in terms of what > languages, modules, applications, and OSs you can use. They also limit > you in terms of space, bandwidth used per period, number of executions > of CGIs... etc. Some of those who give good deals, seem difficult to > trust with either your credit card number or your content. > > I wish i can just use my own computer, with whatever technologies I > choose, keeping my content that i build up over time safe here on my > own machine, but unless you have a broadband connection this is not > possible. It may be possible using a dynamic DNS provider, but then > again either they add cost, end up with an ugly URL, and, most > importantly, there's no way for others to know when you get online. So > here comes the idea that occured to me, and i post it here to ask if > you know of an application that already provides this functionality, > then please tell me what it is, or if you think it is worth doing on > an open source basis, or even proprietary, in which case i invite > anyone to do so, or if you think it's a completely stupid and > impossible idea, then perhaps you can please tell me why. > > You probably guessed if you read as far as the second paragraph that > what i'm thinking about is an application functionality that enables > instant messaging to provide the dynamic DNS functionality. So instead > of giving others a URL I can just give them an IM username they can > add to their client, and when i go online, through my humble dial-up > connection that changes IP whenever i log in, they'll be aware of my > presence, and be able to connect to a server i host on my machine. > > It sounds like a simple thing; IM presence, automatic IP query of my > username, click on my username and or use a contextual menu option or > whatever and a browser launches to go to the site i'm hosting on my > machine. Perhaps it can use existing open-source platforms, such as > jabber or gnutella, or as an add-on to existing open-source > applications/clients. Basically what i'm suggesting is a little tool > to enable a server such as apache to join the whole IM/p2p thing and > have "presence". The more automated it is, and the easier it is, the > better. I think such a functionality will be especially useful for > certain uses, in my case it will be hosting a wiki, as i leave my > machine online a lot through my dial-up, can't predict the number of > executions of CGI or the amount of space needed, wish to be free to > use whatever wiki application is best for my needs and in whatever > language regardless of what a host will support, and do not wish to > pay a monthly fee, extra charges, setup fee or a domain registration. > Perhaps there can be other areas where it is useful, and i'm sure > there are other areas where it will not be suitable. Perhaps there can > also be a simple way to enable a page hosted in such a way to be > submitted to search engines, i haven't thought about that yet, but > tell me if u see any. > > What do you think? already done, worth doing, stupid, or impossible? > (p.s. please also let me know if there are other newsgroup to which > posting this will be a good idea) From quiteblack at yahoo.com Thu Sep 19 06:11:58 2002 From: quiteblack at yahoo.com (black) Date: Thu, 19 Sep 2002 03:11:58 -0700 (PDT) Subject: surface of pygame Message-ID: <20020919101158.58549.qmail@web21305.mail.yahoo.com> Hi,all~ I touched something about pygame today and confused with surface type. I didnt remember surface data type when learning python, and it displays strange to me, for example, I create a new surface by loading a picture as follows: pygame.image.load("myPic.bmp") it works fine but I coulnt see any surface appears on the screen. any ideas ? --------------------------------- Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxm at mxm.dk Mon Sep 9 10:22:13 2002 From: maxm at mxm.dk (Max M) Date: Mon, 09 Sep 2002 16:22:13 +0200 Subject: Zope Status? References: <3D7C4833.2080308@mxm.dk> Message-ID: <3D7CAE95.7090202@mxm.dk> Jeff Sasmor wrote: From what I've seen, Zope 3 is more regular and better organized than Zope 2, but it _is_ different. Anyway, that's all I meant. Nothing bad, just inevitable. Anyway, it's just my opinion, so it doesn't matter all that much! I havn't poked round that much in Z3 either, but from the example product in the "Products3" repository in cvs I could actually go in and read and understand what was going in from the source only. In current Zope I have never been able to do that ;-) It seems almost as simple as Python itself. regards Max M > > > From member at dbforums.com Mon Sep 16 21:06:56 2002 From: member at dbforums.com (hpyhpy) Date: Tue, 17 Sep 2002 01:06:56 +0000 Subject: A question about C/API of python. References: <1818979.1032155554@dbforums.com> Message-ID: <1822704.1032224816@dbforums.com> I try and thanks. -- Posted via http://dbforums.com From brueckd at tbye.com Fri Sep 6 14:53:05 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 6 Sep 2002 11:53:05 -0700 (PDT) Subject: Interapp communication under Python[Linux]? In-Reply-To: Message-ID: On Fri, 6 Sep 2002, Robert Oschler wrote: > My Python app will talk to 3 or 4 modules written in Java and C/C++. > Fortunately I have the source for the Java and C/C++ modules and I have > experience in both languages. Currently the external modules have no > provision for being accessed outside of the process they are running as. So > I'm wondering what the best protocol would be used to "glue it all > together". There a dizzying array of possibilities: > > 1) Have everybody talk to each other via SOAP (web services). > 2) Have everybody talk to each other via XML-RPC (Don't know much about this > method). > 3) Use Boost's SWIG interface for C++ to link the C/C++ modules to Python. > How to link to Java in the same manner? > 4) Use "sockets" and my own custom protocol for everybody. > 5) Code in Jython instead and use various methods above to talk to C/C++ > modules from Jython app. > 6) CORBA? (yikes!) > > So as I said, a lot of ways to get things done. I'd like to hear from those > of you that have actually done a lot of cross-app communication with Python > on what your experiences have been, and the pros and cons you encountered. It depends on the nature of the communication between the various parts. Is the communication lots of frequent messages? Are the messages large or small? Does communication mostly flow in one direction? It _sounds_ like you want the separate pieces to act as if they were all one giant process, so maybe really linking them together is the way to go. Personally I really like a socket-based approach (roll your own protocol or use XML-RPC/SOAP/etc). Putting such questions aside, I'd first evaluate your solutions in terms of difficulty in Java and C++ because all of the ones you listed are pretty easy in Python. -Dave From jjl at pobox.com Sat Sep 7 09:04:43 2002 From: jjl at pobox.com (John J. Lee) Date: Sat, 7 Sep 2002 14:04:43 +0100 Subject: PyQT picture display In-Reply-To: References: Message-ID: On Fri, 6 Sep 2002, Jim wrote: > I've a widget with three buttons and a label. I want to display a JPEG > picture when either of the first two buttons is clicked. When I run the > code below, the widget displays on screen but when either button is clicked, > the picture does not appear( the text in the label disappears as it should Haven't read your code, but have you checked that JPEG support is compiled into your Qt library? It's optional. John From HRG at popmail.com Thu Sep 19 00:54:51 2002 From: HRG at popmail.com (HRG) Date: Thu, 19 Sep 2002 04:54:51 GMT Subject: cephes.pyd for python2.2? Message-ID: Does anybody have cephes.pyd compiled for python 2.2? Thanks, Horatio From jb at cascade-sys.com Fri Sep 27 05:05:37 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 27 Sep 2002 02:05:37 -0700 Subject: Can't suspend a thread? References: Message-ID: <3D941F61.3090108@cascade-sys.com> Tim Roberts wrote: >Hmm, you're quite right. I didn't realize you could suspend another thread >in Win32. The documentation does caution against using it in anything >other than a debugger, but it certainly exists. > Yeah, it's possible but I question the wisdom of doing it. Starting and stopping threads altogether or using synchronization primitives seems the better way to go in every case I can think of. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From rsrchstr at msn.com Mon Sep 30 15:35:08 2002 From: rsrchstr at msn.com (mike henley) Date: Mon, 30 Sep 2002 20:35:08 +0100 Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> <7l0gpugn6lehtmj46a1e5a0stg2cfmreqa@4ax.com> Message-ID: no comment. "TGOS" wrote in message news:7l0gpugn6lehtmj46a1e5a0stg2cfmreqa at 4ax.com... > > On Mon, 30 Sep 2002 00:40:24 +0100 "mike henley" > wrote in comp.lang.java.programmer: > > >> To publish information, all you need is writing it into a HTML file and > >> a server that hands out the HTML file when getting asked for it. > >> You don't need any special languages, modules or applications on the > >> server to publish your information, other than the ones already present > >> on a web-server. > > > > "other than the ones already present on a web-server", exactly! i want to be > > ably to use whatever language, modules or applications i choose, and over > > the year use others, freely. > > You just put your HTML file online, how this is served to users > requesting it is non of your business. Your webhost guarantees that it > is served. It doesn't matter if the WWW server is Apache or Zeus. > > > if i choose perl, php, or even python, ruby or tcl, then i want to be > > able to do that. > > Can use all these on my webhost. However, you need NONE of these to > publish information and that's all you want to do according to your own > words. > > > if i want to use mysql or something else that i prefer, then i want > > to have the freedom to do that. > > Can use that, too. But again, not necessary for your described task. > > > > > Agree, if that's all you want, but beyond keeping some text online, it's > > difficult. > > Keeping some text online (and/or some pictures) means publishing of > information on the WWW. > > > > > my post is not about tim-burners lee or what he said. > > To quote yourself: > > >>> I remember a while ago reading about tim burners-lee and how his > >>> vision of the WorldWideWeb as a medium where all can freely and > >>> easily publish information has not materialized properly > > This vision is already reality, make a HTML file, say what you have to > say and put it on some server. Information... published. His vision did > not include the usage of any script or database, as these are not > necessary to publish information. > > > > > my post is also not about the economics or politics of hosting; > > Of course it is. You demand to get something for free, others (webhosts) > must pay for. How shall this work? > > Despite that, you already pay for your Internet connection, don't you? > So when you publish something from your own PC, it's not for free > either: You pay the fees for your dial-up account! And if anyone would > publish from home through a dial-up account, these fees would raise > noticeably very soon. > > > this sounds much like the open source vs proprietary software arguments. > > OpenSource is "free" software, but "free" like in "free speech"; not > "free" like in "free beer". Nowhere is written that a service must be > offering OpenSource software to you for free (without any costs > involved). They can charge you whatever it pleases them. OpenSource just > means that they will provide the source code for the software as well > (the source code is not kept a trade secret). And often it means that > you may use this source code in your own software, as long as it will be > OpenSource again (GPL, but GPL != OpenSource; not all OpenSource is GPL > software). > > > > >> IRC, ICQ, AIM... the list is endless. > > > > Yes, that is what my post is about, combining instant messaging presence > > with dynamic DNS. > > Then you must create your own shiny, new instance message service, as > the already existing providers like ICQ (belongs now to AOHell, doesn't > it?) and AIM (always belonged to AOHell) don't allow you play with > *their network*. They write the server software, they write the client > software, they alone decide about the network protocol (at least they > did for years, now they pretend to seek for open standards, all bullshit > IMHO). > > So what you are looking for is not a new software, but a new SERVICE. > How will this service be financed if it shall offer everything for free? > AOHell can finance their free services, they make enough money from 12 > millions moron stupid enough to sign-up for the joke they call "Internet > Access". > > > > >> Allow users to see your IP address when you are connected to an IRC > >> network or to ICQ for example, then they can enter your IP address into > >> their browser address bar and will get a webpage if you run a webserver > >> and are not behind a firewall that blocks port 80. > >> > > > > Perhaps it can be possible to do a little application to automate this. > > Perhaps users that are too lazy to copy/paste your IP address into their > browser should go to hell? > > -- > TGOS From cliechti at gmx.net Fri Sep 27 13:30:38 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Sep 2002 19:30:38 +0200 Subject: file open verification References: <9eabe547.0209270710.17ca112d@posting.google.com> Message-ID: python473 at yahoo.com (John Howard) wrote in news:9eabe547.0209270710.17ca112d at posting.google.com: > Two questions - somewhat related: > > Situation - I have several files on an apache server that are being > accessed by > python programs that are receiving data from html forms. > > q1: How can the status of a file be checked? If two forms have been > submitted > and the data is being added to a common file, how do I know that data > from both forms are being written correctly to the common file? don't ever write simultaneous from two processes to one file. your choices are: - use "locks", so that only writes at a time - one server writes the file, logs are directed to that server (like syslog on linux) - use a database - ... all these options ensure that one writes after the other. avoiding problems is better than fixing. > q2: Related to above - really more of a cgi question - does the apache > server keep all these file accesses separate some way? don't know apache. if you manage to limit it on one thread, only one can access the file. but iin that case the performace of the server is poooooor ;-) chris -- Chris From aleax at aleax.it Wed Sep 25 05:47:08 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 09:47:08 GMT Subject: how to check if a function signature "matches" without calling the function? References: Message-ID: Mike McCandless wrote: > Does Python 2.2.1 make it possible for me to see some details about > the expected arguments that a function takes, without actually calling > the function? Yes. inspect.getargspec lets you learn all you need: import inspect argnames, has_varargs, has_kdws, default_values = inspect.getargspec(func) > Specifically, if I have a function or method object, and I have a > tuple + dict of arguments I'd like to apply it on, is there a function > I can call that would check if the tuple + dict can be properly > "coerced" to the formal parameters? You still have some work to do for your checking, but it doesn't seem to be much. You need to check you supply each mandatory argument exactly once, and each optional argument 0 or 1 time; you can have other positional args only if has_varargs, and other named args only if has_kwds. E.g. for clarity: class NoWay(Exception): pass def times_supplied(argname, argposition, atuple, adict): return (argname in adict) + (argposition < len(atuple)) def check_args(argnames, default_values, atuple, adict): number_mandatory = len(argnames) - len(default_values) for pos in range(len(argnames)): name = argnames[pos] n = times_supplied(name, pos, atuple, adict) if n<1 and pos1: raise NoWay, "Argument %s (%s) given twice" % (name, pos) def check_funcargs(func, atuple, adict): import inspect names, has_varargs, has_kdws, defaults = inspect.getargspec(func) check_args(names, defaults, atuple, adict) if not has_varargs and len(atuple)>len(names): raise NoWay, "Supplied %d positional args, max is %d" % ( len(atuple), len(names) ) if not has_kwds: for name in adict: if name not in names: raise NoWay, "Unknown argument %s" % name You can express this more concisely &c, of course, or use other means than raising a dedicated exception to diagnose problems (I only diagnose the first problem if any, that can be tweaked too, of course). Alex From peter at engcorp.com Tue Sep 3 23:44:28 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 03 Sep 2002 23:44:28 -0400 Subject: default tuple unpacking? References: Message-ID: <3d758180$1@news.sentex.net> Huaiyu Zhu wrote: > It is often very convenient to have default arguments such as > > def func(a, b, *c): ... > > Is there a way to use this in statements too? Examples: > > a, (b, *c), *d = e Presumably d would end up as () if there was nothing to put there, just as in the default argument syntax for functions? > for a, *b in c: ... > return a, *b These are all very readable to me, having learned to grok the basic "def func(a, b, *c):" syntax. I'd be in favour of seeing this added, as the first idiom above is something I've needed fairly often. Is there an analog for the **x syntax? I hope nobody suggests that having >>> d = { 'a' : 5, 'b' : 7 } >>> **d should be equivalent to >>> a = 5 >>> b = 7 :-) -Peter From Michael.Sparks at rd.bbc.co.uk Fri Sep 13 06:55:09 2002 From: Michael.Sparks at rd.bbc.co.uk (Michael Sparks) Date: Fri, 13 Sep 2002 11:55:09 +0100 Subject: wrapping yield ? References: Message-ID: "Duncan Booth" wrote in message news:Xns9288759449799duncanrcpcouk at 127.0.0.1... > The syntax wouldn't look quite so bad if your function wasn't returning a > value. Problem is, it would in most situations, also I'm trying to keep the number of generators to a minimum whilst a lower overhead than things like threads and processes if I had several 10s of thousands going, keeping throughput up may become an issue. (Hence the reason for wanting the functions called part of the same generator rather than a separate, extra one) > There definitely isn't any way to put a yield in a function and not have it > turn into a generator. When you yield from a generator, only a single frame > is saved, not a stack, so you can only yield from the outer loop. Ah... that makes sense then...Pity - after all, "all you'd need" (looking at it simplistically) is a marker in the stack frame to tell the system how much of the stack to save. Amiga E had something very similar (from a use perspective) for determining how far back to throw exceptions without requiring the equivalent of try/(except|catch) blocks. Thanks! Michael. From wlfraed at ix.netcom.com Sun Sep 22 16:58:07 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 22 Sep 2002 13:58:07 -0700 Subject: Python GUI app to impress the boss? References: Message-ID: <0talma.rq3.ln@ix.netcom.com> ChrisBarker fed this fish to the penguins on Wednesday 18 September 2002 10:01 am: > > just like VB. > Just located one of my references (O'Reilly: VB & VBA). Based upon the description, VB /currency/ data type is a 64-bit (binary) integer with implicit scaling for FOUR decimal places -- so one STILL has to be concerned with rounding to get to whole cents. The other "applicable" data type is /decimal/, which appears to be a 28-digit packed BCD format. (Though where VB stores the sign and decimal point info I don't know -- book says the type takes 14-bytes). -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From loewis at informatik.hu-berlin.de Tue Sep 3 12:28:26 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 03 Sep 2002 18:28:26 +0200 Subject: xml question References: <3D74CB6B.7697013E@millfilm.co.uk> Message-ID: Eric Texier writes: > From Disk: (unicode) > N1 [(None, u'fileName'), (None, u'OutputType'), (None, u'name'), (None, > u'UId'), (None, u'version'), (None, u'node')] > From Memory: > N2 ['node', 'version', 'UId', 'fileName', 'OutputType', 'name'] > > What will be the simplest thing to do in this case? It appears that when parsing from disk, you have used a namespace-aware mode, and when building the document from memory, you use a namespace-unaware mode. I recommend to use the same mode of operation for both cases. To get namespace-unaware parsing from disk, assuming you use minidom.parse, you should create a SAX parser that has the namespaces feature turned off. HTH, Martin From rajarshi at presidency.com Tue Sep 10 09:56:53 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Tue, 10 Sep 2002 09:56:53 -0400 Subject: os.tempnam() warning Message-ID: Hi, whenever I use the function os.tempnam() I get /usr/local/adapt/bin/striphin.py:14: RuntimeWarning: tempnam is a potential security risk to your program outfilename = os.tempnam() The C library advises against using tempnam() and suggests using mkstemp(). Is there any Python equivilant? (I use Python 2.2) Thanks, Rajarshi Guha From maxm at mxm.dk Wed Sep 18 15:31:30 2002 From: maxm at mxm.dk (Max M) Date: Wed, 18 Sep 2002 21:31:30 +0200 Subject: cgi binary upload References: Message-ID: <3D88D492.1080909@mxm.dk> Robin Becker wrote: > I know there's a lot of skilled people using python so I thought I'd ask > how one can get an HTML page to do a proper binary upload using the > form tag. We want to do this for PDF documents, but it > seems as though IE/Mozilla/Netscape clients insist on putting > > Content-Type: data/pdf > > or similar headers into the multi part file section and the files have > their line endings corrupted. That should not be a problem. I have not heard of the cgi module having those kind of problems at least. > On the receiving side using cgi.py we are certainly seeing some > filetypes OK eg zip files, but surely we should be able to fix this more > reliably. cgi usually is reliable. > I should note that experimentally renaming the file as > xxx.xpdf made no difference as the mime type was being correctly > determined by the browser. I don't think your problem is with Python. You are probably having a problem somewhere else in the chain. At least we should see some code, or you need to be more specific. regards Max M From jdavis at empires.org Fri Sep 27 23:34:06 2002 From: jdavis at empires.org (Jeff Davis) Date: Sat, 28 Sep 2002 03:34:06 GMT Subject: Python Process that can survive References: <571739c3.0209270629.10575f47@posting.google.com> Message-ID: $ python -c " > import time > time.sleep(100) " & That seems to get me a background process. Can you describe your problem in more detail? perhaps show what you did with perl? Regards, Jeff Davis Christopher Peery wrote: > Alright... I love python but I think I may have found a definite > problem. I can't seem to run a python process, kick it to the > back-ground, and then kill the terminal that started it. With most > other things, the python process would keep running in the > back-ground regardless. For me, the process always dies with the > terminal. > > So my question: is there a way to separate a python script from the > underlying terminal so that this will not happen. > > I'm hoping for some scheme that's supported by the language. I've > found a few hacks on-line where the python process is daemonized > but this requires shutting down all the standard io streams. > There's got to be a better way especially since it can be done in > Perl very easily with no special tricks. > > By the way, I'm doing this on a linux box. > > Chris From h_schneider at marketmix.com Fri Sep 27 03:12:55 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Fri, 27 Sep 2002 09:12:55 +0200 Subject: _winreg.DeleteValue - Permission denied ... Message-ID: Hi, go a prob here with _winreg. When I try to delete a registry key, I get a WindowsError (Errno5) / Permission denied, even thought I am logged in as admin. Deleting the same key with regedit works. The function looks like this: def del_cfg_path(self): key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,'SOFTWARE\TEST\SUBTEST) _winreg.DeleteValue(key,"TESTVAL") _winreg.CloseKey(key) Any ideas ? Thanks a lot, Harald From peter at engcorp.com Tue Sep 3 08:17:01 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 03 Sep 2002 08:17:01 -0400 Subject: Python to surpass C performance by 2030 References: Message-ID: <3d74a81f$1@news.sentex.net> Dan Bishop wrote: > Erno Kuusela wrote in message news:... > >>just for fun i ran pystone under python versions since 1.5.2 to >>current cvs. here are the results: >> >>[benchmark results snipped] >> >>since 1.5.2 is about 4 years old, the improvement per year is about >>13.2% on average. if we assume that 1.5.2 is 50 times slower than >>C (probably conservative?), then at 13.2% per year since 1998 it >>will add up to 53x improvement in 32 years. >> >>i wonder if this would be a good application for the time machine... >> >>learn python today, and in 28 years you will have a job writing >>the speed-critical parts of c programs in python :) > > > Before that could ever happen, the Python interpreter would have to be > written in something other than C. Clearly if it will be 53x faster in 32 years even if written in C, then it should be rewritten in Python for another 53x speedup! Imagine the possibilities. You could even implement another virtual machine underneath the current one, to increase speed even more, provided *that* one was executing Python bytecode as well. Scary really. I understand this plan was discussed at a recent PSU mee From erikprice at mac.com Fri Sep 6 17:07:20 2002 From: erikprice at mac.com (Erik Price) Date: Fri, 6 Sep 2002 17:07:20 -0400 Subject: successor to htmllib Message-ID: I noticed that the htmllib module is really best suited to HTML 2.0 documents. I was wondering if there was a newer (4+) HTML or even XHTML parsing module in development right now. (By XHTML parsing lib I mean perhaps an XML parser that is specifically written for the XHTML 1.0 DTD. I realize that any XML parser -should- work.) Erik -- Erik Price email: erikprice at mac.com jabber: erikprice at jabber.org From JeffH at ActiveState.com Wed Sep 11 12:57:51 2002 From: JeffH at ActiveState.com (Jeffrey Hobbs) Date: Wed, 11 Sep 2002 16:57:51 GMT Subject: Tkinter, updateStringProc for type font References: <1907a5e4.0209040455.64ae73b1@posting.google.com> Message-ID: <3D7F772C.80205@ActiveState.com> Pier Paolo Glave wrote: > I'm facing a problem with my Python program, which uses Tkinter to > interface Tcl/Tk. > I sometimes get this error message from Tcl: > "UpdateStringProc should not be invoked for type font". > As a consequence, the application crashes with SIGABRT (6). > > I'm using: Python 2.2, Tcl/Tk 8.3.3-69. > > I've seen in the tcl sources that this happens when a function named > Tcl_GetString() is called for a "type" which has the "byte" field set > to NULL, and no "updateStringProc" function pointer: this seems to > happen for Tk type "font", sometimes in my application. > Anyway, I'm not able to understand more. > > Has anyone encountered this problem before? Do you have any other C extensions in your application? I've not seen this occur myself, except in bugs where other C extensions were abusing Tcl objects internally. -- Jeff Hobbs The Tcl Guy Senior Developer http://www.ActiveState.com/ Tcl Support and Productivity Solutions Join us in Sept. for Tcl'2002: http://www.tcl.tk/community/tcl2002/ From gleki at gol.ge Thu Sep 5 05:39:00 2002 From: gleki at gol.ge (Giorgi Lekishvili) Date: Thu, 05 Sep 2002 11:39:00 +0200 Subject: SWIG 1.3.14::: import error Message-ID: <3D772634.575A0AEB@gol.ge> Hi all! I well may have been missing something in new features of SWIG. Any way, I have not found this in manual. When I try to import a newly wrapped module, I get this error: >>>import PyArray Traceback (most recent call last): File "", line 1, in ? ImportError: dynamic module does not define init function (initPyArray) *** I guess _PyArray is linked somehow with libPyArray.so? What and where did I miss simething? I thought I did everything as I should: 1. I made PyArray.i 2. swig -c++ -python PyArray.i 3. g++ -c PyArray_wrap.cxx -I/usr/local/include/Python2.0 4. g++ -shared Array.o PyArray_wrap.o -o PyArraymodule.so Thank you in advance. Regards, Giorgi From fperez528 at yahoo.com Mon Sep 23 13:12:07 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 23 Sep 2002 11:12:07 -0600 Subject: numpy array assignment References: Message-ID: John Hunter wrote: >>>>>> "John" == John Hunter writes: > > John> I have a 2 dimensional array X which is NxM and a 1 > John> dimensional array v which is Nx1. I want to assign v to the > John> k-th column of X > > This is what I've come up with so far -- if there is a better/faster > way, please let me know.... > > import Numeric > > def putcol(k, Z, v): > (n,m) = Z.shape > Numeric.put(Z, k+m*Numeric.arange(n), v) > > def putrow(k, Z, v): > (n,m) = Z.shape > Numeric.put(Z, k*m+Numeric.arange(m), v) > > > Z = Numeric.zeros( (3,5), Numeric.Float ) > vc = Numeric.ones( (3,1), Numeric.Float ) > vr = Numeric.ones( (1,5), Numeric.Float ) > > putcol(3, Z, vc) > putrow(1, Z, vr) > print Z How about: In [38]: z=Numeric.zeros( (3,5), Numeric.Float ) In [39]: z[1] = vr[0] In [40]: z[:,3]=vc[:,0] In [41]: z Out[41]: array([[ 0., 0., 0., 1., 0.], [ 1., 1., 1., 1., 1.], [ 0., 0., 0., 1., 0.]]) Cheers, f. From gerhard.haering at gmx.de Mon Sep 16 00:44:44 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Mon, 16 Sep 2002 06:44:44 +0200 Subject: pypgsql -- not preserving transactions ? In-Reply-To: References: Message-ID: <20020916044444.GA1566@lilith.ghaering.test> First, I'd recommend to ask questions like this on the pypgsql-user mailing list. You'll find the link on http://pypgsql.sf.net/ * Frank Miles [2002-09-16 03:15 +0000]: > I've discovered that the 2.0 version of pyPgSQL packaged with Debian/woody > doesn't preserve transactions (at least with Postgres). For example, if > a transaction consists of a series of INSERTs, and an error occurs partway > through the series, a COMMIT at the end of the series will result in the > INSERTs up to the erroneous one being thrown out (rollback), but unfortunately > those following the error being committed. I can't reproduce that behaviour here. What do you do to ignore the PgSQL.OperationalError? Or is it a different exception that gets thrown? > In looking at the imported code, there are comments about trying to > recover from a defective state, with the class variable > 'inTransaction' being cleared. > > Does any newer version fix this nonsense? This area of code hasn't changed up to 2.2, IIRC. Could you provide a test case with a minimal schema, minimal code and the output of your code. To see which SQL commands pyPgSQL sends, you can simply access pyconn.conn.toggleShowQuery, where pyconn is your DB-API connection object. This output would be useful, too. Also, which PostgreSQL server version are you using? -- Gerhard From mcherm at destiny.com Tue Sep 10 12:26:51 2002 From: mcherm at destiny.com (Michael Chermside) Date: Tue, 10 Sep 2002 12:26:51 -0400 Subject: Pickle problem References: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D10@hendrix.empolisuk.com> Message-ID: >>Are you trying to store the MatchObject returned by a call to >>a regular >>expression object's match() method? If so, it looks like you're >>forgetting the parens at the end of "re.compile(y).match". > No, I haven't forgotten the parentheses. I'd like to pickle the match method > of the compiled regular expression. Three different objects to consider. (1) "the compiled regular expression object": re.compile(y) (2) "the match method": re.compile(y).match (3) "the MatchObject, ie the results": re.compile(y).match() Objects (1) and (3) can be pickled, I don't think (2) can. Here's a quick summary of what they're there for. Using (3) will allow you to examine the results of the match. Using (2) will allow you to re-run the match on a different string. Using (1) will allow you to perform a match, search, findall, or other functions on any string. Since you can't pickle (2), I suggest storing (3) unless you need to re-run it on a different string, then store (1). -- Michael Chermside PS: If what you are trying to do is save in the pickle the exact way that the "match" method works because you are afraid that the maintainers of Python may come out with a new version of Python in which match works differently and is no longer backward compatible, and you want your code to still work the same way in this hypothetical new version of Python, then you really *DO* need to store (2). Unfortunately, it's still not possible (AFAIK). Fortunately, the maintainers Python wouldn't do that to you. From ifls at rz.tu-clausthal.de Mon Sep 30 02:08:27 2002 From: ifls at rz.tu-clausthal.de (Lutz Schroeer) Date: 30 Sep 2002 06:08:27 GMT Subject: Getting last char in string. References: Message-ID: CheapSkate wrote: : my Q now is how to get the last char??? >>> s = "Hello!" >>> print x[-1:] ! greets Lutz From benji_75 at hotmail.com Thu Sep 19 01:09:04 2002 From: benji_75 at hotmail.com (Ben Gerblich) Date: Thu, 19 Sep 2002 14:39:04 +0930 Subject: FIXED. try import except want lineno from Exception Message-ID: In the file "progfile.py", replace between the print start/end with: ---- self.userDefs[searchPath][file[:-3]] = {} try: self.userDefs[searchPath][file[:-3]]['class'] = __import__(file[:-3]) code = "object = self.userDefs[searchPath][file[:-3]]['class'].%s()" % file[:-3] exec code self.userDefs[searchPath][file[:-3]]['obj'] = object except Exception, e: errortext = e for badfile, badlineno, badfunction, badtext in traceback.extract_tb( sys.exc_info()[2]): pass # ask the user to 1.'skip' this MDF continue loading other MDF's # or 2. quit the application message = "The Module Definition File has an error.\n\n" message = message + "Filename: '%s'\n" % fullfilename message = message + "Line number: %s\n" % badlineno message = message + "Source Code: %s\n" % badtext message = message + "Function: %s\n" % badfunction message = message + "Error message: %s\n" % e message = message + "\n\nSkip this module, but load others?\n" message = message + "\nOr CANCEL the application?" response = wxMessageBox(message , "Confirm", wxOK | wxCANCEL| wxICON_EXCLAMATION, self) if response == wxOK: print ' ** Did not load this Module Definition File **' del self.userDefs[searchPath][file[:-3]] elif response == wxCANCEL: sys.exit(1) >From: "Ben Gerblich" >To: python-list at python.org >Subject: try import except want lineno from Exception >Date: Thu, 19 Sep 2002 13:53:39 +0930 > >I am importing module files, and want to catch an error (if any) and >print the filename and line number of the error. >The "Exception ,e" does not return, or does not have the attirbutes listed >above. It only returns e="line() takes exactly 2 arguments (3 given)" > >I think I want to use SyntaxError as it has the attributes: filename, >lineno, offset and text. >I have found no info on traceback. >With the code below, how do I find the **line_number**? >Thanks. >---- >[13:45:40]~/py/dev/import2:cat runme.py >from progfile import * > >[13:45:44]~/py/dev/import2:cat progfile.py >class Foo: > def __init__(self): > self.lines = [] > > def line(self,x): > self.lines.append( x ) > >print 'start' >try: > klass = __import__('module') > code = "object = klass.%s()" % 'Bar' > exec code >except TypeError, e: > print 'TypeError\n%s' % e >except Exception, e: > print 'Exception\n%s' % e >print 'end' > >[13:45:51]~/py/dev/import2:cat module.py >from progfile import Foo > >class Bar(Foo): > def __init__(self): > Foo.__init__(self) > print 'line-1'; self.line(20) > print 'line-2'; self.line(40,60) # <--- an error!!! > print 'line-3'; self.line(80) > >[13:45:57]~/py/dev/import2:python2 runme.py >start >line-1 >line-2 >TypeError >line() takes exactly 2 arguments (3 given) >end > >[13:46:07]~/py/dev/import2: > > >_________________________________________________________________ >Join the world?s largest e-mail service with MSN Hotmail. >http://www.hotmail.com > > >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ MSN Photos is the easiest way to share and print your photos: http://photos.msn.com/support/worldwide.aspx From mstenner at phy.duke.edu Wed Sep 18 17:27:13 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Wed, 18 Sep 2002 17:27:13 -0400 Subject: monetary applications (et al) In-Reply-To: ; from tg5027@citlink.net on Wed, Sep 18, 2002 at 05:35:32PM -0400 References: Message-ID: <20020918172713.A10897@phy.duke.edu> On Wed, Sep 18, 2002 at 05:35:32PM -0400, terry wrote: > I do admit to being OO inhibited, so maybe you could take it from this > short piece code and execution results, and, provide a brief > description of what you would put into this money class that would > eliminate this error message, while maintaining the code simplicity. While you're at it, please write me 4-liner that predicts the stock market's behavior. :) Take a look at this: http://python.org/doc/2.2.1/ref/numeric-types.html for how to emulate numeric types. -Michael > ------------------------------------------------- > class money: > def __init__(self,name): > self.name = name > > unitprice = money(100) > qty = 2 > amount = qty * unitprice > > terry at terry:~> python money.py > Traceback (most recent call last): > File "money.py", line 7, in ? > amount = qty * unitprice > TypeError: unsupported operand type(s) for *: 'int' and 'instance' > ------------------------------------------------- > > Support for mixed number types in expressions involving this money > class must come from somewhere - where? And, it must be capable of > determing and setting amount to be of class money to be consistent with > the rest of Python's complexity hierarchy for the handling of numbers. > > The rest of the problem is that the above is a trivial calculation. > What happens to your recommendation when faced with an additional > number type? > > taxrate = 0.06 > amount = qty * unitprice + (qty*unitprice)*taxrate > > As I see it, if Python had an intrinsic number type of 'money', the > logic for determing the results of the above calculation would be > easily determined and consistent with expectations, as in VB. > > Thanks for your time, > > terry > > -- > http://mail.python.org/mailman/listinfo/python-list -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From prouleau at impathnetworks.com Thu Sep 12 13:28:57 2002 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Thu, 12 Sep 2002 13:28:57 -0400 Subject: Is there a portable way to copy files in Python? References: Message-ID: <3D80CED9.6050703@impathnetworks.com> Oops... next time i'll lokk a bit more in the lib documentation... Thanks! Mark McEahern wrote: > [Pierre Rouleau] > >>Subject: Is there a portable way to copy files in Python? > > > Have you tried shutil? > > // m > - > > From marklists at mceahern.com Tue Sep 17 12:52:38 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 17 Sep 2002 11:52:38 -0500 Subject: handling exceptions In-Reply-To: Message-ID: > The problem is: how can I access the message string of the exception? try: raise RuntimeError("Gee, I wonder what this is?", "Oh, and how about this too?") except RuntimeError, e: print e // m - From donn at u.washington.edu Fri Sep 6 12:19:52 2002 From: donn at u.washington.edu (Donn Cave) Date: 6 Sep 2002 16:19:52 GMT Subject: Timothy Rue References: <898662b7d85d2c966c0bd45d563d5d2d@xganon.com> Message-ID: Quoth xganon : | Does Timothy Rue still Troll here? | If not, how did you get rid of him? | We need him out of our group now, | maybe we could get him into a Perl | group for a while and let them deal | with him? If the problem is only that he posts to your group, then your group is way ahead of comp.lang.python. When he was here, a number of regulars utterly lost touch with whatever common sense they may ordinarily possess, and it went on for what seemed like months. If you don't want to engage in his discussion, then don't. I think you'll find that it works as well as anything. Donn Cave, donn at u.washington.edu From donal.k.fellows at man.ac.uk Fri Sep 6 06:38:12 2002 From: donal.k.fellows at man.ac.uk (Donal K. Fellows) Date: Fri, 06 Sep 2002 11:38:12 +0100 Subject: Could Python supplant Java? References: <8d3f4438.0208202348.578ff9c8@posting.google.com> Message-ID: <3D788594.79DE84C6@man.ac.uk> Victor Wagner wrote: > Dan Johnson wrote: [I think this attribution is correct] >> What is so developer-hostile about Windows? > > "Friendly" interface. To be a "friendly" is to consider oneself equal > with his friends. If you want your friend to do something for you, > you ASK him, not ORDER him. [...] "Friendly" interfaces are interfaces that let users do things in the order they want to, and they drive everything from the users' viewpoint. Leaving that critical field blank because the person who knows the information is off on vacation? That's a friendly thing to do. Explaining that you can't save the information because some fool that shares the computer with you has decided to share MPEGs from the machine? That's a friendly thing to do. Both are hard to program. Let's face it, even with the help of a top-notch GUI toolkit, writing a good GUI is hard. And playing well in the Windows world demands a GUI (by culture, even if for no better reason.) That's why developing for Windows is hard. (A vast, baroque API with only mediocre documentation doesn't help, but that's not a problem limited to Windows.) Give me a nice clean protocol (where any deviation allows me to say "go away, I don't want to talk to you") any day. So much easier to implement! Donal. -- Donal K. Fellows http://www.cs.man.ac.uk/~fellowsd/ donal.fellows at man.ac.uk -- Of course, she was referring not to the current but to a past chair, unless Babbage is very, very old, *and* tied to a chair in Hawking's basement. Which, admittedly, would be pretty cool. -- Chris Hammock From aleax at aleax.it Thu Sep 19 11:40:08 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 15:40:08 GMT Subject: strong/weak - dynamic/static [Was: Getting started] References: <87ofaut2xt.fsf@pokey.henrik-motakef.de> Message-ID: Henrik Motakef wrote: ... >> Python 2.2.1 (#1, Jun 25 2002, 10:55:46) ... > There's a difference between a type and a class, I guess... In the release of Python you use, the default metaclass for your classes is still such as to force a difference, yes. Just use one of the many ways to make your classes new-style (e.g., a global variable __metaclass__=type will do) if you are bothered by this distinction (gradually going away, but with care for backwards compatibility, of course). Alex From tjreedy at udel.edu Fri Sep 27 08:48:55 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Sep 2002 12:48:55 GMT Subject: a python puzzle References: Message-ID: "David Brown" wrote in message news:an1i31$1r3$1 at news.netpower.no... > I'm not too interested in the crypogram puzzle, but your solution here has > just given me a solution to something that has been bugging me for some > time - finding an easy way to convert a list of characters into a string: > > >>> a = "Hello" > >>> b = [x for x in a] or >>> list(a) ['H', 'e', 'l', 'l', 'o'] which is probably faster > >>> "".join(b) > 'Hello' From jknapka at earthlink.net Sat Sep 7 01:53:55 2002 From: jknapka at earthlink.net (Joseph A. Knapka) Date: Sat, 07 Sep 2002 05:53:55 GMT Subject: Python class ( Prolog ) ??? References: <20020905234600.11264.60328.Mailman@mail.python.org> <3D7914FD.5D713A48@anansispaceworks.com> Message-ID: <3D799469.EB2E47DC@earthlink.net> Terry Hancock wrote: > > Well, I haven't seen any posts go by on the python-logic > SIG, so I thought I'd carry over this topic from the > python list as a conversation starter: > > While we're on the subject -- I've taken a couple of > tries at Prolog in the past, but didn't really get > anywhere with it. I understand the concept of > expressing logic in code, but got rather bogged down > when it came to any practical examples. When done properly, Prolog is beautiful, easy to understand, easy to maintain. It is not well-applicable to a wide range of problems, as is Python; largely because procedural algorithms, which are the meat-and-potatoes of mainstream IT, are rather painful to express in Prolog. But if you happen to have a problem whose structure is easily expressed in first-order predicate logic, you can often simply write down that problem description in your editor and run it as Prolog code. Many problems to which we typically apply procedural algorithms are easily expressed in FOPL; we don't do it simply because efficient procedural algorithms have been around for far longer than practical declarative-logic languages. > Python, with it's object/procedural focus seems like > it would complement Prolog well (or vice-versa). Can > anyone fluent in both compare what sort of applications > you might apply a prolog-python solution to? Where > would you draw the line between the two? What would > using prolog help me with? What's a good problem to > solve as a learning project? I would apply Prolog to a problem that is naturally expressed as a search of a solution space for solutions that satisfy some set of constraints. Of course, any problem -can- be expressed in such fashion; the question is, is it a -natural- description. For trivial examples of the kind of problem I mean, see any book of logic puzzles of the "The man who wears blue lives in the house closest to the river; the man with the parrot lives next to the man who wears green" variety. In this sort of problem, it's not obvious how I would efficiently find an arrangement of houses and owners that satisfies all the given constraints, short of exhaustive generate-and-test; but I can easily write Prolog rules expressing the constraints themselves, and let the interpreter perform the search for me. If I express the constraints properly, the result will be as fast as anything I could code up by hand in Python or perhaps even C. Prolog is (IMO) not particularly suitable for applications that involve lots of user interaction (though this may be because the Prolog UI toolsets I've used have generally been thin wrappers around underlying procedural toolkits - declarative UI design could be quite powerful, as in XUL, etc). The UI is probably best expressed using something like Python. It's also not a good choice for a problem that is mainly a long grindy numeric computation - there are better languages to express such things. When well-known, fast procedural algorithms are applicable, apply them. Prolog is good when you know a lot about the syntax of the solution space, so to speak, but not a great deal about its semantics -- "I ain't never seen one before, but I'll know it when I see it!" Incidentally, there's a Prolog interpreter buried within the WinNT kernel; it handles configuration of network devices at boot time (among possibly other things). > Any more book or website > recommendations for a learner? > > Conversely is there anyone who thinks Prolog is > a waste of time for a Python programmer, or that > it would be better to use something else in such > a role? I think that any programmer would benefit from learning Prolog well (and Lisp, and Haskell, and assembler, and C). It will probably be quite a drastic change if all you know is OO and structured programming, and when you "get it" you will know things about programming that you didn't before. (Disclaimer: Prolog was the second language I learned really well, after BASIC :-) so my experience with it is not typical. When I learned C later on, *that* made my brain hurt.) Cheers, -- Joe "I'd rather chew my leg off than maintain Java code, which sucks, 'cause I have a lot of Java code to maintain and the leg surgery is starting to get expensive." - Me From 53ab2750 at meowing.net Sat Sep 7 11:42:36 2002 From: 53ab2750 at meowing.net (itsy bitsy meowbot) Date: Sat, 07 Sep 2002 15:42:36 GMT Subject: None or 0 References: Message-ID: Michael Str?der wrote: > >>> repr(0 or None) > 'None' > >>> repr(None or 0) > '0' > >>> repr('' or None) > 'None' > >>> repr(None or '') > "''" > >>> > > Is it guaranteed to work like this or should that be avoided? That's what the language reference specifies, in Doc/ref/lambda.html -- but each of the 73 Python license layers disclaims responsibiilty for anything, so Pythonlabs are still free to change it if they're feeling particularly mean and nasty, so don't tick them off. From whisper at oz.net Tue Sep 17 22:08:12 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 17 Sep 2002 19:08:12 -0700 Subject: Python GUI app to impress the boss? In-Reply-To: Message-ID: > Is there any way to get the Python world to allow for the processing of > monetary applications without some hokey 60's constructs that involve > in-line conversions or anticipations of calculation characteristics? > > Regards, > > terry What prevents the creation of a decimal money type? I agree, it would be nice if python could do something akin to calculator aritmetic with types like scientific (covered) engineering (improper scientific with the exponent as a power of 3 and the (oops, forgot the term - mantissa?) more then a single digit as in 12.2e3), fixed precision (1..n to the right of the decimal). The forthcoming fractions are going to be interesting... (chinese interpretation). Be nice too if math could do rads, grads and decimal degrees. Just my $0.02 worth. Dave LeBlanc Seattle, WA USA From duncan-news at grisby.org Wed Sep 11 05:16:24 2002 From: duncan-news at grisby.org (Duncan Grisby) Date: Wed, 11 Sep 2002 09:16:24 GMT Subject: Returning lists from python COM servers References: <3d7731f5$1@pull.gecm.com> <3d7738f5$1@pull.gecm.com> <3d7c87ff@pull.gecm.com> Message-ID: In article <3d7c87ff at pull.gecm.com>, Olly Smith wrote: >I'll remember to only chuck lists across the COM boundary. Just out of >interest, are there any other distributed object architectures that are >better supported by Python? (corba, soap, ......) CORBA is very well supported by Python. Check out omniORBpy or Fnorb: http://omniorb.sourceforge.net/ http://www.fnorb.org/ I wrote omniORBpy, so that is the best one, of course :-) SOAP is a bit of a mess (not just in Python -- everywhere) since the specification has been changing too much, and nobody seems to agree on its interpretation. It's also not strictly speaking a distributed object architecture, since it doesn't have objects in the same way COM and CORBA do. Finally, you might want to consider Dopy and Pyro, which are Python specific remote object systems. Personally I don't like being locked into a single language (even if it's a language as nice as Python), but they might work for you. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From tjreedy at udel.edu Mon Sep 23 21:04:46 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Sep 2002 01:04:46 GMT Subject: list problem References: Message-ID: wrote in message news:mailman.1032818129.8126.python-list at python.org... > i have: > x=[['0020', '0000x9'], ['0030', '0000xa'], ['00B4', '0000x8'], ['0030', '0000xb'], ['00F0'], ['0001'], ['0003'], ['0005']] > > and i want: > y=['0020', '0000x9', '0030', '0000xa', '00B4', '0000x8', '0030', '0000xb','00F0', '0001', > '0003', '0005'] > > how to do this? >>> [b for a in x for b in a] ['0020', '0000x9', '0030', '0000xa', '00B4', '0000x8', '0030', '0000xb', '00F0', '0001', '0003', '0005'] For deeper flattening, try google: Python list flatten Terry J. Reedy From wlfraed at ix.netcom.com Tue Sep 3 03:40:08 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 03 Sep 2002 00:40:08 -0700 Subject: syntax error in Pyton shell References: Message-ID: lion fed this fish to the penguins on Tuesday 03 September 2002 12:04 am: > I'm learning exception handling, I type these code in Python shell: > >>>> try: f=open("nofile") > ... except IOError: pass > ... print "The exception is just passed!" > File "", line 3 > print "The exception is just passed!" > ^ > SyntaxError: invalid syntax > > But these code run without any error as a program(or script). Could > anyone tell me why? Off hand... Your indentation is invalid... You need to return to the >>> level for the print -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From mgerrans at mindspring.com Thu Sep 26 01:52:17 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Wed, 25 Sep 2002 22:52:17 -0700 Subject: "which" command? References: Message-ID: "Brian Quinlan" wrote in message news:mailman.1032998974.31888.python-list at python.org... > The actual software is available here: > http://starship.python.net/~tmick/ This one is nice, especially on the Windows platform where it looks at both the path and pathext. I wrote my own which.py a while ago to support these, but that was before I heard of this one (i.e. just now). I also made mine find all occurrances of matching programs in the path, not just the first one. From skip at pobox.com Sun Sep 8 16:27:56 2002 From: skip at pobox.com (Skip Montanaro) Date: Sun, 8 Sep 2002 15:27:56 -0500 Subject: transform a list of lists in a lit of strtings??? In-Reply-To: References: Message-ID: <15739.45772.400520.334648@12-248-11-90.client.attbi.com> James> labels2 = [i for item in labels1 for i in item] James> (I find this oddly hard to read.) I rarely use list comprehensions for anything complex, but for this sort of thing I tend indent it: labels2 = [i for item in labels1 for i in item] Which is to say, if it gets too complex, I more-or-less just fall back to the statement form: label2 = [] for item in labels1: for i in item: labels2.append(i) :-) -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From phncontact.libero.it at Tue Sep 3 11:49:44 2002 From: phncontact.libero.it at (Ben Jamin) Date: Tue, 03 Sep 2002 15:49:44 GMT Subject: Servizi Internet References: Message-ID: <3bl9nu8924gihfj2nlpog874vfm73qqbh9@4ax.com> excuse me but aren't commercial promotion and such things forbidden on newsgoups? From max at alcyone.com Thu Sep 5 03:01:42 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 05 Sep 2002 00:01:42 -0700 Subject: Graham's spam filter References: <3D647B4B.28D9BF04@alcyone.com> <3D655AE6.A097AA25@alcyone.com> Message-ID: <3D770156.2E55864C@alcyone.com> Aaron Swartz wrote: > I've been using bogofilter[1], Eric Raymond's Graham-derived spam > filter which threw away base64-encoded data and 90% of all spam that > got past the filter was base64-encoded. Therefore, I think that base64 > content really needs to be decoded. I wrote a base64-decoding filter > in Python for it and the problem has gone away. Indeed. I've been finding very much the same thing with my rule-based filter; about 90% of the spam that's getting through is base64 encoded. I haven't yet taken the next step of automatically decoding the base64 text parts (and then just processing that), but as you have discovered it is an obvious solution to the obvious problem. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From sludtke at bcm.tmc.edu Mon Sep 30 15:41:23 2002 From: sludtke at bcm.tmc.edu (Steve Ludtke) Date: Mon, 30 Sep 2002 14:41:23 -0500 Subject: XMLRPC calls don't work in threads, or rather, they don't play well with others ! (help) References: <3D97D190.9030003@bcm.tmc.edu> Message-ID: <3D98A8E3.7020006@bcm.tmc.edu> Ok. Sorry to waste everyone's time. This seems to be a machine-specific problem. I put together a test case to demonstrate it, and it worked (on a different machine). On the original machine (running and identical OS/python version) the problem still persists, so I'll have to figure out what's wrong with that specific machine. Very odd. Thanks everyone. From bdesth at nospam.free.fr Sun Sep 8 23:11:48 2002 From: bdesth at nospam.free.fr (laotseu) Date: Sun, 08 Sep 2002 23:11:48 -0400 Subject: Why Python? References: <4f49d232.0209050418.7668c21@posting.google.com> <3D77FB95.3070300@nospam.free.fr> Message-ID: <3D7C1174.5060905@nospam.free.fr> Roy Smith wrote: > I wrote: > >>>If you're learning languages to study computer >>>science, lisp is looking a lot better. >> > > laotseu wrote: > >>I think once you know them both, you know *how* to program, whatever >>the language you have to use. > > > I believe we actually both said the same thing, just worded > differently :-) Sorry, my misunderstanding... laotseu From sismex01 at hebmex.com Thu Sep 12 18:31:57 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 12 Sep 2002 17:31:57 -0500 Subject: [ANN] PySQLite 0.3.0 released Message-ID: Oops, you are SO right. :-) -gus -- > > >> for row in cursor: > >> print "%14s, %15s, %19s, %8s, %25s" % tuple(row) > >> ? > >> > >> Terry J. Reedy > >> > > > You can already do it, using iter(): > > > for row in iter(cursor, None): > > print .... > > you mean: > > for row in iter(cursor.fetchone, None): > print ... > > > > -- > ?????? > > In a world without walls and fences, > do we care about Windows and Gates ? > > -- > http://mail.python.org/mailman/listinfo/python-list > Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compania. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electronico enviado para o desde esta direccion sera procesado por el sistema de correo corporativo de HEB. Tal correo electronico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el proposito de monitorear que se cumplan las normas de seguridad de la empresa. From erict at millfilm.co.uk Tue Sep 3 10:47:07 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Tue, 03 Sep 2002 15:47:07 +0100 Subject: xml question Message-ID: <3D74CB6B.7697013E@millfilm.co.uk> I am trying to compare 2 node from 2 different xml dom. On it just read from disk and the other one has been generated from memory: I am finding myself having to compare the same thing in 2 differents state: >From Disk: (unicode) N1 [(None, u'fileName'), (None, u'OutputType'), (None, u'name'), (None, u'UId'), (None, u'version'), (None, u'node')] >From Memory: N2 ['node', 'version', 'UId', 'fileName', 'OutputType', 'name'] What will be the simplest thing to do in this case? Thanks, Eric From gerhard.haering at gmx.de Sun Sep 1 17:44:38 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 1 Sep 2002 23:44:38 +0200 Subject: Add methods to a class at runtime? In-Reply-To: References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: <20020901214438.GA4349@lilith.ghaering.test> * Robert Oschler [2002-09-01 17:19 -0400]: > Ok bear with me guys (Gerhard and Peter). I'm not lazy, the reason I > don't test certain things I should is because Python is capable of > such amazing introspective dynamism that, having a _very_ long > experience bank in strongly typed "static" languages like C++ and > Pascal, I find I don't even consider yet even trying certain > possibilies that Python is capable of. > Some interesting tidbits I found while trying out your suggestions, as > you will see in the two ".py" files that follow, I discovered that to > create a method you can dynamically add to a class _instance_, you > need to omit the 'self' parameter in the method declaration. Yep, I found that out today too, when I wrote my last reply. Though I've never used that in real life. > [...] I'm running 2.1.1, anybody know if 2.2.2 is going "disable" > either of these abilities? It will be strictly (even binary) compatible with Python 2.2.{0|1}, so the answer is that these features will stay. > (class or class instance dynamic method addition). I saw a note about > such activities requiring a "dynamic" keyword, which is fine. I never saw such a note. Maybe you were reading a message from the (dormant) types-sig, where ways to introduce optional (!) stronger typing into Python are discussed. I never saw Guido make any comments about removing dynamic features from Python, though. With /one/ exception, which you didn't mention, yet: assigning to the __class__ attribute: >>> class Foo: ... def action(self): print "foo" ... >>> class Bar: ... def action(self): print "bar" ... >>> foo = Foo() >>> foo.__class__ >>> foo.action() foo >>> foo.__class__ = Bar >>> foo.action() bar >>> foo.__class__ >>> AFAIK Guido isn't too fond of this feature. I guess it might go away some day. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From jfaris at sbcglobal.net Mon Sep 9 19:08:50 2002 From: jfaris at sbcglobal.net (Jordan Faris) Date: Mon, 9 Sep 2002 16:08:50 -0700 Subject: Diving into the Python pool.... Message-ID: <005c01c25855$dc5752d0$e680cf3f@leader1> Hi...after strolling through these threads for some while now, and comparing the generally benign tone here with the rather elitist edge of other programming communities, I think I'd like to get my feet firmly onto Terra Pythonia. I'm a little reluctant to plow in headfirst, however, mainly because I had my heart set on becoming a Java programmer, but I think I need to be more realistic about programming fundamentals, since I am doing this completely self-study. Python is, if I understand correctly, an object-oriented language with a much simpler syntax than Java, yet compatible in applicability, especially web-related, is this correct? My primary focus is to create streamlined, rapid-deployment web applications (PHP and JSP portal sites, etc), but from what I've seen, Python can be used or adapted to achieve comparable results; am I on the right track, or should I continue to nurture the Java bean? Any frank, level-headed input would be much appreciated. Thanks...... Jordan -------------- next part -------------- An HTML attachment was scrubbed... URL: From dwelch91 at nospam.attbi.com Sat Sep 21 13:08:17 2002 From: dwelch91 at nospam.attbi.com (djw) Date: Sat, 21 Sep 2002 17:08:17 GMT Subject: PyQt setup on Linux Mandrake 8.2 References: <3D8B4898.20808@nospam.attbi.com> <3d8c9b92$0$182$9b622d9e@news.freenet.de> Message-ID: <3D8CA781.3010000@nospam.attbi.com> > Unfortunately, Mandrake is somewhat more perl than python biased. > Do you mean there is more support/newer versions of Perl or is it more of a philosophical thing: There are many ways vs. there is one way? > If you know a bit about RPM, perhaps you, dwelch, can manage > to update these packages (rpm -Uhv xx.src.rpm, a few changes ..., > rpm -ba SPECS/sip.spec). > Otherwise you could contact me. In about a week I've got time > to do this. Uhhh... considering my extreme novice status on Linux and especially RPMs (as witnessed by my problems), I don't think I am the right person for this task. > The RPM stuff (or DEB) has got real advantages compared to > "setup.exe". > And if the offered versions are outdated, fetch the > new source, learn from the (e.g.) sip.spec file somewhat about > the compilation, and make a new package! > Well, here I have to disagree (at least from a user's perspective). Having come from over 10yrs of Windows development experience (including writing Windows installers from scratch), I find RPM package management (can't say about DEB format, never used it) to be very complex, difficult, and it rarely works for me. Case in point is two systems I tried to install at work... one Mandrake 8.x and one Windows 2000. The packages I was installing were Python 2.2.1 with a bunch of extensions like MySQLdb and mxDateTime, MySQL 4.0, Jabber x.xx (can't remember version) and an FTP daemon. The Windows box was up and running in less than an hour after running a handful of setup.exe-type programs, and the Linux box still wasn't fully installed after two days of trying. I completely gave up trying to upgrade a copy of MySQL 3.23 to 4.0 after every way I tried failed. In the end, the system became corrupted that I had to re-install Linux (probably a real Linux person would laugh at this, but after a while /usr/bin got so filled with junk that I didn't know what I had anymore and wanted to start over "clean"). Not to say that this sort of thing doesn't happen in Windows-land, but setup.exe works on 99% of the packages I have tried 99% of the time. Don't get me wrong, I really like Linux, but this is one area where I believe that Linux still has a ways to go to "catch up" in the ease-of-use department. Don From wlfraed at ix.netcom.com Fri Sep 20 18:18:47 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 20 Sep 2002 15:18:47 -0700 Subject: Python Compiling References: Message-ID: <8s6gma.ti3.ln@ix.netcom.com> Terje Johan Abrahamsen fed this fish to the penguins on Friday 20 September 2002 01:12 pm: > But, I guess my question boils down to, why is not Python a compiled > language? > Firstly, Python started life as a scripting language -- like REXX, DCL, PERL... As such, it was meant to avoid such intervening confusions as compile/link phases. Besides, there is a virtual machine intermediate -- modules that are mentioned in an "import" statement are compiled to the VM byte-codes (creating a .pyc file) so subsequent invocations save time. > Is it not possible to write a complete compiler like the C compiler > for Python? Or is it just that nobody has done it? Or must the > language be constructed differently? > Do you know of a C compiler that builds executables that can read a C expression as input and compile/execute that expression? Most scripting languages can do that, as the interpreter is already present. -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From christophe.delord at free.fr Tue Sep 3 16:09:44 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Tue, 3 Sep 2002 22:09:44 +0200 Subject: efficient list merging References: Message-ID: <20020903220944.475d7222.christophe.delord@free.fr> On Tue, 03 Sep 2002 15:19:44 -0400 pinard at iro.umontreal.ca (Fran?ois Pinard) wrote: > [Peter Saffrey] > > > I have two lists of lists of strings which I would like to merge > > efficiently without repeats. [...] Or is there a better way? > > I am not sure about the relative speed of everything, but I would be > tempted to try: > > dict(zip(list1 + list2, [None] * (len(list1) + len(list2)))).keys() This may be written using list comprehension: >>> list1 = list('abcdebxyz') >>> list2 = list('pqqr') >>> dict([(k,1) for k in list1+list2]).keys() ['a', 'c', 'b', 'e', 'd', 'q', 'p', 'r', 'y', 'x', 'z'] -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From roy at panix.com Mon Sep 30 07:32:59 2002 From: roy at panix.com (Roy Smith) Date: Mon, 30 Sep 2002 07:32:59 -0400 Subject: is cPickle really this slow? References: Message-ID: Dag wrote: > So I pickle my dictionary, which ends up > being a 3.2MB file and try to run my script again, this time getting > the pickled dictonary instead of building it at runtime. This time > however the script takes over 35 seconds to run, close to three times > as long. Did you use the optional third argument which tells pickle to write the file out in binary? My experience is that the difference in performance between reading binary and ascii pickles will be substantial. From marklists at mceahern.com Tue Sep 10 08:27:56 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 10 Sep 2002 07:27:56 -0500 Subject: dynamism In-Reply-To: Message-ID: [Duncan Booth] > New style classes (which are those with 'object' or other builtin classes > as a base class) do not all allow you to add arbitrary attributes: Au contraire: $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> class foo(object):pass ... >>> f = foo() >>> f.x = 1 >>> f.x 1 >>> Cheers, // m - From senux at senux.com Wed Sep 18 04:16:32 2002 From: senux at senux.com (Brian Lee) Date: Wed, 18 Sep 2002 17:16:32 +0900 Subject: python does not start Message-ID: <20020918081632.GA4156@mercury.senux.com> $ ./python ld.so.1: ./python: fatal: libdb-3.2.so: open failed: No such file or directory Killed On SunOS 5.7, python which is compiled on other sun machine does not start. How can I fix this? -- Brian Lee From gerhard.haering at gmx.de Tue Sep 24 13:46:30 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Tue, 24 Sep 2002 19:46:30 +0200 Subject: Python and cgi and problem! In-Reply-To: References: Message-ID: <20020924174629.GA787@lilith.ghaering.test> * CheapSkate [2002-09-24 17:40 +1000]: > thanks dudes, > everything works fine, > im just doing some simple things, nothing that will break the code. I'd recommend to use urllib.quote() anyway. It's better to do the right thing in the first place, as software often lives longer and in stranger places than you'd have expected it to. -- Gerhard From thorsten at thorstenkampe.de Tue Sep 17 14:01:40 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 17 Sep 2002 20:01:40 +0200 Subject: IDLE References: <3D7D4F84.318CDB0F@bellatlantic.net> Message-ID: * Cliff Wells > On Mon, 2002-09-16 at 10:43, Thorsten Kampe wrote: >> "Hardware: 386 enhanced, 75MHz, 32MB RAM." > > This can't be correct. [...] > > The actual CPU is either an AMD/Cyrix 486 clone or an early Pentium. You know hardware better than me, for sure. But even with a 486/586 running with 75 MHz he surely will have problems installing and running Python 2.2.1: the python shell for example is about 4 MB running idle, Pythonwin is about 9 MB. Thorsten From b.maryniuk at forbis.lt Mon Sep 2 04:08:00 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 2 Sep 2002 10:08:00 +0200 Subject: Python GUI In-Reply-To: References: <3d8d3c0.0208262339.e7bc02c@posting.google.com> Message-ID: <200209021008.00596.b.maryniuk@forbis.lt> On Monday 02 September 2002 09:16, Andy Salnikov wrote: > Problem with X11 is that there is no "OS style manager" (whatever > this could mean) for X11, or there is no _single_ style manager. No. Problem with the license. Use wxWindows instead. -- Regards, Bogdan main(k){float i,j,r,x,y=-16;while(puts(""),y++<15)for(x =0;x++<84;putchar(" .:-;!/>)|&IH%*#"[k&15]))for(i=k=r=0; j=r*r-i*i-2+x/25,i=2*r*i+y/10,j*j+i*i<11&&k++<111;r=j);} /* Mandelbrot in ASCII. */ From teaandbikkie at aol.com Wed Sep 11 21:01:59 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 12 Sep 2002 01:01:59 GMT Subject: file upload using msvcrt References: <20020911204906.00669.00000156@mb-fh.aol.com> Message-ID: <20020911210159.00669.00000162@mb-fh.aol.com> >data = fileinfo.file.read( ) >if not data: break I just thought of another possible problem here, read() is supposed to read in the entire file, and maybe 8k is all data can take :) So you could change it to read(1024) for 1k chunks. Also, maybe read() recognises an EOF character in the word doc? Hopefully being binary read this should not happen... Kind regards, From pedronis at bluewin.ch Wed Sep 4 12:31:40 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Wed, 4 Sep 2002 18:31:40 +0200 Subject: jython memory usage References: Message-ID: <3d76366a$1_5@news.bluewin.ch> From: Robin Becker > A colleague has been running tests of reportlab under jython-2.1 several > of the tests use prodigious amounts of memory (one even failed). We're > using win2k+j2sdk1.4.0_01 as the jython engine. > > Anyone know what sorts of things cause x10 memory usage? I find one > particular test needs more that 1Gb and then falls over for lack of > memory. That means you are running jyhton through: java -mx1024m -cp ...jython.jar org.python.util.jython ... and it uses all that memory and would need more? regards. From dwelch91 at nospam.attbi.com Fri Sep 20 01:46:31 2002 From: dwelch91 at nospam.attbi.com (dwelch) Date: Fri, 20 Sep 2002 05:46:31 GMT Subject: newbie seeks advise. References: <77c84db2.0209192137.51167ebb@posting.google.com> Message-ID: <3D89F605.4030303@nospam.attbi.com> akirasugiura wrote: > Hi, > > I've been learning python for about a month. I had no prior knowledge > of programming. > > My question is, I have a tuple which is, data = (69, 40, 74, 41, 56, > 57, 38, 58, 26, 55). How I can make a function that picks up a largest > number > from this "data" tuple. If "data" was a 'List' I would be able to > use "sort" but since sort doesn't work with tuple. I am stuck here. > > Thanks in advance > > Sincerely, > Simple way, probably not optimal: >>> max_element = max(list(data)) >>> max_element 74 From bokr at oz.net Mon Sep 9 21:10:08 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Sep 2002 01:10:08 GMT Subject: Windows/DOS: double clicking a .py file References: Message-ID: On Mon, 9 Sep 2002 16:17:08 -0700, "David LeBlanc" wrote: >cmd.exe will accept a flag telling it to stay open after something is run. >You can create a shortcut along the lines of: > >cmd /K python myscript.py You may want to specify full paths, depending on where things are etc. You can also do _several_ things in the cmd /k line by using "&". E.g., the following %SystemRoot%\system32\cmd.exe /x /k prompt [$T$H$H$H$H$H$H] $P$G & title MyPy & D:\Python22\python.exe will - start a new cmd window - set the prompt for it so it will show current time and directory, e.g., [17:19] C:\pywk> - set the title of the window to MyPy - start interactive python the shortcut also lets you set the working directory. If you have a place you like to test code, note that by setting the working directory there, everything will be visible to import, aside from any other startup initialization. Thus you can separate things by people or project or whatever. When you exit Python, you'll be at a cmd prompt as specified, and in the working directory specified. Handy. Don't forget that you can also change the icon associated with whatever you run via the shortcut. I use the swiss army knife for many of my various "DOS" console shorcuts. > >You could also add this to the cmd shortcut itself if you have one, but that >generally turns out to be a major pain since all dos-window based apps will >then leave their windows open. You mean the file extension association for .bat and .cmd? Yes, that doesn't work out as a good general thing. > >A nice aspect of using a custom cmd shortcut is that you can set colors and >fonts and window size just for this app which might help distinguish it if >you have a lot of dos windows open. You can set the screen buffer height to >a high number so you can scroll really far back (not a good idea to make the >screen buffer width greater then the window width though). > A nice thing is that you can change things just for your current session, using the properties selection from the system (left click title bar icon for it) menu. >you can type 'help cmd' in a dos window for more info on cmd switches. > >HTH, > >David LeBlanc >Seattle, WA USA > >> -----Original Message----- [...] ;-) Regards, Bengt Richter From phr-n2002b at NOSPAMnightsong.com Sat Sep 14 02:20:47 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 13 Sep 2002 23:20:47 -0700 Subject: EDI parsing References: <746127ef.0209110128.53665a23@posting.google.com> Message-ID: <7xd6rh6qio.fsf@ruckus.brouhaha.com> "Emile van Sebille" writes: > > 2) Is there a (python) EDI to XML converter? > > That wouldn't be hard. If there's already a DTD for edi, that would > help a lot. ;-) EDI syntax doesn't fit into the SGML model, so I don't think it could be done with an DTD-driven parser. Parsing and converting EDI is easy. > > [You have to know that I've never written a parser in Python before. > > The last (big) parser I wrote was in C with a few years back the help > > of lex and yacc if memory serves me right.] > > > > What is the best approach to writing an EDI parser in Python? The main thing is to understand that it's not complicated. I worked on an EDI product years ago, and we hired several programmers with CS backgrounds who immediately wanted to use stuff like lex and yacc on it. Really, EDI was designed to be processed by RPG and COBOL programs and just doesn't have much syntactic hair. If you find yourself reaching for fancy compiler implementation techniques, you're probably misunderstanding something. Basically, an EDI document is a sequence of lines called "segments" where the segments are sequences of "elements". The spec describes various document types (purchase order, invoice, etc.) and the types of segments you expect to find in each one. For each segment, the spec describes which elements you expect to find in each one. You break a segment down into elements with a simple lexical scanner (re.split should be more than powerful enough) and then have a dictionary indexed by segment type of what elements should be in it. Within documents, there are some simple looping constructs, that are no big deal. If you want to write a general EDI parser that understands all the documets and segments in the spec, 99% of the work is typing in all the rules from the spec. The code that follows them should be very simple. In reality, nobody uses all the docs or segments. They pick a few docs and use some subset of the allowable segments in specific ways. So if you're trying to implement EDI because you have some customer who wants to order widgets from you by EDI, you don't need a fully general system. Just ask them for the spec of the docs they want to use, and code those. What brought on this question? I seem to remember this subject came up before, maybe on sci.crypt. I don't think there's any free general EDI software around because the big specication documents (X12, Edifact) aren't free. But the code framework is pretty straightforward to write. I did it in C in a few weeks, and in Python it would be a lot simpler. From jepler at unpythonic.net Sun Sep 1 17:30:52 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sun, 1 Sep 2002 16:30:52 -0500 Subject: EOFError using cPickle.load In-Reply-To: <6avc9.264595$me6.34329@sccrnsc01> References: <6avc9.264595$me6.34329@sccrnsc01> Message-ID: <20020901163044.A1401@unpythonic.net> either do not use Windows, or make sure you open with 'rb' and 'wb'. Jeff From marklists at mceahern.com Thu Sep 12 19:17:31 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 12 Sep 2002 18:17:31 -0500 Subject: Restricting methods in derived classes In-Reply-To: Message-ID: [Huaiyu Zhu] > I was hoping for a way to confirm wanted methods, because there are more > methods that I don't want. But the above is good enough for preventing > obvious mistakes. Thank you. Have you considered a metaclass solution? Here's a half-baked attempt that doesn't work and merely serves to demonstrate how weak my grasp of Python is. If Alex Martelli is in the house, perhaps he can shed some light. :D Here's some classic Martelli speak on metaclasses for ya: http://groups.google.com/groups?selm=mailman.1025801286.31332.python-list%40 python.org Meanwhile, my lame attempt... #!/usr/bin/env python import inspect def make_unwanted(cls, method_name): def unwanted(self, *args, **kwargs): raise AttributeError(cls.__name__, method_name) return unwanted class Restricted(type): def __init__(cls, name, bases, dict): for base in bases: for method in inspect.getmembers(base, inspect.ismethoddescriptor): if not method[0].startswith('__') and method[1] not in dict['wanted_methods']: dict[method[0]] = make_unwanted(cls, method[0]) super(Restricted, cls).__init__(name, bases, dict) class RestrictedDict(dict): __metaclass__ = Restricted wanted_methods = [dict.update] d = RestrictedDict() d['a'] = 1 # I expect the following to blow up, but alas, they don't... for key in d.keys(): print key d.update({'a': 2}) print d.items() # Will this give me any clue? print dir(d) # Time to go listen to some good music... // m From igetenoughspamalreadythanksjlr at doctor.com Tue Sep 3 11:33:33 2002 From: igetenoughspamalreadythanksjlr at doctor.com (John La Rooy) Date: Wed, 04 Sep 2002 01:33:33 +1000 Subject: efficient list merging References: <20020903220944.475d7222.christophe.delord@free.fr> Message-ID: <1031110376.483649@ampungk.ozonline.com.au> Fran?ois Pinard wrote: > Taking advantage of other clever suggestions, I would guess that: > > both = list1 + list2 > result = dict(zip(both, both)).keys() > > would not be so bad, speed-wise. > result=dict(zip(list1,list1)) result.update(dict(zip(list2,list2))) John From steven_shaw at adc.com Wed Sep 11 20:33:36 2002 From: steven_shaw at adc.com (Steven Shaw) Date: 11 Sep 2002 17:33:36 -0700 Subject: dynamism References: <66715c02.0209091923.265fe77e@posting.google.com> <3d7e209a_1@news.iprimus.com.au> Message-ID: <66715c02.0209111633.771aa9d3@posting.google.com> Duncan Booth wrote in message news:... > Duncan Booth wrote in > news:Xns92865CE1C916Aduncanrcpcouk at 127.0.0.1: > > The code below gives these timings on my machine: > > 3.84s: 1000000 x New() > > 3.89s: 1000000 x New2() > > 2.39s: 1000000 x Old() > > 5.19s: 10000 x attributes() > > 5.81s: 10000 x attributes() > > 4.17s: 10000 x attributes(__main__.Old) > > Sorry about the bad form of following up to my own post, but I thought I > had better add that the above timings are on Python 2.2.1 and I forgot to > specify -O. > > The optimised times for 2.2.1 are: > 3.77s: 1000000 x New() > 3.81s: 1000000 x New2() > 2.33s: 1000000 x Old() > 4.94s: 10000 x attributes() > 5.56s: 10000 x attributes() > 3.92s: 10000 x attributes(__main__.Old) > > Using the latest CVS build I get rather different timings: > > 0.94s: 1000000 x New() > 1.05s: 1000000 x New2() > 1.39s: 1000000 x Old() > 3.52s: 10000 x attributes() > 4.36s: 10000 x attributes() > 3.05s: 10000 x attributes(__main__.Old) > > So it appears that creating object-derived classes is now faster than > creating old-style classes, although both tests are much faster than in > 2.2. Setting attributes is still somewhat slower. Oh, and the -O flag on > the CVS build has no measurable effect. Hi Duncan, Thanks alot for your time on this. I hadn't read about the __slots__ mechanism before. I feel that there must be something wrong, though, because the Old object layout is winning! Maybe the implementation is finding the index of the variable in the __slots__ array and then using returning __values__[index] in order to implement the attribute access. I made up the "__values__" array - there must be a values array somewhere. Array-based object layout amounts to the same thing as record-based-layout in Python because all primitives are the same size (right?). There needs to be a way for Python to remember the indexes... Hmmm. I think your test code doesn't allow the compiler to remember the indexes since it creates an instance anonymously (using klass). I tried the code I "attached" at the end of the post: $ python f.py 2.2.1 (#4, Aug 21 2002, 14:22:21) [GCC 3.2] 0.14s: 10000 x New() 0.12s: 10000 x New2() 0.09s: 10000 x Old() 13.03s: 10000 x attributes() 14.04s: 10000 x attributes() 8.97s: 10000 x attributes(__main__.Old) 13.13s: 10000 x attributesNew() 14.12s: 10000 x attributesNew2() 8.32s: 10000 x attributesOld() $ python -O f.py 2.2.1 (#4, Aug 21 2002, 14:22:21) [GCC 3.2] 0.14s: 10000 x New() 0.11s: 10000 x New2() 0.10s: 10000 x Old() 12.18s: 10000 x attributes() 12.66s: 10000 x attributes() 7.94s: 10000 x attributes(__main__.Old) 12.26s: 10000 x attributesNew() 12.78s: 10000 x attributesNew2() 7.99s: 10000 x attributesOld() It made no difference. I checked the bytecode and it is the same for accessing a slot as for accessing a normal attribute so optimisations aren't currently possible at that level... BTW your machine seems very fast. What is it? Cheers, Steve. --------------- class Old: pass class New(object): __slots__ = ['a', 'b', 'c', 'd'] # New-style, but not using slots. class New2(object): pass def timeit(repeat, fn, *args, **kw): import time start = time.time() for i in xrange(repeat): fn(*args, **kw) end = time.time() # Format arguments for printout argstring = ', '.join( [str(a) for a in args] + [ '%s=%s' % (k, v) for k, v in kw.items()]) if len(argstring) > 60: argstring = argstring[:57] + '...' print "%.2fs: %d x %s(%s)" % \ ((end-start), repeat, fn.__name__, argstring) def attributes(klass): inst = klass() inst.a = 1 for i in xrange(100): inst.b = inst.a+1 inst.c = inst.a+2 inst.d = inst.a+4 inst.a += 5 def attributesNew(): inst = New() inst.a = 1 for i in xrange(100): inst.b = inst.a+1 inst.c = inst.a+2 inst.d = inst.a+4 inst.a += 5 def attributesNew2(): inst = New2() inst.a = 1 for i in xrange(100): inst.b = inst.a+1 inst.c = inst.a+2 inst.d = inst.a+4 inst.a += 5 def attributesOld(): inst = Old() inst.a = 1 for i in xrange(100): inst.b = inst.a+1 inst.c = inst.a+2 inst.d = inst.a+4 inst.a += 5 def main(): import sys print sys.version timeit(10000, New) timeit(10000, New2) timeit(10000, Old) timeit(10000, attributes, New) timeit(10000, attributes, New2) timeit(10000, attributes, Old) timeit(10000, attributesNew) timeit(10000, attributesNew2) timeit(10000, attributesOld) if __name__ == "__main__": main() From martin at v.loewis.de Tue Sep 17 01:45:00 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Sep 2002 07:45:00 +0200 Subject: pickle magically not working References: <3d865dac@nntp.server.uni-frankfurt.de> Message-ID: jepler at unpythonic.net writes: > If I had to guess, I'd say the "fix" was in Pickle itself, you might turn > something up by investigating Python's CVS tree. Or somebody else might be > able to immediately indicate the relevant code... It's in structseq.c:structseq_reduce (rev. 1.4 and 1.5), also fixed in Python 2.2.1. Regards, Martin From vincent_a_primavera at netzero.net Fri Sep 27 09:35:50 2002 From: vincent_a_primavera at netzero.net (Vincent A. Primavera) Date: 27 Sep 2002 13:35:50 +0000 Subject: comp.lang.python... In-Reply-To: References: Message-ID: <1033133750.1570.22.camel@del-vap-bos.ralphpill.com> Hello, Thank you very much! Vincent A. Primavera. On Fri, 2002-09-27 at 16:15, Gerhard H?ring wrote: > Vincent A. Primavera wrote in comp.lang.python: > > Hello, > > I've been subscribed to python-list at python.org for at least a couple of > > years I would guess. I have been using a mail client to receive all of > > the messages, but I figure that using a news client would be a more > > organized method. However, I can't seem to find what I need to enter > > for a server & user/password combination... > > If your ISP doesn't offer an NNTP server, you'll probably have bad > luck, unless you pay for third-party NNTP access somewhere. > > However, there's a mail-to-news-gateway (and reverse) available at > http://gmane.org/, which NNTP access for many Python mailing lists. > The data you'll need are: > > NNTP server: news.gmane.org > group name: gmane.comp.python.general > > No username or password required for reading. If you post, you'll need > to answer a one-time confirmation message for every group. > > I'd still prefer to use comp.lang.python diretly. But this is quite > cool for all the SIG groups, as you can read them without actually > subscribing. > > -- Gerhard > -- > http://mail.python.org/mailman/listinfo/python-list > From max at alcyone.com Thu Sep 12 16:16:27 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 12 Sep 2002 13:16:27 -0700 Subject: Coding Style: Quotes References: Message-ID: <3D80F61B.A254ED63@alcyone.com> John Waycott wrote: > I'm curious if others have adopted any standards for choice of single > vs. > double quotation marks to delimit strings. A look through the standard > library reveals the choice of one over the other is rather arbitrary. > I > suspect it really makes no difference, but the question has come up > during a > code review. It really makes no difference (provided similar quotes are escaped in the string), so it comes down to a simple matter of style. I personally tend to use single quotes for simple keywords, the equivalent of identifiers, or non-English data (such as HTML or XML fragments), and double quotes for English phrases or text. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ The revolution will not televised \__/ Public Enemy Blackgirl International / http://www.blackgirl.org/ The Internet resource for black women. From jdavis at empires.org Mon Sep 16 05:46:58 2002 From: jdavis at empires.org (Jeff Davis) Date: Mon, 16 Sep 2002 09:46:58 GMT Subject: A question about C/API of python. References: <1818979.1032155554@dbforums.com> Message-ID: Are you sure that you need to access a variable in the .so from the c program? If you really do, then I would recommend using shared memory. It's fast, pretty simple to use, and you don't have to worry about changing it to a python variable and then back again. Regards, Jeff hpyhpy wrote: > > I use python to load C module(.so),then use C load python,like this: > C(main)--->python--->C(.so) > But now my trouble is : > In C(main), I have some Global variable that depend on process of > C(.so). > But because python is in middle of them,so I can't use variable of > C(.so) in C(main) dexterously. > I see some C/API reference but it still pluzzle me.Anybody can tell me > some advise? > Thanks. > > -- > Posted via http://dbforums.com From aleax at aleax.it Fri Sep 27 03:23:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 27 Sep 2002 07:23:53 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <7nHk9.172208$pX1.6117207@news2.tin.it> Message-ID: Terry Reedy wrote: > > "Alex Martelli" wrote in message > news:7nHk9.172208$pX1.6117207 at news2.tin.it... >> The reason >> zz = a and b or c >> is not the same thing as >> zz = a ? b : c >> is that, when a is true and b is false, the former returns c, >> while the latter returns b. > > In almost all the practical cases where I have thought about using > this, b is *not* false or cannot become false, in which important and > real case the two expressions *are* equivalent. A typical, frequent, practical case is classification, e.g.: "Append bleep to list truebleeps when bleep is true, append it to list falsebleeps instead when false". If we had a ternary operator, a natural way of expression would be: (bleep?truebleeps:falsebleeps).append(bleep) Of course this would be a disaster with the and/or idiom instead: (bleep and truebleeps or falsebleeps).append(bleep) As list truebleeps starts out empty, thus false, this buggy code would NEVER append anything to it. In this case, like in most others (but far from all!) we don't need short-circuiting, so we can perfectly well code: (truebleeps, falsebleeps)[not bleep].append(bleep) This is now correct -- but still nowhere as clear as good old: if bleep: truebleeps.append(bleep) else: falsebleeps.append(bleep) which to me remains the canonical way to code this in Python. Yes, it IS fractionally more verbose, but, so what? It's immediately obvious, simple, and not clever. > I think this is an elegant hack, and so I shared it in response to the > OP. Others think it ugly. So be it. It's _dangerous_ -- to use it, one always has to be fully aware of the risk that subexpression b might be false. I think this is a pitfall just waiting for the unwary to stumble. Not being an aesthete, I consider that more important than issues of beauty. Alex From claird at starbase.neosoft.com Tue Sep 17 17:49:15 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 17 Sep 2002 16:49:15 -0500 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: In article , Chris Liechti wrote: >lpgray at uop.com (Lee Gray) wrote in >news:96904b50.0209171305.6d65f574 at posting.google.com: >> My boss is pretty open-minded, but also needs to see something working >> to be convinced Python is even a viable platform (he had never heard >> of it). Otherwise, .Net is a given, whether it's any good or not, >> since corporate is MS all the way. > >with python you have to choice of diffrent GUI libs. if you consider >wxWindows you can play around with the wxPython demo application that comes >with the download. on the other hand when you support win32 only the >win32all package has support for all the windows APIs and it has some >samples that get installed. . . . You can have Python *and* .Net. Well, probably; it's been promised, and, to the extent anyone knew a year ago what .Net is, Python's part of it. While we're pointing out individual applications that might be of interest, please keep in mind that Python is in serious production use at tens of THOUSANDS of sites. Don't judge it solely by what you see of the first two demonstrations someone happens to push your way. Incidentally, Python *is* a "Microsoft solution". There are plenty of people within Microsoft who use Python because of its productivity in Win* contexts. It's hard for me to give concrete references for this claim; essentially all the people doing so describe their efforts only "off the record". I'm willing to bet, though, that Python will be around for longer than VBScript. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From wlfraed at ix.netcom.com Sat Sep 7 13:53:57 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 07 Sep 2002 10:53:57 -0700 Subject: Larry Wall's comment on python... References: Message-ID: David LeBlanc fed this fish to the penguins on Friday 06 September 2002 08:56 pm: > One could hardly expect Larry to say "I have seen Pearl 6 - and it is > Python!" :) > "The serpent has tempted me" -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From max at alcyone.com Wed Sep 11 13:28:28 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 11 Sep 2002 10:28:28 -0700 Subject: function pointer References: Message-ID: <3D7F7D3C.7F47993C@alcyone.com> Christina wrote: > Does Python have function pointers? If not, is there a possibility to > emulate them? Functions and methods (both bound and unbound) are first-class objects in Python. Python doesn't have function pointers, but it doesn't need them. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Procrastination is the thief of time. \__/ Edward Young WebVal / http://www.alcyone.com/pyos/webval/ URL scanner, maintainer, and validator in Python. From bob at eleaston.com Fri Sep 6 13:26:27 2002 From: bob at eleaston.com (Bob Easton) Date: Fri, 6 Sep 2002 13:26:27 -0400 Subject: Interrupting Python Message-ID: I have a script that can run, accessing network resources, for several days. Since the script does not normally need keyed input, exception processing does not raise the keyboard exception until after the program ends normally. I would like to be able to interrupt if from the keyboard, but have not learned the trick. How can I do this? -- Bob Easton From op73418 at mail.telepac.pt Wed Sep 4 16:25:45 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 04 Sep 2002 21:25:45 +0100 Subject: Why read-only nested scopes? References: Message-ID: On Wed, 4 Sep 2002 19:46:49 GMT, Andrew Koenig wrote: >Gon?alo> Anyway, I've been directed to PEP 227, cheerfully obeyed, and >Gon?alo> from what I have understood having read-only nested scopes >Gon?alo> was more of a design decision than something else. And while >Gon?alo> I can live happily with the decision (some would even say >Gon?alo> happier) there is something about the "You can look at it but >Gon?alo> not touch it" attitude that I dislike ;-) > >You can do anything to the object that the object support. >What you can't do is change the binding of the name. Yes, I am aware of this. You can even wrap x in a list and then modify the list to indirectly change x, but it was the rebinding that I was refering to, so let me rephrase the above to "You can look at it AND even touch it but ONLY if suitably dressed" :-) > > x = [] > def foo(y): > x.append(y); > foo(3) > foo(4) > foo(5) > >After executing this code, x is [3, 4, 5]. All the best, Gon?alo Rodrigues From jubafre at brturbo.com Wed Sep 25 19:29:47 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Wed, 25 Sep 2002 20:29:47 -0300 (GMT-03:00) Subject: transform strings list in a int lists or other type??? Message-ID: <872170378.1032996587856.JavaMail.nobody@webmail2.brturbo.com> Can i tranform a list of strings in a list of int, or other type in python??? and also write in a file? I think the open(path,'wb') in __builtin__ dont?t write in a file other types, just strings, rigth??? Juliano Freitas www.gebrasil.hpg.com.br From erikprice at mac.com Tue Sep 10 12:01:00 2002 From: erikprice at mac.com (Erik Price) Date: Tue, 10 Sep 2002 12:01:00 -0400 Subject: Python iCalendar API? Message-ID: <80494127-C4D6-11D6-A54B-00039351FE6A@mac.com> Is there a Python module that provides capability of processing files in .ics (iCalendar) format? I found nothing concrete on Google or at python.org ... Erik -- Erik Price (zombies roam) email: erikprice at mac.com jabber: erikprice at jabber.org From chris.gonnerman at newcenturycomputers.net Mon Sep 30 01:20:40 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 30 Sep 2002 00:20:40 -0500 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xelbcgo56.fsf@ruckus.brouhaha.com> <7x65woks0i.fsf@ruckus.brouhaha.com> Message-ID: <006d01c26841$1fa587a0$ba01010a@local> ----- Original Message ----- From: "Paul Rubin" > No, I'm still not convinced. Is business arithmetic well- > defined enough that you can never do the same calculation two > ways and get different results? > > Example: bunches are three for a dollar. How much do you pay > if you buy nine bananas? > > Answer #1: > price_per_banana = 1.00 / 3 > number_of_bananas = 9 > total_price = number_of_bananas * price_per_banana > print total_price > > Answer #2: > price_per_bunch = 1.00 # three bananas > number_of_bunches = 3 > total_price = number_of_bunches * price_per_banana > print total_price > > With floating point and rounding on output, you get the same > answer both ways. > > With decimal arithmetic, you get $2.97 the first way and > $3.00 the second way. Excellent example, wrong focus. The business user (in this case, the retail store owner/manager) would define which method, and which results, are right. The second mode is the "canonical" way in the manual system, but lately I've realized that many (most?) retail POS systems can do it "both" ways, handling single items by a variation of method 1 which gives answers consistent with method 2. I'm glad I didn't have to write and debug that code. > For "business arithmetic" to always give the same answer, it > has to forbid at least one of those methods of doing the > problem. Except for the hack I described above, you're right. *The business user will define the rules* regarding when and to how much you round. You seem to think that I mean to round to two places (as in US dollars and cents) when what I mean is to handle numbers in (or as if in) base 10 all the time. It isn't a question of when you round, so much as it is a question of what *happens* when you round. Proper floating decimal numbers would also solve the problem; it's floating binary that causes unexpected anomalies. The banana problem might be solved in a given POS (point of sale) system by using four or five decimals, then rounding to two at the line-item level. That would give correct results for both methods above. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From aleax at aleax.it Thu Sep 19 07:27:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 11:27:53 GMT Subject: lists in dictonaries ? References: Message-ID: Manuel Hendel wrote: > Is it possible to put lists in dictionaries? And is it also possible > to put multiple lists in a dictionary for one key? Yes to the first, no to the second (stricto sensu). Lists are OK as values in dictionaries. But a dictionary has ONE value "for one key". You can make that value a list of lists, a tuple of lists, and so on, but not, strictly speaking, "multiple" anythings. Alex From eric.brunel at pragmadev.com Mon Sep 16 03:48:29 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 16 Sep 2002 09:48:29 +0200 Subject: Tkinter listbox clicking problem References: <2D7E3697CF5D1521.5D9711540E657ED8.7EF0451C598438FC@lp.airnews.net> <9rCg9.262546$kp.888557@rwcrnsc52.ops.asp.att.net> Message-ID: Matthew Bonig wrote: > I'm confused... I looked at these examples but I didn't see anything pop > out that answered my question... or was this mostly for the other post? Binding to is equivalent to binding to . When your button is pressed, the list has actually not been updated yet. But if you bind to , you'll get what you want. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From johnroth at ameritech.net Sun Sep 1 19:40:36 2002 From: johnroth at ameritech.net (John Roth) Date: Sun, 1 Sep 2002 19:40:36 -0400 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: "A.M. Kuchling" wrote in message news:un50ccotaak86b at corp.supernews.com... > In article <3d725881.345921 at news.t-online.de>, Gerson Kurz wrote: > > in the match or find function. So basically, couldn't one come up with > > a *human readable* syntax for re, and compile that instead? Python > > Maybe Ka-Ping Yee's rxb? http://web.lfw.org/python/rxb15.py > > The problem with a new syntax is that no one else would be using it, so > you'd still need to learn the existing syntax for use with grep, vi, Perl, > &c. (It wouldn't surprise me if Perl 6's revised regexes run into this very > difficulty and don't gain much adoption.) I see you've already gotten to my suggestion - look at Apocalypse 5 and Exegesis 5 on the O'Reilly Perl page and see what Larry Wall has done. I tend to agree that Larry is going out on a limb. However, since he's done so, if we are thinking about a new regex syntax, we really should consider doing it the same way. As you point out, there's going to be enough difficulty getting one radical revision accepted. Getting two different ones accepted is likely to sink everyone's effort. Also, doing it the same way will simplify the Python effort in Parrot (assuming anyone cares about that any more...) And as far as grep, Vi and so forth are concerned (Perl isn't an issue - that's the way it's going,) doing something to fix them isn't all that hard - at least for the GNU versions of the programs. > > --amk From pearu at cens.ioc.ee Mon Sep 9 04:52:38 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Mon, 9 Sep 2002 11:52:38 +0300 (EEST) Subject: returning values from FORTRAN with f2py In-Reply-To: Message-ID: On 7 Sep 2002, Chris Fonnesbeck wrote: > I am wondering how to persuade some fortran code that I have compiled > with f2py to return its calculated values to me in python. I have > some code that does gaussian elimination (mostly from Numerical > Reciopes), and is supposed to return an inverted matrix so that I can > solve a system of linear equations. However, when run in python, the > function runs without error but returns no values: > > >>> a = [[2,1,3],[1,-1,1],[3,6,-1]] > >>> b = [7,2,10] > >>> import gauss > >>> gauss.gauss(a,3,b,1) > >>> > > Is there something that I have to change in my fortran code to make > this work? You can add the following comment lines to your Fortran code: cf2py intent(in,copy,out) a cf2py intent(in,copy,out) b (provided that you want the arguments a and b returned to Python). If you cannot modify Fortran codes then you should create a .pyf file and insert the above lines there (without cf2py prefix, of course). HTH, Pearu From storedmails at gmx.net Tue Sep 24 10:43:59 2002 From: storedmails at gmx.net (beachboy) Date: 24 Sep 2002 07:43:59 -0700 Subject: Sessionhandling References: Message-ID: > Are you aware that a users language preference is encoded in every > request that they make to a web server, through the "Accept-Language" > HTTP header? Thank you very much for your response. This could be a very good solution, but the problem is that the company which i work for want that the user has to choose which language he want. So I still have the problem with Sessions. From fpm at u.washington.edu Sun Sep 15 23:15:48 2002 From: fpm at u.washington.edu (Frank Miles) Date: 16 Sep 2002 03:15:48 GMT Subject: pypgsql -- not preserving transactions ? Message-ID: I've discovered that the 2.0 version of pyPgSQL packaged with Debian/woody doesn't preserve transactions (at least with Postgres). For example, if a transaction consists of a series of INSERTs, and an error occurs partway through the series, a COMMIT at the end of the series will result in the INSERTs up to the erroneous one being thrown out (rollback), but unfortunately those following the error being committed. In looking at the imported code, there are comments about trying to recover from a defective state, with the class variable 'inTransaction' being cleared. Does any newer version fix this nonsense? Or perhaps someone can recommend an alternative module, preferably compatible with DB-API 2.0? TIA! -frank -- From peter at engcorp.com Fri Sep 6 22:47:23 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Sep 2002 22:47:23 -0400 Subject: py2exe and a single exe file? References: <3D792351.3070008@motorola.com> Message-ID: <3d7968a2@news.sentex.net> Stephen Boulet wrote: > I'm trying to get py2exe to work for me, and I must be doing something > wrong. > > I have a script that uses easygui (which uses Tkinter) and Numeric. It > also imports a small module from the same directory that the script > resides in. > > I try building it like this: > > python setup.py py2exe -d N:\ -i easygui > > It builds and runs, but only with the other stuff in the build directory > with the generaged exe. The other stuff is: > > tcl directory containing tcl8.3 and tk8.3 directories > _numpy.pyd > _sre.pyd > _tkinter.pyd > multiarray.pyd > umath.pyd > > What I would like to accomplish is just having a single exe file lumping > everything together. Is this possible? In addition to Gerhard's answer: I've successfully used PowerArchiver (and I'm sure there are a dozen other similar possibilities) to package up a py2exe'd program plus all the DLLs into a single .EXE which is really just a self-extracting-and-executing ZIP file. You run it, it unpacks itself to a temporary directory, runs the main program, and then cleans up everything (or not, optionally) when it's done. -Peter From cliechti at gmx.net Sat Sep 7 12:54:50 2002 From: cliechti at gmx.net (Chris Liechti) Date: 7 Sep 2002 18:54:50 +0200 Subject: getting input in a embeded GUI app ... References: Message-ID: rgkindya at yahoo.co.in (rgkindya) wrote in news:b2df190a.0209070836.9713b08 at posting.google.com: > Dear Newser, > > I'm a newbie for python. I wish to embed Python interpreter into my > vc++ GUI app(for ms-windows only). when executing input statements (eg > raw_input()) , in pythonwin environment (activepython) , it gets input > using a new small input window, in IDLE , it gets input in its own > window (next line). please help me to do these two type of inputs in > my embeded GUI app. my app is only GUI , there is no console mode. tha pythonwin way: you can write your own input function in c/c++ that gets the input from a message box. it should return Python string. (i assume you've found out how to write python funcs in c/c++, i.e. like those for in a module) then you can replace the builtin function raw_input with your function (assign it to __builtin__.raw_input). take a look at the python win sources on how to do this in python. > please debug my engliz bugs ... :-) chris -- Chris From fbarbuto at telusplanet.net Fri Sep 20 05:11:01 2002 From: fbarbuto at telusplanet.net (Fausto Arinos de A. Barbuto) Date: Fri, 20 Sep 2002 09:11:01 GMT Subject: What the heck? open() requires an integer? Message-ID: Hi, The open() function is returning me a strange error. An attempt to create an output file with f = open("output.txt","w") yields the following error: Traceback (most recent call last): File "", line 1, in ? TypeError: an integer is required That happens when I am using either Pythonwin or IDLE 0.8, but not in interactive mode. In this latter case I can open, write to and close a file OK. What's the matter? Thanks in advance! ---Fausto From mhammond at skippinet.com.au Fri Sep 6 23:23:54 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 07 Sep 2002 03:23:54 GMT Subject: COM/Active X newbie question References: <5523ec5.0209061446.1404cd10@posting.google.com> Message-ID: Gabe Gittings wrote: > I am a newbie to prgramming in Python and programming under windows. I > am trying to access an .ocx file. I can access the methods in python > after running makePy.py but when I run a test script and try to access > a method from the COM object I get this error. > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python22\Lib\site-packages\win32com\gen_py\7ADCDC5B-D0B6-11D1-AA76-002078136998x0x1x0.py", > line 57, in GetRunManagerStatus > return self._oleobj_.InvokeTypes(0xa, LCID, 1, (8, 0), (),) > com_error: (-2147418113, 'Catastrophic failure', None, None) > If it is a true OCX, then it probably needs to be hosted in a GUI environment, such as pythonwin. See pywin\demos\ocx for examples. If you can find any VBScript or JScript code that works with the object, it should be usable the way you are trying. If the only examples you can find are hosted inside a form in a full-blown VB sample, then the Pythonwin thang should work. Mark. From ht at cogsci.ed.ac.uk Mon Sep 16 13:18:19 2002 From: ht at cogsci.ed.ac.uk (Henry S. Thompson) Date: 16 Sep 2002 18:18:19 +0100 Subject: Accessing Windows Registry under cygwin In-Reply-To: <20020916164259.GG424@tishler.net> References: <20020916164259.GG424@tishler.net> Message-ID: Jason Tishler writes: > Sorry for the sluggish response time, but I just returned from > vacation...] > > On Mon, Sep 09, 2002 at 09:59:41PM +0100, Henry S. Thompson wrote: > > On 11 September 2001 Norman Vine said "I have managed to get the > > '_winreg' module working with Cygwin < _winreg = Python access to the > > Windows Registry >" [1]. Assiduous searching does not reveal that > > this work ever surfaced -- where might I find it? > > See the following: > > http://sourceforge.net/tracker/?group_id=5470&atid=305470&func=detail&aid=554807 > > Are you willing to help? I wish I were competent to help -- I have no experience with programming to WIN32 APIs. I'll download the package and have a look. It's not entirely clear from the sourceforge log what's actually needed next. ht -- Henry S. Thompson, HCRC Language Technology Group, University of Edinburgh W3C Fellow 1999--2002, part-time member of W3C Team 2 Buccleuch Place, Edinburgh EH8 9LW, SCOTLAND -- (44) 131 650-4440 Fax: (44) 131 650-4587, e-mail: ht at cogsci.ed.ac.uk URL: http://www.ltg.ed.ac.uk/~ht/ [mail really from me _always_ has this .sig -- mail without it is forged spam] From jepler at unpythonic.net Tue Sep 17 22:37:29 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Tue, 17 Sep 2002 21:37:29 -0500 Subject: timeoutsocket module help In-Reply-To: References: Message-ID: <20020917213720.A2554@unpythonic.net> You won't have a lot of luck using timeoutsocket to influence the timeout of name lookups -- those are done in C code, not at the level where timeoutsocket can be useful. Investigate a pure python DNS setup, like pydns (http://pydns.sourceforge.net/). Jeff PS following for your enjoyment, an inefficient program that attempts to look up a host in many different RBLs, using threads for parallelism and the aforementioned pydns for lookups with a defined timeout: RBL_LIST = ( 'bl.redhatgate.com', 'blackholes.intersil.net', 'dews.qmail.org', 'dssl.imrss.org', 'mr-out.imrss.org', '3y.spam.mrs.kithrup.com', 'blackhole.com', 'pu.net', 'blackholes.2mbit.com', 'blackholes.five-ten-sg.com', 'blackholes.mail-abuse.org', 'blackholes.wirehub.net', 'blacklist.spambag.org', 'block.blars.org', 'blocktest.relays.osirusoft.com', 'dev.null.dk', 'dialup.blacklist.jippg.org', 'dialups.mail-abuse.org', 'dialups.relays.osirusoft.com', 'dnsbl.njabl.org', 'list.dsbl.org', 'multihop.dsbl.org', 'unconfirmed.dsbl.org', 'dul.maps.vix.com', 'dul.orca.bc.ca', 'dynablock.wirehub.net', 'flowgoaway.com', 'formmail.relays.monkeys.com', 'http.opm.blitzed.org', 'inputs.relays.osirusoft.com', 'ipwhois.rfc-ignorant.org', 'opm.blitzed.org', 'orbs.dorkslayers.com', 'outputs.orbz.org', 'relays.ordb.org', 'pm0-no-more.com', 'pu.net', 'proxies.relays.monkeys.com', 'rbl-plus.mail-abuse.org', 'rbl.maps.vix.com', 'rbl.spam.org.tr', 'relays.dorkslayers.com', 'relays.mail-abuse.org', 'relays.osirusoft.com', 'relays.radparker.com', 'relays.visi.com', 'sbl.spamhaus.org', 'socks.opm.blitzed.org', 'socks.relays.osirusoft.com', 'bl.spamcop.net', 'spamguard.leadmon.net', 'spamhaus.relays.osirusoft.com', 'spammers.v6net.org', 'spamsites.relays.osirusoft.com', 'spamsources.fabel.dkspews.relays.osirusoft.com', 'wingate.opm.blitzed.org', 'xbl.selwerd.cx', 'ztl.dorkslayers.com', 'or.orbl.org', 'spamips.rbl.shub-inter.net', ) import sys, socket, threading, DNS DNS.DiscoverNameServers() def check_one(i, j): dns = DNS.Request(timeout=5) k = "%s.%s" % (i, j) try: res = dns.req(k) except DNS.DNSError, reason: l = reason else: status = res.header['status'] if status == 'NOERROR' and res.answers: l = res.answers[0]['data'] elif status == 'NOERROR': l = "NOERROR but no answer?" elif status == 'NXDOMAIN': return else: l = status print "%-50s %s" % (k, l) for i in sys.argv[1:]: i = socket.gethostbyname(i).split(".") i.reverse() i = ".".join(i) tl = [] for j in RBL_LIST: t = threading.Thread(target=check_one, args=(i, j)) t.start() tl.append(t) while tl: tl.pop().join() From kkto at csis.hku.hk Fri Sep 6 08:11:15 2002 From: kkto at csis.hku.hk (Isaac To) Date: 06 Sep 2002 20:11:15 +0800 Subject: Dictionary... Message-ID: <7ir8g7xqqk.fsf@enark.csis.hku.hk> Hi, Some time ago I want to have a dictionary-like type that can support dictionary operation, plus that given any key, I want to know the predecessor and successor of any given key efficiently. I've thought of using a Python list, but it is impossible to update quickly. The closest thing I can think of is an auxillary map that implements the successor and predecessor functionalities. But I'm wondering there is anything better. After all, Python dictionaries are implemented by height balancing tree, so internally the needed data can be retrieved efficiently. Any hint? Regards, Isaac. From sschwarzer at sschwarzer.net Wed Sep 11 16:23:02 2002 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 11 Sep 2002 22:23:02 +0200 Subject: "str.contains(part)" or alternatives? Message-ID: Hello all I would like to get your thoughts on testing if a string contains another. To do something dependent on whether a part is contained in another string, the following code is familiar to me: >>> s = 'Hello' >>> if s.find('ll') != -1: ... do_something_if_found() ... else: ... do_something_if_not_found() However, I dislike the test for the special value -1; that reminds me of error code checking. On the other hand, using exceptions could look like >>> try: ... s.index('ll') ... do_something_if_found() ... except ValueError: ... do_something_if_not_found() This has the problem that a ValueError raised in do_something_if_found() may give the false impression that the substring isn't contained in the string s. Moreover, that code doesn't represent my thoughts very well. (Maybe I could say that better if I were a native English speaker :) ). I would like something analogous to .startswith and .endswith: >>> s = 'Hello' >>> if s.contains('ll'): ... do_something_if_found() ... else: ... do_something_if_not_found() Do you have other suggestions how to do the test easily without using special values? Should a .contains method be part of string objects in future Python versions? What do you think? Stefan From mike at bindkey.com Fri Sep 13 15:14:54 2002 From: mike at bindkey.com (Mike Rovner) Date: Fri, 13 Sep 2002 12:14:54 -0700 Subject: squeeze with packages Message-ID: Hi all, I'm trying to use squeeze (http://www.pythonware.com/products/python/squeeze/) and run into couple of problems: - I could not squeeze packages (subdirs with __init__.py) and - when I try to make archive (squeeze -1x ...), I got an error "name 'explode' is not defined". Is it possible to bypass those obstacles? Thanks in advance, Mike From andres.meza at nuevosmedios.ws Wed Sep 18 12:01:09 2002 From: andres.meza at nuevosmedios.ws (Andres Meza) Date: Wed, 18 Sep 2002 11:01:09 -0500 Subject: problems getting a single item out of a list Message-ID: <1032364878.3088.64.camel@coraje> Manuel Hendel wrote: > I try to get a single item out of a list, but after this, the single > item is stil a list item. > > domainfield = fields[3:4] > > I just want to get a new variable with a the value of the 3rd item of > the list fields. > If I understand your question, you have two ways to make it work, from my point of view: a) Get the value from domainfield: domainfields = fields[3:4] value = domainfields[0] b) Get the value directly from the list: value = fields[3] I hope it helps. Bye, -- Andr?s Meza Technical Manager __Nuevos Medios - NM S.A.____________________ e-mail: andres.meza at nuevosmedios.ws day time phone: (+572)6827794 ext.102 url: www.nuevosmedios.ws -------------- next part -------------- An HTML attachment was scrubbed... URL: From luc.saffre at gmx.net Mon Sep 16 09:37:21 2002 From: luc.saffre at gmx.net (Luc Saffre) Date: Mon, 16 Sep 2002 16:37:21 +0300 Subject: "if x == None" raises "'NoneType' object is not callable" References: Message-ID: <3D85DE91.8010102@gmx.net> Thank you, Mark. Now I will remeber the difference between "is" and "=="! There is another big bug in my code snippet. If I write:: try: return self._values[name] except KeyError,e: raise AttributeError,str(e) instead of:: try: return self._values[name] except KeyError,e: AttributeError,str(e) then the results are also much more as expected :-) For every undefined attribute I told Python "yes, I have this attribute defined, and its value is None". The explanation for this strange message is now clear (at least for my simplistic thinking): - Because I used "==" (and not "is"), Python made a deep look into my object and looked into each attribute, not only the hash() - One of these attributes was some of those magic functions, perhaps __cmp__(). And my __getattr__() returned None instead of raising AttributeError for these attributes which, I admit, if you define them, should be callable... Okay... Python is great! Luc On 9/16/2002 4:14 PM, Mark McEahern wrote: >Comparison to None should generally be comparison by identity rather than >equality: > > if x is None: > >or: > > if x is not None: > >not: > > if x == None: > >nor: > > if x != None: > >What you might consider is adding a __len__ magic method to your Row class >like so: > > def __len__(self): > return len(self.values) > >Then you can do this: > > r = Row() > if r: > ... > else: > ... > >Cheers, > >// mark > >- > > > > From jb at cascade-sys.com Sat Sep 28 04:07:16 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Sat, 28 Sep 2002 01:07:16 -0700 Subject: combining mailbox and email modules References: <1fj6jb2.62mx08f47amsN%fgranger@alussinan.org> Message-ID: <3D956334.3020804@cascade-sys.com> Fran?ois Granger wrote: >Bob Horvath wrote: > > > >>The problem is that it looks good to me. I've played around with >>it, and if I take out the MIME gunk (It actually is a Klez virus), >>it parses ok. >> >> > >I have had difficulties with the handling of multipart message with the >email package. I did not found a solution yet. > My experience is that a lot of Spam violates Mime rules. Often they omit the end marker, I guess relying on EOF to terminate the message. Then the python packages can't parse any of the remaining messages. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From tjlavoie at mb.sympatico.ca Tue Sep 17 09:53:33 2002 From: tjlavoie at mb.sympatico.ca (Tim Lavoie) Date: 17 Sep 2002 08:53:33 -0500 Subject: tkinter asyncore.loop References: Message-ID: <87znugbu3m.fsf@theasylum.dyndns.org> >>>>> "Rune" == Rune Hansen writes: Rune> Hello, Some months back I sendt a question to the list where Rune> I asked if anyone knew how to catch errors in an asyncore Rune> loop. I got an answer to override the "handle_error" in the Rune> client. I still can't get Rune> it to trap any errors though. The error I need to trap is Rune> "Connection lost". If I remove the network connection and Rune> try to update the stream Rune> or post to the socket nothing happens. When I reconect the Rune> network my application just continues to serve like nothing Rune> has happened. This is Rune> of course nice, but not the functionallity I'm looking for. I tried much the same thing, and never did see much in useful errors hitting my handle_error, but catching exceptions in handle_read did the trick. My little app also uses tkinter and asyncore, along with timeoutsocket. Anyway, the exceptions were caught and used to trigger the error-handling callback to do the work. From mbonig at hotmail.com Fri Sep 13 12:49:28 2002 From: mbonig at hotmail.com (Matthew Bonig) Date: Fri, 13 Sep 2002 16:49:28 GMT Subject: Tkinter listbox clicking problem Message-ID: Right now I have it bound so when a Tkinter listbox gets a (lb.bind("", someFunc)) it calls function someFunc. Now, someFunc() simply prints the curselection(). The problem is it's lagged... if I first select list item 1 (index 0), and then 2, and then 3 (array indexes 0,1,2) it prints out themout incorrectly. (I have someFunc actually do some try, except stuff so I don't get uncaught exceptions) Instead of printing 0,1,2 it prints "nothing selected", 0, 1. The function get's called before the listbox updates it's selection markers! Does anybody know how I could force listbox to update it's selection markers so instead of printing "nothing selected, 0,1 it prints 0,1,2 like it should? Thanks Matthew Bonig From grahamd at dscpl.com.au Sun Sep 15 03:06:36 2002 From: grahamd at dscpl.com.au (Graham Dumpleton) Date: 15 Sep 2002 00:06:36 -0700 Subject: Pmw.ScrolledText programatically scrolling References: <3D81D44E.C5FC4A8B@mill.co.uk> Message-ID: Joe Connellan wrote in message news:<3D81D44E.C5FC4A8B at mill.co.uk>... > I've got a Pmw.ScrolledText() that I'm using as a log and I've written > an addToLog() method like so: > > def addToLog(self, logString): > self.logScr.configure(text_state = 'normal') > self.logScr.insert(END, logString) > self.logScr.configure(text_state = 'disabled') > > I now want it to scroll when I add a line so the user doesn't have to > constantly scroll down to view the most recent lines. > > I can't find any info on doing this with ScrolledText or its text > component - do I need to reposition the scrollbars for it to scroll? Another slightly different way to what others have suggested is the following: def __init__(self,...): ... self._eventView = Pmw.ScrolledText(g1.interior(),text_padx=4, text_pady=4,text_wrap="char",text_state="disabled", vscrollmode="static") self._eventView.pack(side="top",padx=8,pady=8,fill="both",expand="true") self._eventView.yview("moveto",1.0) def _clearLog(self): self._eventView.configure(text_state="normal") self._eventView.clear() self._eventView.configure(text_state="disabled") self._eventView.yview("moveto",1.0) def _appendLog(self,message): p1,p2 = self._eventView.yview() self._eventView.configure(text_state="normal") self._eventView.insert("end",message) self._eventView.configure(text_state="disabled") if (p1 == 0.0 and p2 == 0.0) or p2 == 1.0: self._eventView.yview("moveto",1.0) A trick in this code is that one uses yview() to determine what of the text is being shown and will only move to last text inserted if the scroll area was already at the end. The reason for this is that it can be mighty annoying to have the scrolled area always go to the end if you have used the scroll bar to explicitly go to an earlier part of the text to look at it. From jason at atdesk.com Fri Sep 27 09:38:20 2002 From: jason at atdesk.com (Jason D. Smith) Date: Fri, 27 Sep 2002 13:38:20 +0000 (UTC) Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> <20020926164641.1753ebbb.ckasso@sprynet.com> Message-ID: Chris Kassopulo writes: > On 26 Sep 2002 10:56:45 -0700 > pknotz at sandia.gov (Pat Notz) wrote: > > > @ = "at" > > ! = "bang" > > . = "dot" > > * = "star" I'm for "George" and "Penelope" -- Jason. Hi, I'm Bob. I'm a tomato and I'm here to help you. From peter at engcorp.com Fri Sep 6 23:15:54 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Sep 2002 23:15:54 -0400 Subject: Timothy Rue References: <898662b7d85d2c966c0bd45d563d5d2d@xganon.com> Message-ID: <3d796f52@news.sentex.net> Martijn Faassen wrote: > Which group is that anyway? :) Seems like you and Tim have been posting > on comp.sys.amiga misc. Apparently you were looking for a Tim Rue > FAQ at the time, and the thread has a link, FAQ posted in '99! > > http://groups.google.com/groups?q=tim.rue.faq&start=10&hl=en&lr=&ie=UTF-8&scoring=d&selm=7r5lrp%24ftj%241%40ns2.dialnet.net&rnum=15 Thanks for the link, Martijn! Humorous reading at this point. I find the revelations about the Team AMIGA conspiracy especially intriguing, considering the past connections between certain PSU members and the From wurmy at earthlink.net Thu Sep 12 22:11:53 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Fri, 13 Sep 2002 02:11:53 GMT Subject: Expect() from telnetlib giving me problems. References: <4378fa6f.0209121325.130766fc@posting.google.com> Message-ID: <3D814A31.2010909@earthlink.net> Marc wrote: [snip] > File "C:\python22\lib\telnetlib.py", line 541, in expect > list[i] = re.compile(list[i]) > File "C:\Python22\lib\sre.py", line 178, in compile > return _compile(pattern, flags) > File "C:\Python22\lib\sre.py", line 228, in _compile > raise error, v # invalid expression > error: nothing to repeat Note that this is an error in sre.py, not in telnetlib. (A clue! ;-) > I've tried several different ways to get the expect command to work. I > can't find any examples and only limited documentation. Here is how > I'm trying to implement it: > > alist = [ 'COMPLD', '*/' ] > buffer = conn.expect(alist, 5) > > Can someone please tell me what is wrong or provide me with some > working examples of using the command. expect() expects a list of regular expressions. '*/' probably isn't a valid regex. See also http://www.python.org\doc\lib\telnet-objects.html """ expect(list[, timeout]) Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in seconds; the default is to block indefinitely. """ HTH, -- Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA==')) # decode for email address ;-) The Pythonic Quarter:: http://www.awaretek.com/nowak/ Kaa:: http://www.awaretek.com/nowak/kaa.html From ajw126NO at SPAMyork.ac.uk Wed Sep 11 09:48:56 2002 From: ajw126NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Wed, 11 Sep 2002 14:48:56 +0100 Subject: Abstract Syntax Trees References: Message-ID: What an idiot I am! It was the fact that it didn't have a new line at the end that was causing the problem. It does seem strange that the file will run fine, but you can't access it's syntax tree. That looks suspiciously like a bug to me... Thanks, Andrew "holger krekel" wrote in message news:mailman.1031743334.4015.python-list at python.org... > Andrew Wilkinson wrote: > > Hi, > > > > I'm having a lot of trouble trying to get the parser and compiler modules to > > properly parse some files. > > > > At the moment the trouble seems to be with any loop construct (i.e. for or > > while). > > > > If you create a test file like this... > > > > --- > > for i in range(10): > > print i > > --- > > make sure that this file has a newline at the end. > > others would say, get a better OS :-) > > regards, > > holger > From leafnode-usenet at schabi.de Thu Sep 19 09:28:34 2002 From: leafnode-usenet at schabi.de (Markus Schaber) Date: Thu, 19 Sep 2002 15:28:34 +0200 Subject: Remarks to Python 2.3 References: <20020918222421.328088eb.use-net@schabi.de> Message-ID: <20020919152834.592eaa39.leafnode-usenet@schabi.de> Hallo, martin at v.loewis.de (Martin v. Loewis) schrieb: > Or, better yet, submit bug reports. I'm not really shure whether my remarks are about "bugs" - I just wanted to collect other opportunities here to help me decide whether one can regard this as bugs or not, and eventually submit bug reports. Gru?, Markus From cjw at sympatico.ca Wed Sep 25 08:53:43 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 25 Sep 2002 08:53:43 -0400 Subject: Attempt to install and test gnuplot fails Message-ID: <3D91B1D7.A5AB6F85@sympatico.ca> An HTML attachment was scrubbed... URL: From martin at v.loewis.de Tue Sep 10 14:42:34 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 10 Sep 2002 20:42:34 +0200 Subject: shared libraries References: Message-ID: "Jim Taylor" writes: > The loader is loading the module, however, during the init function when > Py_InitModule() is called, a segmentation fault occurs indicating an address > out of bounds error. When I try to print the contents of the module table > from within the initialization function, I also get a segmentation fault, so > the problem is the way in which the module has been loaded. It appears there > is an address space issue, but I don't know how to resolve it. > > Ideas anyone? I recall the problem, but I don't think it was ever solved. "A gcc bug" was the theory that was most widely used to explain the phenomenon. Of course, this was all a few years ago when Python 1.5 was still in use :-) Regards, Martin From bokr at oz.net Mon Sep 9 17:58:38 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Sep 2002 21:58:38 GMT Subject: Embedded Python implementation References: Message-ID: On Sat, 07 Sep 2002 04:50:52 GMT, Evan wrote: >Hello, > >I am currently trying to embed Python in an application I am writing, >and all is going well, except for one inexplicable bug.. > >When I pass a variable (pointer to a string) to PyRun_String, it will >always error on line 2, character 5.. regardless of what is actually on >the line in that spot (for that matter, even if there is no line 2).. > >The script works perfectly when I place it in a file, and use >PyRun_File, and it also works perfectly when I place the string in >quotations, and pass it to PyRun_String directly inside the C code.. > >The C code in question is as follows: >if ( PyRun_String( com_list, Py_file_input, pGlobals, pLocals ) == NULL ) > PyErr_Print(); > >I am confident the problem is not with pGlobals or pLocals, as those >arguments are used with PyRun_File, as well as with the quoted string.. > Looking at \python-2.1\python\pythonrun.c: -- int PyRun_SimpleString(char *command) { PyObject *m, *d, *v; m = PyImport_AddModule("__main__"); if (m == NULL) return -1; d = PyModule_GetDict(m); v = PyRun_String(command, Py_file_input, d, d); if (v == NULL) { PyErr_Print(); return -1; } Py_DECREF(v); if (Py_FlushLine()) PyErr_Clear(); return 0; } -- I would model the code after that. You say you have the directories, and Py_file_input is the constant from Python.h, so capture v and do the right thing (note the decref), IWG ;-) Regards, Bengt Richter From jb at cascade-sys.com Wed Sep 25 21:45:20 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 25 Sep 2002 18:45:20 -0700 Subject: Larry Wall's comment on python... References: Message-ID: <3D9266B0.7090906@cascade-sys.com> sismex01 at hebmex.com wrote: >>Ironically, Guido originally ruled (in the style guide, IIRC) >>that thou shalt use tabs and tabs are 8 spaces, "as god >>intentended them to be." >> >> > >Yeesh! Why in God's name would he say such a dumb thing? >I mean, even ancient mechanical typewriters have movable >tab settings. Rigid, 8-char tabs is just so... neolithical. > Once upon a time, a large class of computers, and their attendant peripherals, OSs and utility programs universally implemented tabs hard-wired at 8 stops. In some circles this heritage extended back 30 or 40 years. Unix originally followed this convention, as did IIRC all Dec computers and that of most other "minicomputer" vendors. Ed and the original VI editors only had fixed tab stops consistent with terminal drivers and all the unit record equipment at the time. IIRC, even Emacs originally only had tab stops at every 8 columns. The original PC also followed this convention, though not all applications did. I don't know for sure but I bet $1 that Linux tty drivers today also are hard wired at 8 char tab stops. Now, if you've ever worked in an environment where EVERYBODY uses the same tab stops then you'd probably agree that tabs are vastly superior to spaces. I don't think there's any question. I presume it's from this perspective that the right honorable BDFL issued his original proclamation, which is actually quite reasonable, especially from my old fart's perspective. In fact, problems only arise when alternative, competing tab stop conventions try to coexist, which I agree is not generally solvable. Closest solution I've seen is some sites where everybody uses Emacs and employ coding conventions so that on startup Emacs can read a specially coded comment and automatically switch to the proper indent for that file. This can sort of work but your printer and other rendering utilities also all have to recognize the codes. Spaces are a more practical solution. I myself still prefer tabs as I find "indenting" and "out denting" sections of code to be a common operation (in Python and in other languages). Inserting or removing an "if" or changing inline code to a function makes indenting and out denting a common operation. In the environments I use, this works well with tabs and not so well or at all with spaces. By default, I still prefer 8 char stops but I also find I can live just fine with 4. But I can't stand it without tabs. I'll convert to spaces if I need to when delivering code but I can't work on it that way. Anyway, what's wrong with the "neolithical" 8 char stops? For several decades, all the C code ever written was tab indented at 8 columns, along with most of the text and other programming languages on Unix. Some people complained that in practice 8 char tabs forced them to indent too much and their programs got squashed off the right edge of the page. I have little sympathy for that argument, as I feel if your program is properly modularized then then this should not be much of a problem as individual modules should not have to be indented all that much. Also, I suspect part of the pressure came from Pascal users, where some coding conventions require indenting two levels, once for the begin/end pairs and again a second time for the code contained between them. What a crock. For what it's worth, Python's C implementation today appears to be tab indented to 8 columns, at least all the parts I've looked at. The main interpreter loop is a good example of a "complex" piece of code. The innermost loop includes a single switch statement that's over 1400 lines long! Surrounding logic require that the switch statement and case labels start 2 tab stops in and thus the body of each case starts 3 stops in or in column 24. Yikes, that's like 1/3 of the total. And yet none of the case bodies extend past column 73 or so. Turns out that in practice most code lines are pretty short. The ones that aren't typically are function calls with multiple arguments, and these may easily be split onto multiple lines (often thereby increasing readability). Since Guido personally wrote the bulk of this system as a labor of love, I surmise that he's still pretty sentimental about the old ways. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From SBrunning at trisystems.co.uk Tue Sep 10 09:55:23 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Tue, 10 Sep 2002 14:55:23 +0100 Subject: [UK] Reminder - the next Python South-East UK booze-up is on Thur sday, September 12th, 2002 Message-ID: <31575A892FF6D1118F5800600846864DCBD77C@intrepid> The next Python South-East UK booze-up is on Thursday, September 12th, 2002, at The Lamb and Flag, Covent Garden, London, at seven p.m. See and for details. All welcome! No PSU business to be ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From pyth at devel.trillke.net Mon Sep 2 07:23:48 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 2 Sep 2002 13:23:48 +0200 Subject: Why it is so dramatical? In-Reply-To: <200209021251.17165.b.maryniuk@forbis.lt>; from b.maryniuk@forbis.lt on Mon, Sep 02, 2002 at 12:51:17PM +0200 References: <200209021228.58453.b.maryniuk@forbis.lt> <20020902124505.J3893@prim.han.de> <200209021251.17165.b.maryniuk@forbis.lt> Message-ID: <20020902132348.K3893@prim.han.de> Bo M. Maryniuck wrote: > On Monday 02 September 2002 12:45, holger krekel wrote: > > It's much more interesting to look at real performance limitations > > instead of some theoretical pusing-the-limits loops. > Hmmm... I've raised this, `coz I have a problem with a perfomance in Python > app, which generates XML for XSLT. I found, that > > string1 += string2 > > ...sucks and just for experiment I got rewrote XML generating piece of code to > Perl and I've found, that Perl does the same *much* faster than Python. :( Did you try using cStringIO? With your first example [hpk at cobra /tmp]$ python slow.py took 4.68154907227 seconds took 0.00871503353119 seconds where func2 is: def func2(): _body = cStringIO.StringIO() _data = 'A'*81 for a in xrange(0, 0xfff): _body.write(_data) return _body.getvalue() (you need to do 'import cStringIO' at the top of the file.) and func1 is your code. regards, holger P.S: the full script import cStringIO _data = 'A'*81 def func1(): _body = '' _data = 'A'*81 for a in xrange(0, 0xfff): _body += _data return _body def func2(): _body = cStringIO.StringIO() _data = 'A'*81 for a in xrange(0, 0xfff): _body.write(_data) return _body.getvalue() def drive(func): import time start = time.time() res = func() end = time.time() print func, "took",end-start,"seconds" return res print len(drive(func1)) print len(drive(func2)) From eva_ag at eresmas.com Sun Sep 15 10:35:26 2002 From: eva_ag at eresmas.com (Eva) Date: 15 Sep 2002 07:35:26 -0700 Subject: Good book choice? Message-ID: Hello all! I am new to Python but an experienced programmer in Fortran95 (not too object oriented). I am looking for a suited Python book. I'd like it to have clear ideas about OO, as well as an straight pointing into the core language. It seems that 'Python Essential Reference (2nd Edition)' is a good choice. There is also the book 'Making use of Python' (by Rashi Gupta). Is there any user that bought both? Is it good the treatment of OO in the former? Is there a lack of applications point of view in the former? Could anybody compare them? pros/cons? Thanks in advance, Eva. From marklists at mceahern.com Sun Sep 29 13:52:27 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sun, 29 Sep 2002 12:52:27 -0500 Subject: Python's import: why doesn't it work? In-Reply-To: <3d9739c7$0$19818$91cee783@newsreader01.highway.telekom.at> Message-ID: [Jurie Horneman] > However, I do stand by my criticisms of the Python docs. Feel free to improve them then. I didn't read every word of your post. It seems you're having trouble importing. Do you still need help with that or have you found the help you need? Cheers, // mark From pedro_rodriguez at club-internet.fr Thu Sep 26 12:30:47 2002 From: pedro_rodriguez at club-internet.fr (Pedro RODRIGUEZ) Date: Thu, 26 Sep 2002 18:30:47 +0200 Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <%8ci9.138477$5r1.5541622@bin5.nnrp.aus1.giganews.com> <3D911FE1.1050801@something.invalid> Message-ID: On Wed, 25 Sep 2002 04:30:57 +0200, Greg Ewing wrote: > thp at cs.ucr.edu wrote: > >> But why use grotesque hacks in the first place? "a ? b : c" is a >> well-established syntax for conditional expressions. Why doesn't >> Python simply adopt it? > > > I believe because Guido (a) thinks it's ugly and (b) doesn't think it > would add enough to the language to be worth including. > > Personally, I rather like > > a if b else c > > but Guido doesn't like that either, unfortunately. > > Perhaps I'll slip it into Pyrex when no-one's looking...:-) Ada has two short-circuits operators : "and then" and "or else" that do the trick : if A and then B then ... end if; Looks cleaner to me. Pedro From martin at v.loewis.de Mon Sep 16 01:37:23 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Sep 2002 07:37:23 +0200 Subject: Pickling slotted instances References: Message-ID: Andrew McNamara writes: > I'm really just wondering what makes the solution space large: my > superficial understanding suggests all the necessary information is > readily available for serialising the object's state (but I can see > metaclasses make it complex). I don't know what issues Guido had in mind, but here are a few for consideration: 1. How to determine all slots? It has been proposed that __slots__ should return a tuple that includes base slots as well; alternatively, iterate over base types yourself. Alternatively, return slots in __dict__. 2. Should all slots be pickled unconditionally? You seem to expect this, but Samuele Pedroni points out that, in Java, some slots can be marked transient, to avoid pickling them. 3. How to pickle slots? You are suggesting that the list of slot names is included, but that appears to be redundant - if you know the type, you also know what slots it has. 4. How to pickle unset slots? If a type has a slot but the instance has not assigned the slot, requesting the slot value raises an AttributeError. If you are in doubt that this is really as tricky as presented, I'd encourage you to come up with a patch. In the process of implementing the patch, you may either find that all issues have a straight-forward solution, or that there are really serious issues remaining. Regards, Martin From mjais at web.de Wed Sep 4 05:36:10 2002 From: mjais at web.de (Markus Jais) Date: Wed, 04 Sep 2002 11:36:10 +0200 Subject: Why Python? References: Message-ID: Benjamin wrote: > Hi guys (and girls) > I just begun to learn how to program. And I choosed Python for > doing that. surfing around the web i found an article about this > language, they said it's the ideal language for beginners to the > world of programming. and i admit it, the syntax is very clear making > the code very readable, i learn easily the concepts of programming > and i soon wrote some nice programs. but since i finished my > newbie-tutorial, i am wondering about one question: is it worth to go > deeper into python? i talked to a friend of mine, he told me that i > should try php.. > what should i do?? ^_^ in other words: what is python good for? > why should i continue with python? > thank you! > > _____________________________________________________ > I'm going to prove the impossible really exists hi one reason is that with every programming language you can learn new concepts. when I started with perl I learned a lot about string processing and regular expressions and this knowledge is also useful with python with java I learned object oriented programming and the concepts are also useful for python with Ruby (my favourite, http://www.rubycentral.com) I learned more about OOP and other cool stuff with python (and ruby) I learned to appreciate clean syntax and how to use OOP with a very dynamic language. what I want to say: you should always learn several languages. every one has its advantages and if you know more you can decide which is best for you problems. for example I try to use Ruby most of the time but when there are good modules in python or perl for my problem but ruby has no such module I swith to python or perl the pragmatic programmers (http://www.pragmaticprogrammer.com - very good, you should visit it) recommend to learn at least one new language every year. so maybe you should learn both PHP and Python (and Ruby, of course :-) ) markus From imbosol at vt.edu Tue Sep 10 17:57:17 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 10 Sep 2002 17:57:17 -0400 Subject: Larry Wall's comment on python... References: Message-ID: Brian Slesinsky wrote: > I've long thought that Python would be improved by an optional "end" > statement. Python already has that. It's called a comment. -- CARL BANKS http://www.aerojockey.com From cmay4 at yahoo.com Tue Sep 24 14:29:00 2002 From: cmay4 at yahoo.com (Chuck May) Date: Tue, 24 Sep 2002 18:29:00 GMT Subject: Limit number of concurrent threads Message-ID: I am writing a database utility that needs to run a particular process on every table in the database. Currently, it is something like this: def do_table(table): # handle table operations here for table in all_tables: do_table(table) # summarize results Since some tables take much longer than others, and since the table are not in contention with each other, I'd like to thread the operation. What I would ideally like is to have a set number of threads, say 10, running at the same time (my database has a concurrent connection limit). Since there are about 80 tables, once there are 10 threads running I'd like to add another one as soon as one finishes. Then I need to wait at the end until all the threads finish, so that I can summarize results. One other nice feature would be to exit the application if any thread fails. I've searching for examples that fit my problem, and I haven't found any. Most examples I've found look something like this: threads = [] for i in range(number_of_tasks): thread.append(thread_for_task) # let the threads run - just wait for shutdown for t in threads: t.join() which whould work fine if I wanted to start all 80 threads at once. I've read about the Queue, but I'm not sure if it's what I want, and I can't seem to find any good examples on it. Any help would be appreciated. Thanks. -- Chuck May IMS, Inc. From jepler at unpythonic.net Tue Sep 17 16:59:40 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 17 Sep 2002 15:59:40 -0500 Subject: subclassing tuple In-Reply-To: References: Message-ID: <20020917205939.GE18327@unpythonic.net> On Tue, Sep 17, 2002 at 08:05:02PM +0000, Douglas Zongker wrote: > Is there any way to create a subclass of 'tuple' that has a customized > constructor? I tried doing the obvious thing, but it doesn't work -- > it seems the tuple initializer gets called *before* the one for my > subclass. This: You must override __new__. See the "docs". http://www.python.org/2.2/descrintro.html Jeff From akakakhel at attbi.com Sat Sep 14 18:52:11 2002 From: akakakhel at attbi.com (Ali K) Date: Sat, 14 Sep 2002 22:52:11 GMT Subject: IDLE References: <3D7D4F84.318CDB0F@bellatlantic.net> Message-ID: Hardware: 386 enhanced, 75MHz, 32MB RAM. OS: Win98 Copied files from other computer to mine. It doesn't open when I click on ide.pyw or when I choose to edit a py file with it. From zoltan at trados.com Tue Sep 17 05:00:49 2002 From: zoltan at trados.com (Zoltan Sekeres) Date: Tue, 17 Sep 2002 11:00:49 +0200 Subject: More on Protecting Source Code References: Message-ID: <3D86EF41.5090808@trados.com> David LeBlanc wrote: > Well, I think of it this way: machine coded binaries are more like a 128 bit > key and Python is more like a 40 bit key. I agree that nothing is safe from > reverse engineering; it's a matter of how much pain and money it takes to > unscrut the inscrutable. Python could do better - how I'm not totally sure. Why should do Python better wrt obscurity ? I don't think that's the intention behind the language. As always: Use the right tool. (Probably INTERCAL http://www.ugcs.caltech.edu/~jlm/intercal.html is the right one for you :-) If you develop an app you have the copyright. If somebody uses it without your approval the law is on your side. But using obscurity to me always looks like starting a race which you cannot win. If you need a headstart use dongles and something heavily compiled. The last time I looked SAP R/3 came with the ABAP source code for the business logic. And haven't heard that SAP has much of a problem with piracy. -- Zoltan From ponderor at lycos.com Tue Sep 24 12:22:55 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: Tue, 24 Sep 2002 16:22:55 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 24) Message-ID: QOTW: "When something "is *EVERYWHERE*", how can it be "clearly VISIBLE" at the same time?" - Alex Martelli http://mail.python.org/pipermail/python-list/2002-September/123526.html "... [A]necdotally speaking I find Python development goes faster more as a result of its very high readability than as a result of low loc/FP." Peter Hansen Threads Another good summary regarding a Python to C++ conversion http://mail.python.org/pipermail/python-list/2002-September/121194.html Insight into the Python shipped with Mac OS X 10.2 (Jaguar) http://mail.python.org/pipermail/python-list/2002-September/122912.html Rob Andrews requests ideas for Python advantages on Linux, with many resources in response http://groups.google.com/groups?selm=cBci9.43632%24U7.15670948%40twister.socal.rr.com Where's shared memory functionality in the standard python distribution? http://mail.python.org/pipermail/python-list/2002-September/123431.html Classifying Python's typing evokes question and discussion of terms http://mail.python.org/pipermail/python-list/2002-September/123509.html Serial port programming tips, including: get a breakout box http://mail.python.org/pipermail/python-list/2002-September/123523.html Mathematical perspecives on Programming, ended in the reality of references http://mail.python.org/pipermail/python-list/2002-September/123526.html Getting started with Internationalization / il8n of a wxWindows app http://mail.python.org/pipermail/python-list/2002-September/123656.html Reviews and perspective on core programming language books http://mail.python.org/pipermail/python-list/2002-September/123676.html Is Python 2.2.1 compatible with Tcl/Tk 8.4? Yes, but you must recompile Python. http://mail.python.org/pipermail/python-list/2002-September/123770.html Discussion regarding Python as a compiled language http://mail.python.org/pipermail/python-list/2002-September/123776.html Mark Hammond details the steps for MS Outlook plug-in, finishing with the Python connection http://mail.python.org/pipermail/python-list/2002-September/124112.html Misc. New Python-XML column by Uche Ogbuji at xml.com. First article: http://www.xml.com/pub/a/2002/09/18/py.html O'Reilly offers Python Success Stories http://mail.python.org/pipermail/python-announce-list/2002-September/001694.html Lightweight Languages Worshop 2002 (LL2) Saturday, November 9, 2002 - Cambridge, MA, USA http://ll2.ai.mit.edu/ 3-day Python training session with Mark Lutz in Colorado, on October 28-30 http://www.rmi.net/~lutz/oct02-longmont-class.html Brett Cannon's Python-dev summary for 2002-09-01 to 2002-09-15 http://mail.python.org/pipermail/python-announce-list/2002-September/001695.html Call for Participation: UK Python Conference 2003, April 2-3 - Oxford. http://mail.python.org/pipermail/python-announce-list/2002-September/001692.html Software eGenix.com's mx Python extension packages mxODBC 2.0.5 and BASE 2.0.4 versions released. http://www.egenix.com CilentForm HTML forms handler 0.0.2a alpha released http://mail.python.org/pipermail/python-announce-list/2002-September/001705.html PyReverse 0.4 reverse code generator (plus) released including bug fixes, pyvcg support and improved documentation http://mail.python.org/pipermail/python-announce-list/2002-September/001702.html RuneBlade 0.3.2 release includes updates for wxPython 2.3.3.1 and 2.3.2.1, aspect oriented support code, and optimizations and bug fixes http://mail.python.org/pipermail/python-announce-list/2002-September/001701.html wxPython 2.3.3.1 released - Unicode and many other improvements for this wxWindows wrapper http://mail.python.org/pipermail/python-announce-list/2002-September/001700.html Gordon McMillan releases version 5b4 of Installer http://mail.python.org/pipermail/python-announce-list/2002-September/001699.html The bugfix-release, 0.5.1, of pyOpenSSL is out, and introduces basic PKCS12 support http://mail.python.org/pipermail/python-announce-list/2002-September/001693.html Version 0.8.1 of the Python/XML distribution is now available, and should be considered a beta release http://mail.python.org/pipermail/python-announce-list/2002-September/001691.html DocUtil's gets a DocFactory: a wxPython based "kind of integrated publishing environment for documentation" http://mail.python.org/pipermail/python-announce-list/2002-September/001690.html pyblosxom is a weblogging tool written in Python and modelled after blosxom. http://mail.python.org/pipermail/python-announce-list/2002-September/001689.html FontTools/TTX 2.0 beta 1, an Open Source Python library and toolkit to manipulate fonts. http://mail.python.org/pipermail/python-announce-list/2002-September/001688.html ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of summarizing action on the python-dev mailing list once every other week. http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From h_schneider at marketmix.com Sun Sep 29 08:20:50 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Sun, 29 Sep 2002 14:20:50 +0200 Subject: SOLVED: _winreg.DeleteValue - Permission denied ... References: Message-ID: Thanks a lot Dave! It was right before my eyes ... Bye, Harald > Perhaps you need to open the registry key with write permissions, e.g.: > > key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \ > 'SOFTWARE\\TEST\\SUBTEST', \ > 0, _winreg.KEY_ALL_ACCESS) > > (Also note that you should use double backslashes in your strings or use > raw strings) > > HTH, > Dave > > From henrik.motakef at web.de Thu Sep 26 16:59:19 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 26 Sep 2002 22:59:19 +0200 Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> <20020926164641.1753ebbb.ckasso@sprynet.com> Message-ID: <873crwfowo.fsf@pokey.henrik-motakef.de> Chris Kassopulo writes: > How about: > > _ = "un" > __ = "dun" "dun-init-dun"? Sounds too much like "done" for me... :-) From quiteblack at yahoo.com Tue Sep 24 03:52:33 2002 From: quiteblack at yahoo.com (black) Date: Tue, 24 Sep 2002 00:52:33 -0700 (PDT) Subject: how to build up a guest book with python ? Message-ID: <20020924075233.91441.qmail@web21306.mail.yahoo.com> Hi,all~ I'm learning python for almost 1 month and decide to build up a guest book with it, but I really know nothing about web programming, any tutorials for me please ? --------------------------------- Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! -------------- next part -------------- An HTML attachment was scrubbed... URL: From bobx at linuxmail.org Wed Sep 11 22:17:40 2002 From: bobx at linuxmail.org (Bob X) Date: Thu, 12 Sep 2002 02:17:40 GMT Subject: [FEEDBACK] Is this script efficient...is there a better way? References: <4ZRf9.1782$Lg2.248733@news2.news.adelphia.net> <3hSf9.168947$l_4.98525@atlpnn01.usenetserver.com> Message-ID: <8PSf9.1796$Lg2.257378@news2.news.adelphia.net> Steve Holden wrote: > "Bob X" wrote in message > news:4ZRf9.1782$Lg2.248733 at news2.news.adelphia.net... > [ ... ] > >>Thank you very much...as a follow up: >> >>#1 Can I use the same sys.exit("message here") on the IO errors as well? > > > Sure. I assumed you would generalize the first example to the rest ... > > >>#2 For the "print looks like a debugging statement"...how would it be >>done different...in the context of my script and not a total re-write? > > > I simply thought that since you were writing the output to the outFile > anyway it seems a bit redundant to be printing it. Plus the readlines() > includes the line ending, so you'd get double-spaced output fom the print > statements anyway. > > >>#3 I will test your shorter one as I have stayed away from RE till now. > > > Well, obviously there may be problems if the keywords contains any > characters special to regular expressions. Nut my example whould wqork for > testing purposes. > > >>#4 On your shorter one should xreadlines still be done for memory sake? > > > Yes. This is a general improvement. > > regards > ----------------------------------------------------------------------- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/pwp/ > Previous .sig file retired to www.homeforoldsigs.com > ----------------------------------------------------------------------- > > > Thank you very much...your shorter script did work. The keywords are all "normal" english words that would not have any special characters. I only added a re.IGNORECASE (since case doesn't matter to me) after a quick search of the python docs. Domo! Bob From Omri at atavox.spam Tue Sep 10 04:58:48 2002 From: Omri at atavox.spam (Omri at atavox.spam) Date: Tue, 10 Sep 2002 08:58:48 +0000 (UTC) Subject: Howto debug self? References: Message-ID: Do you mean something like: (Pdb) print self.__dict__ {'a': 5, 'c': 16.6999999999999, 'b': 'good'} ? From member at dbforums.com Mon Sep 16 01:52:34 2002 From: member at dbforums.com (hpyhpy) Date: Mon, 16 Sep 2002 05:52:34 +0000 Subject: A question about C/API of python. Message-ID: <1818979.1032155554@dbforums.com> I use python to load C module(.so),then use C load python,like this: C(main)--->python--->C(.so) But now my trouble is : In C(main), I have some Global variable that depend on process of C(.so). But because python is in middle of them,so I can't use variable of C(.so) in C(main) dexterously. I see some C/API reference but it still pluzzle me.Anybody can tell me some advise? Thanks. -- Posted via http://dbforums.com From paulmg at digitalbrain.com Tue Sep 24 04:52:20 2002 From: paulmg at digitalbrain.com (Paul MG) Date: 24 Sep 2002 01:52:20 -0700 Subject: instance creation Message-ID: <265e380f.0209240052.4c2988f3@posting.google.com> Hi I am dabbling with Python and have run into a bit of an oddness. I have a class Appointment, with fields Title and Details. I want to allow two means of construction: 1) Providing Title and Details strings explicitly, to create a new instance. 2) Providing an ID, which causes that Appointment to be loaded from a backing store. Now in C++ or smalltalk, I would do one of - Provide two constructors: def __init__(self, name, details): self.name = name self.details = details def __init__(self, id): load(id) def load(self, id): i = open("appointment"+str(id)) self = pickle.load(i) - Provide a class method (creation method) to instantiate: def create(id): i = open("appointment"+str(id)) return pickle.load(i) However, much of this seems not to work. - Having two constructors seems to be illegal - or at least the second overwrites the first. - Assigning to 'self' in the load method seems to really not work! - Putting the create() method outside of the class works fine - but I want it to be a class method on Appointment, goddammit!:) Is there no way to do this? Any help would be appreciated, basically i am looking for the python idiom to do this, as my C++ and Smalltalk idiom's clearly aren't in the grain of the language! Thanks very much Paul MG From whisper at oz.net Tue Sep 24 22:45:30 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 24 Sep 2002 19:45:30 -0700 Subject: PythonWin CVS problem Message-ID: Second day it's inaccessable with "permission denied" David LeBlanc Seattle, WA USA From skip at pobox.com Tue Sep 3 10:02:05 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 3 Sep 2002 09:02:05 -0500 Subject: How to avoid freeing memory on exit? In-Reply-To: <31575A892FF6D1118F5800600846864DCBD710@intrepid> References: <31575A892FF6D1118F5800600846864DCBD710@intrepid> Message-ID: <15732.49373.250008.442195@12-248-11-90.client.attbi.com> Roy> Is there any way to get the interpreter to just exit without doing Roy> all that memory cleanup? Gerhard> os._exit Gumuz> so what does 'one' underscore prefixing a methodname mean? Simon> Proceed with caution. In particular, in this case it means that Roy should make sure he *really* doesn't care if __del__ methods associated with those 200,000 objects don't get called. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From Andreas.Leitgeb at siemens.at Thu Sep 19 06:55:44 2002 From: Andreas.Leitgeb at siemens.at (Andreas Leitgeb) Date: Thu, 19 Sep 2002 10:55:44 +0000 (UTC) Subject: lists in dictonaries ? References: Message-ID: Andrew Thompson wrote: > You can put any python objects into a python dictionary, even the > dictionary itself... Oh, can I create a dictionary in Python that contains all those dictionaries that don't contain themselves ... ?-) *scnr*'ly yours. From gvdbogae at vub.ac.be Tue Sep 3 11:41:02 2002 From: gvdbogae at vub.ac.be (Geert-Jan Van den Bogaerde) Date: 03 Sep 2002 17:41:02 +0200 Subject: Design question.... parent/child class In-Reply-To: <3d74b021$0$234$4d4ebb8e@news.nl.uu.net> References: <3d74b021$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: <1031067663.914.137.camel@gandalf> On Tue, 2002-09-03 at 14:56, Gumuz wrote: > hi all, > > i have a SessionManager class, which contains a list of Session > objects(instantiated from a Session class). I have a design problem. > > Each session object has a small 'queue' of messages for the specific > session. How can a session send a message to another session without having > some kind of parent-reference to the SessionManager object? > > i am a bit puzzled, or is this parent-reference not such a bad idea after > all? > There have been other replies which might be more suited to your situation, but if you want a very loose coupling I've found using a signal dispatching system very effective. There is a python implementation here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/87056/ This is similar to Qt's signal/slot system, if you're familiar with that. You have your session objects send a signal whenevever some interesting event happens, and your other objects listening for the signals they're interested in. Best Regards, Geert-Jan Van den Bogaerde From thorsten at thorstenkampe.de Fri Sep 20 03:49:58 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 20 Sep 2002 09:49:58 +0200 Subject: Avoiding referencing (was: Python sequences reference - problem?) References: Message-ID: * Alex Martelli > Just remembed that EVERYTHING works by reference, and what > could possibly be the problem...? The problem is that we newbies sometimes don't want referencing: #v+ def part(seq, indices): """ chop seq by indices """ partition = [] for slice in indices: partition.append(seq[:slice]) del seq[:slice] partition.append(seq) return partition #v- >>> foo = [11, 22, 33, 44, 55, 66, 77] >>> part(foo, [2, 3]) [[11, 22], [33, 44, 55], [66, 77]] # yes >>> foo [66, 77] # aaarrrghhh Obviously I did not pass 'foo' "by value" to function 'part' but by reference and obviously not only local variable 'seq' was modified in the function but "outer" variable 'foo', too. So how to deal with that? 1. "Just don't call function 'part' by with a variable, call it by value - part([11, 22, 33, 44, 55, 66, 77], [2, 3]) - and everything's okay". Obviously no solution to me. 2. "If you don't want referencing, call it with a copy of 'foo' like: part(foo[:], [2, 3])" Yes, but how do I know in advance that 'part' modifies 'foo'? I might not be the author of 'part'. 3. "Rewrite function 'part' so that it works with a tuple as argument. Thereby you're avoiding all possible modifying of existing objects." Yes, but I'm also losing the "extended" possibilities of lists: "list.append", "list.reverse", "list.index" etc. My code will be twice as long as it would be with list methods. Is there a way to "bypass" referencing _without_ disadvantages? I'm sure there is a "canonical" way to do this in Python! Thorsten From danb_83 at yahoo.com Fri Sep 20 15:28:44 2002 From: danb_83 at yahoo.com (Dan Bishop) Date: 20 Sep 2002 12:28:44 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> Message-ID: Magnus Lyck? wrote in message news:<3D8B1537.4010803 at thinkware.se>... > ChrisBarker wrote: > > The only reason I can see > > to not writing your class in Python is performance, and unless you are > > doing a lot of calculations, that is probably a non-issue. > > Performance issues might well matter in large financial > systems, but that's not the only reason. Please name one other real-world situation in which decimal arithmetic is actually *needed*. > [snip] > And if someone would write > > x = Decimal(9.999999999999999) - Decimal(9.9999) > > they would not get what they expected (unless they > expected 0.000099999999998). Ok, they could write But how often does an error of 10 parts per trillion really matter? Afaict, not nearly enough to justify having a default number representation that works against the hardware. > [major snippage] > But perhaps a command line argument or something like > "import exact_arithmetic" could change the behaviour to > using exact instead of floating point arithmetic. I guess > we'd need a module anyway, to specify things. Like: > > >>> import exact_arithmetics as exact > >>> exact.default_rounding(exact.UP) > >>> exact.default_fractions(2) > >>> exact.max_precision = 20 > >>> 7.5/20 > 0.38 > >>> In your proposal, is 1/3 exact? How about sqrt(2)? What's so important about terminating decimal fractions that they should get special treatment? It's true that they're useful for currency calculations, but isn't a Money class enough? From teaandbikkie at aol.com Fri Sep 20 07:16:02 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 20 Sep 2002 11:16:02 GMT Subject: general thoughts References: Message-ID: <20020920071602.29041.00000016@mb-bg.aol.com> >From: Benjamin phncontact.libero.it@ >but now i don't know >what to programm. sounds weird, doesn't it? :) what >should i program?? For a fun programming experience, I suggest a collaboration with other programmers, its more fun than on your own and you learn different things. Open source programming can be very rewarding. You could look on sourceforge for a project to join, or for ideas, and you can limit the selection to those using Python. Kind regards, Misha From jhorneman at pobox.com Sun Sep 29 13:36:39 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: Sun, 29 Sep 2002 19:36:39 +0200 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> Message-ID: <3d9739c7$0$19818$91cee783@newsreader01.highway.telekom.at> "Jurie Horneman" wrote in message news:9ac02e81.0209290839.4f4d6475 at posting.google.com... > rant My thanks to both of the people who have ignored my ranting and tried to help me. I believe I did what you suggested, but it didn't work, hence my frustration. Right after posting my original problem, I completely removed and reinstalled Python. And hey, now it works, with solution 4, ie packages as they are described in the documentation. I don't know what I did to my installation to make it do that, but my problem appears to be solved. For what it's worth - I've already been called on this once in a private email: although my post was meant to illustrate my frustration and criticism of the Python docs, it was also meant to be at least partly self-deprecatory. I should have known better: not because nobody out there gets that, but because text, and especially text sent out to millions of people, just is not a good place for irony - especially when one is asking for help. So if you felt offended: sorry, that wasn't what I intended. However, I do stand by my criticisms of the Python docs. Jurie. From aleax at aleax.it Wed Sep 18 08:45:41 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 12:45:41 GMT Subject: minimizing Tk programs to the taskbar References: <3D8872F1.87850856@optushome.com.au> Message-ID: Richard Tardif wrote: > Is there any way to minimize programs to the taskbar? I'm talking about > windows here. By taskbar I mean the area down in the bottom right > corner, near the clock, that shows icons for what proggies you've got > running. Thanks for any help. I don't think Tkinter offers such an intrinsically non-cross-platform functionality. I suspect therefore that you'd need to work this part through the win32all add-ons, win32gui.Shell_NotifyIcon &tc. Alex From itamar at itamarst.org_NOSPAM Sun Sep 1 17:15:50 2002 From: itamar at itamarst.org_NOSPAM (Itamar Shtull-Trauring) Date: Sun, 01 Sep 2002 17:15:50 -0400 Subject: Twisted docs (was Re: Python IPC options) References: <1030829572.943495@irys.nyx.net> <3D715160.2020109@itamarst.org_NOSPAM> Message-ID: <3D728386.2060908@itamarst.org_NOSPAM> Will Stuyvesant wrote: > Please stop coding and working on functionality until you have good > docs. You have a doc explaining the difference between a framework > and a library, that is good. More of that! About daemons, servers, > internet protocols, tutorials, whatever. We don't have enough documentation, that's true. But see http://www.twistedmatrix.com/documents/dev - I count 14 docs there that have immediately useful info. They cover writing servers, clients, threading, proceses, web developlement, scheduled execution, database integration and more. > Open source is great but weak without good docs. That is very true. I take it you're going to volunteer some time to write docs? We'd really appreciate it! ;) -- Itamar Shtull-Trauring http://itamarst.org/ Available for Python, Twisted, Zope and Java consulting From DeepBleu at DeepBleu.org Fri Sep 20 19:15:49 2002 From: DeepBleu at DeepBleu.org (DeepBleu) Date: Fri, 20 Sep 2002 23:15:49 GMT Subject: How to upload a file using http protocol References: Message-ID: Yes it is. Assume that the user has to enter the file name (with the path) on a form. You use File type form element which allows the user to browse for the file. Using CGI module, and a Submit button (or some javascript with a submit function) this form element has a KEY. The VALUE of this key is the Byte content of the file, NOT the file name. Thus, by using the VALUE KEY, the server is actually receiving the byte content. From there on, the sky is the limit. DeepBleu "A" wrote in message news:mailman.1032552637.6156.python-list at python.org... > Hi, > Does anyone know how to upload a file through HTTP protocol?Is that a possible? > Thank you for help. > ladislav > > > From grante at visi.com Thu Sep 26 17:27:17 2002 From: grante at visi.com (Grant Edwards) Date: Thu, 26 Sep 2002 21:27:17 GMT Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> Message-ID: In article <525eaba.0209260956.72bf6786 at posting.google.com>, Pat Notz wrote: > @ = "at" > ! = "bang" > . = "dot" > * = "star" > > Is there a short (one or two syllable) pronounciation for "__" (double > underscore). "Underscore underscore" and "double underscore" are kind > of long. Somthing like "splat"? Anyone? I've heard "splat" used for both '#' and '*', so I'd cross it off the list... -- Grant Edwards grante Yow! Sign my PETITION. at visi.com From lbrannma at cablespeed.com Sat Sep 28 13:25:46 2002 From: lbrannma at cablespeed.com (Lance) Date: Sat, 28 Sep 2002 10:25:46 -0700 Subject: How to persist IDLE Window state? Message-ID: Hi, I'd like to have the IDLE window state persist across IDLE sessions. Has anyone done this? I'm new to Python and open source. It looks like I might be able to edit one of the idle.py files, rather than changing C code. Any suggestions would be appreciated. Thanks, Lance From gerhard.haering at opus-gmbh.net Wed Sep 4 05:47:02 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 4 Sep 2002 09:47:02 GMT Subject: using python to call java code?? References: <3cc90cd2.0209040122.17242a04@posting.google.com> Message-ID: Tim Schulz wrote: > I am considering to use zope in order to develop an content management > portal. My problem is, that I have to integrate some ready-built java > code. Is there any possibility to call java code from python? Is there > a API for this kind problem? http://jpe.sourceforge.net/ I'm not sure if that's stable yet. I also don't know if I'd bet a project on it, but probably not. At least not without some thorough testing. -- Gerhard From anthony at computronix.com Thu Sep 12 12:06:59 2002 From: anthony at computronix.com (Anthony Tuininga) Date: 12 Sep 2002 10:06:59 -0600 Subject: How to upload files using mod_python? In-Reply-To: <1031845024.2957.154.camel@coraje> References: <1031845024.2957.154.camel@coraje> Message-ID: <1031846819.472.26.camel@chl0151.edmonton.computronix.com> You may wish to report this to the mod_python developers, as __methods__ was removed in Python 2.2, right? On Thu, 2002-09-12 at 09:37, Andres Meza wrote: > Greetings. > > I have created a python CGI script that can upload files sucessfully. > Now, I want to create a mod_python script with the same feature using > the "publisher" handler and I get this error: > > > [Thu Sep 12 08:53:41 2002] [error] PythonHandler mod_python.publisher: > Traceback (most recent call last): > [Thu Sep 12 08:53:41 2002] [error] PythonHandler mod_python.publisher: > File > "/home/mrnet/rpm/tmp/mod_python-root/usr/lib/python2.2/site-packages/mod > _python/apache.py", line 193, in Dispatch > [Thu Sep 12 08:53:41 2002] [error] PythonHandler mod_python.publisher: > File > "/home/mrnet/rpm/tmp/mod_python-root/usr/lib/python2.2/site-packages/mod > _python/publisher.py", line 104, in handler > [Thu Sep 12 08:53:41 2002] [error] PythonHandler mod_python.publisher: > File > "/home/mrnet/rpm/tmp/mod_python-root/usr/lib/python2.2/site-packages/mod > _python/publisher.py", line 308, in __init__ > [Thu Sep 12 08:53:41 2002] [error] PythonHandler mod_python.publisher: > AttributeError: 'file' object has no attribute '__methods__' > > Anyone have an idea about why I get this error? > > Thanks for your time, > > -- > > Andr?s Meza > > Technical Manager > > __Nuevos Medios - NM S.A.____________________ > > e-mail: andres.meza at nuevosmedios.ws > > day time phone: (+572)6827794 ext.102 > > url: www.nuevosmedios.ws -- Anthony Tuininga anthony at computronix.com Computronix Distinctive Software. Real People. Suite 200, 10216 - 124 Street NW Edmonton, AB, Canada T5N 4A3 Phone: (780) 454-3700 Fax: (780) 454-3838 http://www.computronix.com From rsrchstr at msn.com Sun Sep 29 20:38:51 2002 From: rsrchstr at msn.com (mike henley) Date: Mon, 30 Sep 2002 01:38:51 +0100 Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> Message-ID: "TGOS" wrote in message news:pasepuc0r73mh5vlcsu1l7erl4e2b17qvi at 4ax.com... > > > Use an IRC bot on your system, that does the following after each > dial-up: > > - get your new IP address > - make a connection to a specific IRC server > - authenticate you as a specific user > (and obtain possession of a specific nickname if currently taken by > someone else) > - enter a specific channel > - authenticate as channel operator to gain control over the channel > (remove operator status of all useres that are currently operators > of the channel) > - regularly announce your current IP address as HTTP link on the > channel, e.g.: > http://1.2.3.4/ > > Users that know the IRC network and channel can go there and wait in > your channel till you log on (they can tell their IRC client to notify > them if you enter the channel or play a certain sound or perform some > other actions, like executing a specific script on their PC). that's the whole idea of giving a personal webserver "presence", so that others don't have to "go there and wait in my channel till i log on". Also, i want to be able to give a simple AOL or MSN username to anyone without assuming they can write specific scripts. > Once you > log on your IP address will appear in the channel in regular intervals > (e.g. once every 5 minutes or so), as well as it appears every time a > new user is joining the channel as welcome message. Users then just have > to click on it in their IRC client and their default browser will open > and take them to your page. > > You will need to select an IRC network where people can register their > nicknames and a channels, so nobody can prevent your bot from working > correctly by gaining access to your nickname or channel and to make sure > your channel stays alive, even if no user is lurking inside and you are > not online (your bot isn't there either, the channel is empty). > too messy. IRC is a messy medium. > > Problem solved with technology around already since 1988. > yes, this is 2002, almost 2003, it should be possible to do it in a much easier and automated way without all the 1988 mess above, even assuming i can do it, i do not wish to make it as difficult as it sounds above for others. I'll be looking at jabber, xml-rpc, and relevant technologies. if anyone can suggest anything, please let me know. From quiteblack at yahoo.com Tue Sep 3 02:55:06 2002 From: quiteblack at yahoo.com (black) Date: 2 Sep 2002 23:55:06 -0700 Subject: The Module Search Path is ??? Message-ID: <7153651c.0209022255.7fd50ba0@posting.google.com> tutorial told me I could found it in the folder:/usr/local/lib/python. but my OS is windows so folders are different. I searched the folder "lib" but find no file named "python", any ideas ? From kccw at well.ox.ac.uk Fri Sep 13 04:19:20 2002 From: kccw at well.ox.ac.uk (Kenny) Date: Fri, 13 Sep 2002 09:19:20 +0100 Subject: Practical Python Re: [newbie] Buying an introductory/reference text In-Reply-To: References: Message-ID: Hello, Just wondered has anyone taken a look at Magnus Hetland's book Pratical Python. I sort of saw a description while randomly surfing through the book sites. Kenny From leafnode-usenet at schabi.de Thu Sep 19 16:20:35 2002 From: leafnode-usenet at schabi.de (Markus Schaber) Date: Thu, 19 Sep 2002 22:20:35 +0200 Subject: Remarks to Python 2.3 References: <20020918222421.328088eb.use-net@schabi.de> <20020919152834.592eaa39.leafnode-usenet@schabi.de> Message-ID: <20020919222035.185daa67.leafnode-usenet@schabi.de> Hello, loewis at informatik.hu-berlin.de (Martin v. L?wis) schrieb: > There is always the potential danger that a newsgroup message gets > ignored, and the poster gets the impression that nobody cares about > the (potentially significant) problem. I know this and I'm pretty shure I'd take other steps in this case (like PM to some gurus or using the bug tracker). > Of course, bug reports are only the right thing if the poster feels > that Python behaves "bad", where "bad" means either incorrect, > non-intuitive, or in an otherwise undesirable way. For a bug report, > one should also research whether this is a well-known issue. And my original post was my first step in research whether this is a well known issue and whether it is considered "bad" by others. I learned that one of my points was already corrected, and simply is a misdocumentation - so I'll try do submit a documentation correction patch. Gru?, Markus From dwelch at nospam.vcd.hp.com Fri Sep 6 18:38:30 2002 From: dwelch at nospam.vcd.hp.com (djw) Date: Fri, 06 Sep 2002 15:38:30 -0700 Subject: Larry Wall's comment on python... References: Message-ID: <3D792E66.4080304@nospam.vcd.hp.com> [snip] > structures are not completely analogous, they BOTH burden the programmer > with arbitrary rules to govern the physical layout of the code. Although [snip] I completely disagree that Python's rules for code layout are arbitrary. D From marklists at mceahern.com Tue Sep 24 18:22:02 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 24 Sep 2002 17:22:02 -0500 Subject: List/Tuple bug or feature? In-Reply-To: <8765wv6o0d.fsf@nospam.eml.cc> Message-ID: [Mahesh Padmanabhan] > I spent a lot of frustrating hours tracking this down and I am > confused as to why I see this behavior. > > >>> x = ('a' 'b') > >>> x > 'ab' > > >>> x = ['a' 'b'] > >>> x > ['ab'] > > As you might have guessed, I missed a comma between two elements in > a fairly large list. > > If this is a concatenation feature, how can I prevent something like > this happening in the future ? This will sound flippant, but I don't really mean it that way: Put a comma in there next time. You don't really say much about how you generated this large list, but one idea would be to automate the process of generating it and/or fix whatever bug led to the omission of the comma. I don't have anything more clever than that to offer; perhaps someone else does. Cheers, // m From david at no.westcontrol.spam.com Wed Sep 11 06:26:44 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Wed, 11 Sep 2002 12:26:44 +0200 Subject: function pointer References: Message-ID: "Christina" wrote in message news:ffcedbc9.0209110215.644c1788 at posting.google.com... > Hi! > > Does Python have function pointers? If not, is there a possibility to emulate them? > > Christina Functions are first-order objects (is that the right term?) in Python, so you can just assign them to a variable. For example: def foo(x): print x bar = foo bar(10) From irmen at NOSPAMREMOVETHISxs4all.nl Mon Sep 16 15:11:37 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Mon, 16 Sep 2002 21:11:37 +0200 Subject: pyro & parallel processing References: Message-ID: Robin Becker wrote: > The master can presumably pass the new global cutoff to the slaves, but > I'm not sure yet how interruptible I can make them, so I guess my second > question is can we have asynchronous calls into the workers or do I need > to have multiple published classes with a common thread protected state? You almost certainly want to use Pyro's oneway call mechanism. This is very handy to use with callback objects, just read the Pyro manual on this subject. Irmen de Jong From nas at python.ca Sat Sep 7 17:51:20 2002 From: nas at python.ca (Neil Schemenauer) Date: Sat, 7 Sep 2002 14:51:20 -0700 Subject: Daemonize? In-Reply-To: <20020907201022.GA93398@hishome.net> References: <20020907161037.GA70503@hishome.net> <20020907174957.GA25058@glacier.arctrix.com> <20020907201022.GA93398@hishome.net> Message-ID: <20020907215120.GA25431@glacier.arctrix.com> Oren Tirosh wrote: > Any particular reason why you think this is better? One less system call. :-) Neil From jbublitzNO at SPAMnwinternet.com Sun Sep 8 01:02:38 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Sun, 08 Sep 2002 05:02:38 GMT Subject: PyQT picture display References: <3D799F42.2020903@SPAMnwinternet.com> Message-ID: <3D7AD8EF.9050306@SPAMnwinternet.com> Jim wrote: > Jim wrote: >>As far as I can tell, nothing's wrong. It works fine >>for me. Are you sure the jpg files actually exist and >>the path to them is correct? The only thing I changed >>in your program was the filenames for the image files. >>I used PyQt-3.3.2 with Qt 2.3.0 on Linux. >>(another) Jim > The jpg files are in the same directory as the program. I'm using Qt 3.0.5 > with PyQt 3.3.2 on Linux. I'm sure that JPEG support is compiled in the Qt > library as I got this to work using C++. Does JPEG support need to be built > in when compiling PyQt? if so, what must I do to accomplish this? Thanks, As far as I know, PyQt has no options for enabling or disabling jpeg support - the jpeg handling appears to be done at the C++ level, so if Qt has jpeg enabled, that should be sufficient. I also tested your program on a different machine running Qt 3.03 - works fine there also. I have no idea why you're having problems. Some of the things you might try are full explicit paths to the jpg files, different jpg files, make sure the jpg files you're referencing are actually readable. Do you have multiple versions of Qt running? If so, be sure that Qt 3.0.5 libs are being found by PyQt at run time. Run ldconfig just to be sure. Do the PyQt example programs (in PyQt-3.3.2/examples3) work? Delete any older PyQt files and re-run 'make install'. Sorry I can't be of more help. Jim From joconnor at cybermesa.com Wed Sep 4 20:43:06 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Thu, 05 Sep 2002 07:43:06 +0700 Subject: Privacy and Inheritance References: Message-ID: <20020905.074306.188213258.2038@cybermesa.com> In article , "Dennis B." wrote: > Greetings; > > Have enough confidence in Python to realize this is probably just my > misunderstanding, but wondering why Python mangles private, double > underscore attributes with the name of the base class even if they're > inherited and the instance is that of the sub class. > > Like the following doesn't even seem to work: > > class StandardNormal: > > def letEventZScore(self, eventZScore): > self.__eventZScore = float(eventZScore) > > class DerivativeNormal(StandardNormal): > > def getCentral(self): > if self.__eventZScore < 0: > > Unless I change that last line to something like: > > if self._StandardNormal__eventZScore < 0: > > Maybe just missing the point all together, but wondering if anyone'll > point out anything a little more elegant and/or intuitive. > > Thank you and have a great day, Coming from a Smalltalk background, myself, which does not have anything akin to 'protected' and 'private', rather than a C++ background I would say the real solution is "don't bother" :) Code is communication...between you and the machine, but also between you and other developers. Sometimes communicating your intent through convention to other developers is more important than communicating your intent through syntax to the compiler. Idon't really care as much about getting the compiler to *enforce* what I want in ptotected or private access as I do in telling other developers my intention of protectedness. The convention seems to be that a leading underscore (_foo) implies that the variable or function is not meant for public access. You're still free to reference it if you want, but you've been warned that it's not recommended and you are on your own. Like calling sys.exit() vs sys._exit(), both are legal, but you shouldn't use the second flippantly as it has certain ramifications you shold be aware of. This allows developers to communicate their intention of how their code should be used, without mucking up the language syntax and rules with a lot of requirements for how to handle 'protectedness' It's a different philosophy than in C++ or Java, but I think to be effective in Python, it would be good to adopt that philosophy -- Jay O'Connor joconnor at cybermesa.com http://www.r4h.org/r4hsoftware From michaels at one.net Thu Sep 19 08:45:16 2002 From: michaels at one.net (Michael Schneider) Date: Thu, 19 Sep 2002 08:45:16 -0400 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: <3D89C6DC.5050801@one.net> If stackless makes it into the core. Couldn't the "dangerious modules" check if the current program is running in stackless mode. If stackless mode + dangerious module => exception ex: (not the right syntax, just the symantics) #################### start of my dangerNonStacklessModule.py require NoStackless import sys ############################################################# Martin v. Loewis wrote: >Greg Ewing writes: > >>So, the only way to find out whether a particular >>extension is safe to use in Stackless is to try >>it. >> > >That is not true. It is more reliable to inspect the source code. > >In general, it is very easy to do so: if there are no callbacks to >Python, the module is stackless-safe. > >>That's why I say that I would be nervous about >>using Stackless. Not to say that would stop me >>from using it, but I'd feel nervous while I was >>doing it! :-) >> > >That is perfectly fine with me. The question is whether incorporation >of Stackless Python in the core distribution would already make you >nervous. I can see no rational reason for that. > >>Yes, I understand that, and I acknowledge that it >>won't cause any harm to have Stackless in the core >>if the Stackless stuff is switched off by default. >> > >It is better than that: it does not need to be "switched off". Even if >switched on (at build time), it won't start copying slices of the >stack. An application actively has to import one of the modules, and >to call a function in those modules, before you need to get nervous. > >Regards, >Martin > From nospam at bigfoot.com Fri Sep 20 16:39:02 2002 From: nospam at bigfoot.com (Gillou) Date: Fri, 20 Sep 2002 22:39:02 +0200 Subject: urllib2 ? Message-ID: Hi, I'm stuck reading the doc of urllib2. When urllib seemed so easy. Are there examples somewhere ? TIA --Gilles From NineOfSix at gmx.de Mon Sep 2 06:56:08 2002 From: NineOfSix at gmx.de (Axel Grune) Date: Mon, 02 Sep 2002 12:56:08 +0200 Subject: file processing question Message-ID: Hi, Im trying to read the data of a file with following method file = open( inputfile, "r") data = file.read() file.close() but 'data' is always smaller then the file size, e.g. I have a file which is 25677824 bytes but file.read() reads only 4295 (file.tell() = 25677824). Im using python 2.2 under win2k. BTW, file = open( inputfile, "r") lines = file.readlines() data = ''join( lines) file.close() has the same effect. TIA, Axel From see_reply_address at something.invalid Sun Sep 29 20:57:18 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 30 Sep 2002 12:57:18 +1200 Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> <3D911A1B.1000109@something.invalid> Message-ID: <3D97A16E.5060801@something.invalid> Alan Daniels wrote: > Unfortunately, that fails when one person writes their code with tabs > set to 8, and another person reads the code with tabs set to 4. Code > that was hand-aligned with a mix of tabs and spaces doesn't align > anymore. If you're trying to line up things on two lines having different indentation levels, that's true. So you don't do that -- you only try to line things up at the same indentation level. e.g. fooblarg(x, y, z) Note the absence of tabs underneath the "fooblarg(". -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mcfletch at rogers.com Tue Sep 10 10:05:20 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 10 Sep 2002 10:05:20 -0400 Subject: Graph Layout Algorithms References: Message-ID: <3D7DFC20.9010008@rogers.com> Boa Constructor has some code in their UML view that I contributed to do this using topological sorts. The topological sorting algos (one by me, one by Tim) are available seperately here (as toposort.py): http://members.rogers.com/mcfletch/programming/ if you don't want the GPL contamination of using Boa's copy. Basically, you do the topo-sort, then lay out each generation above/below next/previous generations. For really nice-looking graphs, you'd want to do some post-processing to make children show up underneath parents as much as possible (i.e. minimise number of crossing arcs in the graph), and maybe do some work with spacing so that each generation takes up approx. the same amount of space. HTH, Mike Duncan Smith wrote: > Hello, > Just wondering if anyone has implemented anything in Python. I > need to lay out my graphs (directed acyclic / undirected / trees) in a > reasonably clear way. So if anyone has already implemented anything, or if > anyone has advice on appropriate algorithms, I'd be glad to hear about it. > Cheers. > > Duncan > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From erwin at andreasen.com Tue Sep 3 13:12:21 2002 From: erwin at andreasen.com (Erwin S. Andreasen) Date: 03 Sep 2002 19:12:21 +0200 Subject: Better tracebacks for exec and execfile References: <3i99nusjbgpiepva9pkuv3mtl7equ7h88h@4ax.com> Message-ID: <87elcbm1ze.fsf@andreasen.org> Stefan Franke writes: > 1. I'm toying araound with a text templating engine containing > embedded Python scripts. These scripts are run with exec. > If they throw an exception, the traceback looks like > > File "", line 5 > e = a+c+b+ > ^ > SyntaxError: invalid syntax I don't know how to make SyntaxError appear correctly, but for the others you can use compile which lets you pass in a file name. You can then exec the compiled string. compile won't let you specify a start line number: for that I simply added "\n" * start_line to the start of the evaluated string :) -- =============================================================== Herlev, Denmark <*> =============================================================== From gerhard.haering at gmx.de Sat Sep 28 21:15:46 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 29 Sep 2002 01:15:46 GMT Subject: A simpler singleton pattern? References: Message-ID: lee lion wrote in comp.lang.python: > singleton pattern is a way to provide one and only one object of a > particular type. There are many ways to implement a singleton > pattern, is the below one? > class OnlyOne: > instance = None > def __init__(self, arg): > OnlyOne.instance = arg > def __getattr__(self, name): > return getattr(OnlyOne.instance, name) That's another cool way. Did you read about the Borg pattern from Alex Martelli, yet? It works similarly, but without the need to override __getattr__: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 -- Gerhard From F.L.Burton at bio.gla.ac.uk Sun Sep 1 16:39:22 2002 From: F.L.Burton at bio.gla.ac.uk (Francis Burton) Date: Sun, 01 Sep 2002 21:39:22 +0100 Subject: Python IPC options References: <1030829572.943495@irys.nyx.net> Message-ID: <3D727AFA.1FE19151@bio.gla.ac.uk> Armin Steinhoff wrote: > SPREAD -> http://www.python.org/other/spread/ This seems to be very close to what I am looking for. Thanks for the pointer! > Hope this is enough :) More than enough. :-) I'll investigate Spread first, then maybe delve into some of the others. Francis From djc at object-craft.com.au Thu Sep 19 23:46:05 2002 From: djc at object-craft.com.au (Dave Cole) Date: 20 Sep 2002 13:46:05 +1000 Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <23891c90.0209190014.26c5bb9@posting.google.com> Message-ID: >>>>> "Dennis" == Dennis Lee Bieber writes: Dennis> Paul Boddie fed this fish to the penguins on Thursday 19 Dennis> September 2002 01:14 am: >> It could well be that not many people do financial database >> programming in Python, bizarre and unlikely as that may >> seem. Taking a look at pyPgSQL, as the only database module I have >> installed that actually readily documents such things (and that >> should tell you something), it would seem that monetary amounts are >> converted to floating point numbers - surely the first thing one >> would want to avoid in manipulating financial data. Perhaps people >> use integers, or perhaps other modules provide better decimal >> support. Dennis> If I recall from the c.l.ada group, GNAT's "fixed Dennis> point" data type is implemented as scaled integers, so even Dennis> that might not pass the spec for a monetary type. My VB Dennis> references are on loan (or currently stuck in the Windows Dennis> environment and unreadable on Linux) so I can't recall what Dennis> VB6 had for fixed/monetary. Dennis> The only language I've ever encountered that had a Dennis> truely monetary safe fixed point data type is COBOL -- which Dennis> has always used packed BCD formats (though where the sign Dennis> "bit" is stored may vary). COBOL was created from the Dennis> beginning for "business" applications (heck: COmmon Business Dennis> Oriented Language) and was spec'd by a government team. My Dennis> college mainframe required /four/ of the sixteen registers to Dennis> hold /one/ BCD number (32 BCD digits, 2 digits/byte, 16bytes @ Dennis> 4/register). I while ago I worked for a stock broker and developed some Python code for doing financial post trade calculations. I sweated quite a bit about loss of accuracy in stamp duty, GST, and commission calculations until it was pointed out that errors of a few cents here are there are considered normal. For larger amounts of money (100's of 1,000's of dollars) an error of around a dollar would be more or less transparently handled within the various back end systems used between the trading organisations (institutional investors and stock broker). It might be worth talking to the actual users of the software to see what margin of error is considered normal before getting too upset about achieving 100% accurate results. You may be able to get a provably correct answer in your code, but you have no control over the software being used by other people (if there are other people). I found my largest problem was trying to repeat the calculations being performed by a third party system and reproduce the truncation and rounding that was evident in their final numbers. - Dave -- http://www.object-craft.com.au From marklists at mceahern.com Mon Sep 23 22:44:13 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 23 Sep 2002 21:44:13 -0500 Subject: confusion about opening files In-Reply-To: <3d8fcda4$0$198$75868355@news.frii.net> Message-ID: [robie1373] > I am trying to open a file, > > >>> import os > >>> file = os.open("e:\\d12", "r") > Traceback (most recent call last): > File "", line 1, in ? > file = os.open("e:\\d12", "r") > TypeError: an integer is required > > I get this error if the mode is r, r+, a+ or whatever. I also get it > whether the file exists or not. Can someone explain what I am doing wrong? This is a FAQ. You should probably find the Python FAQ and read it. Short story: Don't use 'from x import *' unless you know what you're doing. Cheers, // m - From tmohr at s.netic.de Wed Sep 18 12:39:24 2002 From: tmohr at s.netic.de (Torsten Mohr) Date: Wed, 18 Sep 2002 18:39:24 +0200 Subject: OpenGL Bindings for Tcl/Tk 8.4 References: Message-ID: Hi, i just received a hint by eMail that some more informations would help: OS: Linux, Kernel 2.4.19 Compiler: gcc-2.95.3 Thanks for any hints, Torsten. > Hi, > > i just downloaded and installed Tcl/Tk 8.4 and PyOpenGL-2.0.44. > > Sadly it doesn't compile, though i edited "togl.c", as mentioned > in the #error directive. > > Also the latest CVS snapshot doesn't compile. > > > Has anybody got some patches/hints that will help me compiling > and installing OpenGL bindings for python? > > > Best regards, > Torsten. From gerhard.haering at opus-gmbh.net Mon Sep 16 05:22:31 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 16 Sep 2002 09:22:31 GMT Subject: CPAN for Python References: Message-ID: Bo M. Maryniuck wrote: > Hi. > I "heard" that Python will have something like CPAN for Perl soon. It's probably pythonsiphon that you've heard of. > Is there is something new and moving forward in this area? http://sourceforge.net/mailarchive/forum.php?thread_id=1048175&forum_id=2412 Looks like Suchandra Thapa is still working on it (my patch still hasn't been integrated, however). So the answer is probably that yes, it's moving forward, but slooowly. -- Gerhard From gerhard.haering at opus-gmbh.net Thu Sep 12 07:59:11 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 12 Sep 2002 11:59:11 GMT Subject: Starting external functions in Python applications References: <1d3ffc6b.0209120345.64cf64a1@posting.google.com> Message-ID: Paulus wrote: > How can I link an external dll in a Python programs and (when possible) > start any function from this DLL ? You don't exactly link to a DLL, but the usual answer is that you can use calldll - http://www.nightmare.com/software.html This site has only Python 2.1 binaries - for Python 2.2 binaries, you can install it using the PPM package manager of the ActivePython distribution. -- Gerhard From 2002 at weholt.org Mon Sep 23 07:17:47 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Mon, 23 Sep 2002 11:17:47 GMT Subject: UpToDate SOAP-module ?? References: Message-ID: > My personal recommendation is to ignore SOAP. Eh ... ok. I might be the victim of pure hype but I'm developing a WebService-project, currently supporting XML-RPC only, and I do feel like I have to support SOAP too if I'm to be taken serious. I like the ease of use of XML-RPC and there are lots of services available for it allready, but SOAP seem to be the next, allthough somewhat bloated and complicated, step for Web-Services. Anyway, if you want to provide more information about why I safely can ignore SOAP feel free. It would make my project a bit less complicated so I'd be glad to skip it. :-) Best regards, Thomas From kseehof at neuralintegrator.com Tue Sep 3 17:54:43 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Tue, 3 Sep 2002 14:54:43 -0700 Subject: Converting Python app to C++ completely In-Reply-To: Message-ID: > Hi all, ... snip ... > Now, what I want to do is write the thing in C++. The reason? heh, > because I want to ;) Well, actually I want to learn C++ too, and I would > like to have the performance of a compiled program for larger data sets > (just for fun and comparison more than anything). Hmm. I guess that could be a good reason. In practice, the only real reason to do a complete python to C++ conversion that I have ever seen is to reduce the applications footprint size (i.e. exclude the python libraries). Speed is not a good reason to convert the entire application. You can get all the speed you need by converting individual components to C++ as extensions. I recommend that you learn how to write extensions, or better yet, learn how to use Boost.Python: http://www.boost.org/libs/python/doc/index.html I'd doubt that converting the GUI code from wxPython to wxWindows would make much difference. Has anyone done wxPython vs wxWindows benchmark comparisons? In most cases changes in GUI response time will be irrelivant, except maybe high frequency events such as mouse move handling when you want smoothness. > 1) How easy is it to convert existing Python code to C++? I read that > each line of C++ code is roughly equivilent to 5-8 lines of C++ code, > but is the conversion a simple task or is it troublesome? Actually, you can convert your entire python program into 1 line of C++ code :-) > 2) Are there any pitfalls to beware of - I understand that dealing with > memory and pointers might be a problem, but like I said earlier, I just > don't really know? Yes, I think your biggest issue will be memory management. > 3) Does C++ have equivilent functional constructs like reduce and map? > These helped to make my code much cleaner, tighter and faster, and I > would miss them dearly. Don't bother. Just use for loops in C++. > btw - the code I am writing doesn't rely upon any platform specific > stuff at all and is quite portable in Python - I will be aiming for the > same thing in Python and assume it will be possible. C++ and wxWindows are almost as portable as Python and wxPython. C++ varies a bit: http://fusshuhn.ourfamily.com/cppincomp.html. From mike at bindkey.com Fri Sep 27 15:20:12 2002 From: mike at bindkey.com (Mike Rovner) Date: Fri, 27 Sep 2002 12:20:12 -0700 Subject: [XML-SIG] well-formed xml References: Message-ID: IIRC, double quotes are the must: s = 'search' Cheers, Mike "Juergen Hermann" wrote in message news:E17uppg-0007LF-00 at smtp.web.de... On Thu, 26 Sep 2002 19:08:48 -0500, Mark McEahern wrote: >I'm obviously missing something because this seemingly innocent chunk of >xhtml: > > from xml.dom import minidom > > s = "search" This is not well-formed and thus not XHTML. ... en&q= ... is the correct form. From eworrall at netcomuk.co.uk Sun Sep 29 12:45:47 2002 From: eworrall at netcomuk.co.uk (Eric Worrall) Date: Sun, 29 Sep 2002 17:45:47 +0100 Subject: Linker can't find library (PyProlog setup) References: Message-ID: <3D972E3B.C07047E5@netcomuk.co.uk> Robert Oschler wrote: > > I'm having trouble getting gcc/ld to 'see' the existence of a known shared > library. I quadruple-checked and I do indeed have the files 'libtermcap.so' > and 'libtermcap.a' in my '/usr/lib/termcap' directory. 'gcc' is being > passed the following library directive '-ltermcap'. I tried the following > 'export' commands in my build script (the echoed results do indeed show > /usr/lib/termcap being properly added to the respective environment > variables): > > export LD_LIBRARY_PATH="/usr/lib/termcap:$LD_LIBRARY_PATH" > echo "LD_LIBRARY_PATH=$LD_LIBRARY_PATH" > # run gcc command here > > and I also tried: > > export PATH="/usr/lib/termcap:$PATH" > echo "PATH=$PATH" > # run gcc command here > > and lastly, both: > > export LD_LIBRARY_PATH="/usr/lib/termcap:$LD_LIBRARY_PATH" > export PATH="/usr/lib/termcap:$PATH" > # run gcc command here > > In all three cases I still get a complaint from 'ld', 'cannot > find -ltermcap'. What am I doing wrong? > > thx Include the library path using the -L option: gcc -L/usr/lib/termcap etc Eric Worrall -- You have just received an Etech Solution For all your Linux requirements contact eworrall at netcomuk.co.uk From llothar at web.de Tue Sep 17 11:26:22 2002 From: llothar at web.de (Lothar Scholz) Date: Tue, 17 Sep 2002 17:26:22 +0200 Subject: More on Protecting Source Code References: <3d86b4a0$0$23173$afc38c87@news.optusnet.com.au> Message-ID: On Tue, 17 Sep 2002 14:50:39 +1000, in comp.lang.python you wrote: > >"Security through obscurity is no security against a determined attacker" > >So, someone who is willing to hacka nd hack and hack away at your code, can >get at it, and this is true for things coded in assembler, C, Python or >Befunge. Most people aren't determined attackers, they're simply Joe Average >who needs to get a job done. And some of them must count the time it takes to crack the program vs the money they need to buy it. >Do a very very simple risk analysis. Who is your target audience, what is >the price of your software, will people bother going through your bytecode, >or will they just post the registration key to a website? Will stolen >software lead to a loss in revenue - or will those pirate users be people >who would never have bought it in the first place? (yes, the pirate users >are annoying, and you would feel ripped off, but OTOH you haven't lost >money, and you've gained a bunch of users) Your comment here is language independent.a The main problem comes with stealling the intellectual properties (for the few programs where you can say 'intellectual'). This is the difference between python and compiled languages like Eiffel. I agree that this problem is the main reason for so less commerical python applications. But it could be changed easily if the core python developer would see this problem as relevant as commerical users. But at the moment they don't see the point. Thats the problem. Until this changed i would recommend using Armadillo and embedd your python source code inside a C binary wrapper. Armadillo encrypt/decrypt memory pages that are not in use so its a to hard for 95% of all attackers. From dsavitsk at e-coli.net Wed Sep 18 13:45:13 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Wed, 18 Sep 2002 17:45:13 GMT Subject: COM object registration References: <4J_h9.19439$Ee4.59690@news-server.bigpond.net.au> Message-ID: "Mark Hammond" wrote in message news:4J_h9.19439$Ee4.59690 at news-server.bigpond.net.au... > dsavitsk wrote: > >>>>a = win32com.client.Dispatch('ecp.MODULE_REGISTER2') > >>> > > Traceback (most recent call last): > > File "", line 1, in ? > > File "C:\Python\win32com\client\__init__.py", line 92, in Dispatch > > dispatch, userName = > > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > > File "C:\Python\win32com\client\dynamic.py", line 81, in > > _GetGoodDispatchAndUserName > > return (_GetGoodDispatch(IDispatch, clsctx), userName) > > File "C:\Python\win32com\client\dynamic.py", line 72, in _GetGoodDispatch > > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > > pythoncom.IID_IDispatch) > > com_error: (-2147467259, 'Unspecified error', None, None) > > It is likely that an exception is being encountered that we can get at > pretty easy. > > Add a named param "debug=1" to all UseCommandLine calls. Then, on both > machines, start Pythonwin and select the debug trace collector. Rerun > your tests and see if any additional interesting exceptions are reported. > > Mark. > This is the traceback, but I'm afraid it doesn't mean much to me. It is the error that I got when using a VB client and where I get the 'localserver' notion. in _Invoke_ with 1000 0 2 () in _Invoke_ with 1000 0 1 (u'MODULE_REGISTER2',) Registered: ecp.MODULE_REGISTER2 (for debugging) Object with win32trace dispatcher created (object=None) Traceback (most recent call last): File "C:\Python\win32com\server\dispatcher.py", line 27, in _CreateInstance_ self.policy._CreateInstance_(clsid, reqIID) File "C:\Python\win32com\server\policy.py", line 199, in _CreateInstance_ myob = call_func(classSpec) File "C:\Python\win32com\server\policy.py", line 634, in call_func return apply(resolve_func(spec), args) File "C:\Python\win32com\server\policy.py", line 624, in resolve_func return getattr(module, fname) AttributeError: 'localserver' module has no attribute 'regmodule2' -doug From fperez528 at yahoo.com Wed Sep 4 17:38:31 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 04 Sep 2002 15:38:31 -0600 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 4) References: <448A0F008E0AFE11.19B9EF86BEE2B191.107D5020B234F743@lp.airnews.net> Message-ID: Fernando P?rez wrote: > James Kew wrote: > >> I can't persuade Google to find this message-id; any chance of a link? > > google_groups('comp.lang.python anansispaceworks.com')[0] Oops. Make that google_groups('comp.lang.python anansispaceworks.com scientific')[0] Sorry, f. From tdelaney at avaya.com Wed Sep 18 21:12:43 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 19 Sep 2002 11:12:43 +1000 Subject: Python comment stripper Message-ID: > From: Dennis Reinhardt [mailto:DennisR at dair.com] > > At the time extraction is going on, it is impractical for > Python to be doing > the extraction -- there is the Python DLL (v2.0: 653 Kb and > v2.2: 821 Kb) > for starters. I am aiming for a small footprint. The 361 Kb > download has > Python22.dll inside and that DLL is used when the hello > program runs. : Um ... if you are including Python22.dll in the download, surely that is dwarfing your code size? Using your numbers ... > raw Kb compressed Kb > ---------- -------------------- > original 10.44 2.98 > 4 spaces -> 1 space 8.85 2.86 > + strip comments 4.65 1.34 So you would have: 821 -> 365 (I zipped it up ;) Therefore your package sizes would go from 368 KB -> 366 KB. Even assuming you have 100 times as much (compressed) code, and the comment savings are identical: 663 KB -> 499 KB Is the savings worth the hassle? Tim Delaney From gerhard.haering at opus-gmbh.net Tue Sep 3 03:32:06 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 3 Sep 2002 07:32:06 GMT Subject: The Module Search Path is ??? References: <7153651c.0209022255.7fd50ba0@posting.google.com> Message-ID: In article <7153651c.0209022255.7fd50ba0 at posting.google.com>, black wrote: > tutorial told me I could found it in the folder:/usr/local/lib/python. > but my OS is windows so folders are different. Yep. The module search path is dynamically constructed during Python startup, but can be changed even at a later point. It's in sys.path: >>> import sys >>> sys.path ['', 'C:\\Python22\\Lib\\site-packages\\Pythonwin', 'C:\\Python22\\Lib\\site-pac kages\\win32', 'C:\\Python22\\Lib\\site-packages\\win32\\lib', 'C:\\Python22\\Li b\\site-packages', 'C:\\Python22\\DLLs', 'C:\\Python22\\lib', 'C:\\Python22\\lib \\lib-tk', 'C:\\Python22', 'C:\\Python22\\lib\\site-packages\\PIL'] -- Gerhard From phoebe_1 at att.net Tue Sep 24 13:41:21 2002 From: phoebe_1 at att.net (Holden Caulfield) Date: 24 Sep 2002 10:41:21 -0700 Subject: Solaris 64 bit compilation References: Message-ID: martin at v.loewis.de (Martin v. Loewis) wrote in message news:... > phoebe_1 at att.net (Holden Caulfield) writes: > > > > Please try to report failures carefully. It does not say sizeof(LONG), > > > instead, it says SIZEOF_LONG. Which gives rise to the question: What > > > value does SIZEOF_LONG have, in pyconfig.h? > > > > > cc -c -DNDEBUG -g -Xc xarch=v9 -xcode=pic32 -I. -I./Include > > -DHAVE_CONFIG_H -o Modules/p > > ython.o Modules/python.c > > "./Include/pyport.h", line 480: #error: "LONG_BIT definition appears > > wrong for platform (bad gcc/glibc config?)." > > So what value has SIZEOF_LONG in pyconfig.h? > > How did you invoke configure? How did you manage to get -xarch=v9 into > the compiler command line? > > Regards, > Martin My initial post was just a query to find out if python in 64bit mode was available/compiled successfully by anyone. To answer your questions: - pyconfig.h does say 8 as SIZEOF_LONG - I had hacked the Makefile as a initial pass to see where things were and I posted to get an idea about it. Since then, I have hacked the configure.in and added the option --enable-solaris-64bit and regenerated the configure script. Now, good news, it all builds fine. Except I am having a few problems with extension modules these are: - 'curses' modules does not compile. - 'dbm' modules compiles fine but core dumps during test. So, I disabled these modules in 'setup.py' and built it and ran the make test. I had only two failures these are: 1) test test_time failed -- Traceback (most recent call last): File "./Lib/test/test_time.py", line 46, in test_mktime time.mktime, (999999, 999999, 999999, 999999, File "/apps/python/build/Python-2.2.1/Lib/unittest.py", line 279, in failUnlessRaises raise self.failureException, excName AssertionError: OverflowError 2) test_gettext test test_gettext crashed -- exceptions.OSError: [Errno 20] Not a directory: 'xx/LC_MESSAGES/gettext.mo' I could probably live without them for now. Are there any plans to support 64-bit python executable/module on solaris platforms for future versions? Is anyone even interested in the configure.in patches? Thanks From sismex01 at hebmex.com Thu Sep 26 10:01:00 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 26 Sep 2002 09:01:00 -0500 Subject: Larry Wall's comment on python... Message-ID: > > sismex01 at hebmex.com wrote: > > >>Ironically, Guido originally ruled (in the style guide, IIRC) > >>that thou shalt use tabs and tabs are 8 spaces, "as god > >>intentended them to be." > > > >Yeesh! Why in God's name would he say such a dumb thing? > >I mean, even ancient mechanical typewriters have movable > >tab settings. Rigid, 8-char tabs is just so... neolithical. > > > > Once upon a time, a large class of computers, and their attendant > peripherals, OSs and utility programs universally implemented tabs > hard-wired at 8 stops. In some circles this heritage extended > back 30 or 40 years. Unix originally followed this convention, > as did IIRC all Dec computers and that of most other "minicomputer" > vendors. > Ed and the original VI editors only had fixed tab stops consistent > with terminal drivers and all the unit record equipment at the time. > IIRC, even Emacs originally only had tab stops at every 8 columns. > The original PC also followed this convention, though not all > applications did. I don't know for sure but I bet $1 that Linux > tty drivers today also are hard wired at 8 char tab stops. > Thanks for a beautiful reply. Well, I might not be an old fart :-), but I *was* kinda present at that time, I started work in highschool hacking on CP/M machines, writing drivers for diverse printers and terminals for some apps (ahh, customizable terminal control... we lost that during the PC era, everybody wanted CGA, MDA or Hercules). AND, I distinctly remember that most printers could customize their tab stops via escape codes, same as some (not all) terminals; I worked a lot on some Xoroc terminals, and lots on a Northstar Advantage (ahh, beautiful hardware... *snif*) and they also had customizable tabstops. Hmmm... maybe, what I'm getting at is, why did terminal-designers everywhere toss out years of research in typewriter technology (at the time) and ignore customizable tab-stops? It's simply not sane, I think. > Now, if you've ever worked in an environment where EVERYBODY uses the > same tab stops then you'd probably agree that tabs are vastly > superior to spaces. I don't think there's any question. I presume > it's from this perspective that the right honorable BDFL issued his > original proclamation, which is actually quite reasonable, especially > from my old fart's perspective. Sounds quite likely. > > In fact, problems only arise when alternative, competing tab stop > conventions try to coexist, which I agree is not generally solvable. > Closest solution I've seen is some sites where everybody uses Emacs > and employ coding conventions so that on startup Emacs can read a > specially coded comment and automatically switch to the proper indent > for that file. This can sort of work but your printer and other > rendering utilities also all have to recognize the codes. Spaces > are a more practical solution. Indeed. I *do* recognize that using actual tabs is a much better solution, but having hard-stops each 8 chars is a show-stopper, so if my editor can't customize it's tab width, or customize it's stops (say, when in asm, on columns 12, 18 and 32) then I'm never going to use it willingly (you *could* whip me into submission, but I'll curse your name for the rest of my natural life ;-) > I myself still prefer tabs as I find "indenting" and "out denting" > sections of code to be a common operation (in Python and in other > languages). Inserting or removing an "if" or changing inline code > to a function makes indenting and out denting a common operation. > In the environments I use, this works well with tabs and not so well > or at all with spaces. By default, I still prefer 8 char stops but > I also find I can live just fine with 4. But I can't stand it without > tabs. I'll convert to spaces if I need to when delivering code but I > can't work on it that way. That's what I mean. An editor should be smart enough to handle tab stops at arbitrary columns, and when using tabbed text, jump between those columns. Best of both worlds. Problems arise when mixing tabs and spaces, because you can't ask a program to read your mind; so, is move-left a "jump to previous indent level" or a "move to left character position"? That's the users's responsability to define, but with flexible tab stops, or tab positions, it becomes much easier. > > Anyway, what's wrong with the "neolithical" 8 char stops? > I find them hmmm... philosophically [sp] "wrong", because computers, being programmable and customizable ("terminals" being specialized computers) and so, should _at_least_ do what their mechanical counterparts are able to do, and then some. Would an electronic calculator survive, if it couldn't do the same operations as a mechanical adding machine? > For several decades, all the C code ever written was tab indented > at 8 columns, along with most of the text and other programming > languages on Unix. Yup, I did the same also, but maybe it was because there was no alternative? > Some people complained that in practice 8 char tabs forced them > to indent too much and their programs got squashed off the right > edge of the page. I have little sympathy for that argument, as > I feel if your program is properly modularized then this should > not be much of a problem as individual modules should not have > to be indented all that much. Same here, I find that kind of argument a falacy: "my program is badly modularized and I can't read it clearly, it's the editor's fault". Nope, sorry. > Also, I suspect part of the pressure came from Pascal users, > where some coding conventions require indenting two levels, > once for the begin/end pairs and again a second time for the > code contained between them. What a crock. If it was corporate standard, it sux. But, as for personal taste, I never could decide which looks better, either: if something > another begin blah blah end; --- or --- if something > another begin blah blah end; --- or --- if something > another begin blah blah end; I'm still somewhat ambiguous over which is more readable, maybe it depends on the context, the surrounding code, the tab width, the amount of spaces one uses for the begin/end indent and the actual code indent, I don't know and I don't really care to do reasearch about it. > > For what it's worth, Python's C implementation today appears > to be tab indented to 8 columns, at least all the parts I've > looked at. The main interpreter loop is a good example of a > "complex" piece of code. The innermost loop includes a single > switch statement that's over 1400 lines long! Surrounding logic > require that the switch statement and case labels start 2 tab > stops in and thus the body of each case starts 3 stops in or in > column 24. Yikes, that's like 1/3 of the total. And yet > none of the case bodies extend past column 73 or so. Turns > out that in practice most code lines are pretty short. The ones > that aren't typically are function calls with multiple arguments, > and these may easily be split onto multiple lines (often thereby > increasing readability). Since Guido personally wrote the bulk > of this system as a labor of love, I surmise that he's still pretty > sentimental about the old ways. I suppose you're right. It's not the same to write something for love of the work, as when it's for just work. > > Regards > > --jb > > > -- > James J. Besemer 503-280-0838 voice > 2727 NE Skidmore St. 503-280-0375 fax > Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com > http://cascade-sys.com > It's been nice tossing ideas around :-) -gustavo Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From b.maryniuk at forbis.lt Fri Sep 6 11:57:04 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Fri, 6 Sep 2002 17:57:04 +0200 Subject: ttySx In-Reply-To: <20020906152418.GA6937@sferacarta.com> References: <200209061708.25677.b.maryniuk@forbis.lt> <20020906152418.GA6937@sferacarta.com> Message-ID: <200209061757.04427.b.maryniuk@forbis.lt> On Friday 06 September 2002 17:24, Marco Mariani wrote: > Here it is. > Of course, the code is old and sucks. Yes, it sucks. Because it is GSM modem, and not Hayes compatible (I forgot this note post here). Anyway, thank you much and I already had solved this problem in other Python way. :) -- Regards, Bogdan If you are good, you will be assigned all the work. If you are real good, you will get out of it. From gregory.p.green at boeing.com Wed Sep 4 13:05:14 2002 From: gregory.p.green at boeing.com (Greg Green) Date: Wed, 4 Sep 2002 17:05:14 GMT Subject: Daemonize? References: Message-ID: <1y89n0s5.fsf@boeing.com> sismex01 at hebmex.com writes: > Sorry to ask here, but I don't have any "unixy" python > documentation at hand. > > Normally, I put an app into "daemon" mode, by first > forking, then reopening stdin/out/err to /dev/null, > and then forking again. Works good enough for my > purposes. > > But, am I right? Is this the correct way to do this? > Also, I can't find any "reopen" in python to apply > to sys.stdin/out/err. > > Any help will be most appreciated. > > Thanks. > > -gus The best place to look for this is either Stevens book "Advanced unix programming" or the unix programming faq online: http://www.erlenstar.demon.co.uk/unix/faq_toc.html see section 1.7 -- Greg Green From marklists at mceahern.com Fri Sep 20 10:15:55 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 20 Sep 2002 09:15:55 -0500 Subject: isFloat: Without Exception-Handling In-Reply-To: <3D8B23E5.3040005@thinkware.se> Message-ID: [Magnus Lycka] > Something like this perhaps: > > import re > > def isFloat(S): > floatRE = r"^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$" > return re.match(floatRE, str(S)) is not None > > I'm not sure it's faster though. If you were going to run this lots of times, you might want to compile the pattern. Anyway, the exception based code is faster, by my testing (harness at bottom): isFloatExcept 0.220 isFloatRE 0.521 isFloatRECompiled 0.400 Again, I wonder, why avoid the exception test? Cheers, // mark Harness: #!/usr/bin/env python import re from time import clock # Compile up front. floatPattern = re.compile(r"^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$") def isFloatExcept(s): is_float = True try: float(s) except (ValueError, TypeError), e: is_float = False return is_float def isFloatRE(s): floatRE = r"^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$" return re.match(floatRE, str(s)) is not None def isFloatRECompiled(s): return floatPattern.match(str(s)) is not None def time_it(fn, test_data, n): time_in = clock() for x in xrange(n): for (s, expected) in test_data: actual = fn(s) assert actual == expected time_out = clock() return time_out - time_in def show(fn, r): print "%20s %1.3f" % (fn.func_name, r) def test(): test_data = [(1.2, True), (1, True), (-1, True), (1e+10, True), ("1e-10", True), ("banana", False), ("5j", False), (4+0j, False), (isFloatExcept, False), (__import__, False), (clock, False)] n = 1000 results = {} for fn in (isFloatExcept, isFloatRE, isFloatRECompiled): r = time_it(fn, test_data, n) results[fn] = r for fn in results: show(fn, results[fn]) if __name__ == "__main__": test() - From reuben_stump at hotmail.com Tue Sep 10 09:14:56 2002 From: reuben_stump at hotmail.com (Reuben Stump) Date: Tue, 10 Sep 2002 09:14:56 -0400 Subject: UNIX processes References: Message-ID: Try "ps -Alf". Probably more information than you need. Check the man page for more options, including output formating. R. "Bo M. Maryniuck" wrote in message news:mailman.1031654172.15956.python-list at python.org... Hi, all. Somebody know how to list all the processes in RIGHT way on Linux/UNIX? I need to find the zombies, stopped processes etc. -- Regards, Bogdan Linux: The Ultimate NT Service Pack From ponderor at lycos.com Mon Sep 9 00:39:16 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 8 Sep 2002 21:39:16 -0700 Subject: Newby Question: os.rename References: Message-ID: > > > > "Kevin Bass" wrote in message > > news:AcGc9.68214$Xa.3523883 at twister.southeast.rr.com... ... > > > > I have figured it out. Thanks! > > > > > > "CotaBas" wrote in message news:... > > LOL if you wait long enough people solve there own problems.... If you're skimming or Google'ing for a similar problem...you'll find the problem listed 3 times and no answer in the follow-up! From martin at v.loewis.de Wed Sep 4 17:42:55 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Sep 2002 23:42:55 +0200 Subject: str() of a tuple References: Message-ID: Douglas Zongker writes: > Why, oh why does the str() of a container use the repr()s of the > objects inside? This seems to violate what the docs claim str() does > -- "return a nicely printable representation of an object." Would a > sane implementation break something? Yes. If you have [''], then recursively printing this using str would produce '[]', which would be confusing. Regards, Martin From jepler at unpythonic.net Sat Sep 21 23:01:11 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sat, 21 Sep 2002 22:01:11 -0500 Subject: Math optimization In-Reply-To: <3D8D0612.A6CE7011@bellatlantic.net> References: <6T5j9.145247$pX1.5195840@news2.tin.it> <3D8D02A0.FF572334@bellatlantic.net> <3D8D0612.A6CE7011@bellatlantic.net> Message-ID: <20020921220111.A2274@unpythonic.net> ... and your results will change again if you work at function scope, not global scope. Lookups of locals or constants are faster than lookups of globals. I still doubt you'll measure a substantial difference between * and / on ints, though. I am getting 1.94 vs 2.08 seconds on 1,000,000 iterations, which is actually bigger than I expected. Comparing a*b to a*3 (and likewise for division) also surprised me: a*b is faster in function scope (and likewise for division). If you are planning to do a lot of operations of this kind, for instance on long lists, then what you're actually looking for is the "Numeric" extension, which can perform these tasks at C speeds. Jeff r = range(1000000) def f(x): for i in r: res = x * 3 def g(x): for i in r: res = x / 3 def h(x): for i in r: pass def j(x, y): for i in r: res = x * y def k(x, y): for i in r: res = x / y import time for fun in (f, g, h): t0 = time.time() fun(7) t1 = time.time() print fun.__name__, t1-t0 for fun in (j, k): t0 = time.time() fun(7, 3) t1 = time.time() print fun.__name__, t1-t0 From jepler at unpythonic.net Wed Sep 11 11:10:00 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 11 Sep 2002 10:10:00 -0500 Subject: ANN: Thinking in Tkinter In-Reply-To: References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> Message-ID: <20020911150949.GB28720@unpythonic.net> On Wed, Sep 11, 2002 at 07:41:29AM -0700, Stephen Ferg wrote: > So no combination of "bind()" statements (well, no *easily coded* > combination of bind() and callback logic) can emulate this behavior. Sure it is. The code comes to < 50 lines of tcl, surely a similar number in Python. See my other message. Jeff From inyeol_lee at yahoo.com Thu Sep 5 05:04:35 2002 From: inyeol_lee at yahoo.com (Inyeol Lee) Date: 5 Sep 2002 02:04:35 -0700 Subject: How to get function name which raised IOError/OSError? Message-ID: Is there any way to get function name which raised IO/OSError? I want to write an error message formatter like; def print_oserror(): e = sys.exc_info() func = get_func(e) # I don't know how to implement this. print "cannot %s %s: %s." % (func, e[1].filename, e[1].strerror) try: os.mkdir("foo") os.chdir("bar") os.rmdir("baz") except OSError: print_oserror() # print message like 'cannot chdir bar: blabla...' Thanks, Inyeol Lee From pyth at devel.trillke.net Sun Sep 1 19:10:14 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 2 Sep 2002 01:10:14 +0200 Subject: Add methods to a class at runtime? In-Reply-To: <20020901214438.GA4349@lilith.ghaering.test>; from gerhard.haering@gmx.de on Sun, Sep 01, 2002 at 11:44:38PM +0200 References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> <20020901214438.GA4349@lilith.ghaering.test> Message-ID: <20020902011014.H3893@prim.han.de> Gerhard H?ring wrote: > * Robert Oschler [2002-09-01 17:19 -0400]: > > Ok bear with me guys (Gerhard and Peter). I'm not lazy, the reason I > > don't test certain things I should is because Python is capable of > > such amazing introspective dynamism that, having a _very_ long > > experience bank in strongly typed "static" languages like C++ and > > Pascal, I find I don't even consider yet even trying certain > > possibilies that Python is capable of. > > Some interesting tidbits I found while trying out your suggestions, as > > you will see in the two ".py" files that follow, I discovered that to > > create a method you can dynamically add to a class _instance_, you > > need to omit the 'self' parameter in the method declaration. > > Yep, I found that out today too, when I wrote my last reply. Though I've > never used that in real life. > > > [...] I'm running 2.1.1, anybody know if 2.2.2 is going "disable" > > either of these abilities? > > It will be strictly (even binary) compatible with Python 2.2.{0|1}, so > the answer is that these features will stay. Even with future version you should be able to rely on this. Attribute names are first looked up in the instance and if they are bound to a function object you can call it. > >>> class Foo: > ... def action(self): print "foo" > ... > >>> class Bar: > ... def action(self): print "bar" > ... > >>> foo = Foo() > >>> foo.__class__ > > >>> foo.action() > foo > >>> foo.__class__ = Bar > >>> foo.action() > bar > >>> foo.__class__ > > >>> > > AFAIK Guido isn't too fond of this feature. I guess it might go away > some day. With new-style classes (python 2.2) it's already somewhat restricted: >>> class a(object): pass >>> class b(dict): pass >>> a1=a() >>> a1.__class__=b ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in ? TypeError: __class__ assignment: 'b' object layout differs from 'a' >>> regards, holger From eugene at ulka.com Wed Sep 18 10:07:18 2002 From: eugene at ulka.com (Eugene Pervago) Date: 18 Sep 2002 07:07:18 -0700 Subject: Loading modules from several directories References: <33803989.0209172247.2e6afc1f@posting.google.com> Message-ID: tebeka at cs.bgu.ac.il (Miki Tebeka) wrote in message news:<33803989.0209172247.2e6afc1f at posting.google.com>... > Hello Eugene, > Doesn't > > sys.path.append('/somedir/foo') > sys.path.append('/somedir/foo/project_a') > import foostuff > import projectstuff > > works? > > Miki Miki, The problem is with following: >>> sys.path.append('/onedir/foo') (where /onedir/foo/utils.py exists) >>> sys.path.append('/anotherdir/project_a/') (where /aotherdir/project_a/foo/bar.py exists) >>> import foo.utils >>> import foo.projectA.bar ImportError: No module named projectA.bar If I put the project_a path first, it loads its modules but can't import the /onedir/foo modules. It seems package can only be in one place, once Python finds it, it just stops looking elsewhere. Thanks, Eugene Pervago From debl2absolutelynospammy at bellatlantic.net Sun Sep 15 18:43:30 2002 From: debl2absolutelynospammy at bellatlantic.net (David Lees) Date: Sun, 15 Sep 2002 22:43:30 GMT Subject: Good book choice? References: Message-ID: <3D850D21.9E34DDEF@bellatlantic.net> I looked at the Rashi Gupta book, but purchased 'Practical Python' by Magnus Lie Hetland, which I have read about the first 80 pages. I like the book, which is written in a conversational style. There are many clear short examples of each of the language elements. If you have a bookstore you might go browse it and compare the two. David Lees Eva wrote: > > Hello all! > > I am new to Python but an experienced programmer in Fortran95 (not too > object > oriented). I am looking for a suited Python book. I'd like it to have > clear ideas about OO, as well as an straight pointing into the core > language. > > It seems that 'Python Essential Reference (2nd Edition)' is a good > choice. There is also the book 'Making use of Python' (by Rashi > Gupta). Is there any user that bought both? Is it good the treatment > of OO in the former? Is there a lack of applications point of view in > the former? Could anybody compare them? pros/cons? > > Thanks in advance, > Eva. From theller at python.net Fri Sep 20 14:52:10 2002 From: theller at python.net (Thomas Heller) Date: Fri, 20 Sep 2002 20:52:10 +0200 Subject: Destructor never called ??? References: Message-ID: Tim Peters wrote: > If an object is destroyed by GC, and the object has a __del__, the __del__ > is called. > [...] > > What is true is that if an object *in* a trash cycle has a __del__, that > cycle will not be collected, but rather shuffled into gc.garbage for the > programmer to do something sane with it explicitly. There may be any number > of objects with __del__s not in cycles themselves but reachable only from > cycles; they don't inhibit collection, and if collection occurs their > __del__s will be invoked. It's only the cases where Python can't possibly > guess a safe order in which to call destructors where both __del__ and > collection are inhibited. > So what are the recommended practices if my program creates datastructures containing cyclic references? - avoid using __del__ in these objects by cleaning them 'manually'? - only using weak references to break these cycles? - and finally using the debugflags of the gc module to ensure everything is cleaned correctly? Thomas From mcherm at destiny.com Tue Sep 17 09:08:44 2002 From: mcherm at destiny.com (Michael Chermside) Date: Tue, 17 Sep 2002 09:08:44 -0400 Subject: Python.jobmart.com Server Upgrade References: <20020916221626.13483.93466.Mailman@mail.python.org> <1020916154114.212AAC/w.lozinski@maya> Message-ID: lozinski at openstepnews.com wrote: > The python jobmart now allows for full text searches of the embedded resumes. > So hiring managers can find just the right person with whatever specialty skill > is required. For those who, like me, weren't familiar with "the python jobmart", an instant's Googling results in: http://python.jobmart.com/ Hey, perhaps everyone else already knows about this one, but *I* hadn't, and I wish I had since I just finished a job search in which one of the few criteria that I wasn't able to achieve was a job which used Python. -- Michael Chermside From buzzard at urubu.freeserve.co.uk Sat Sep 7 09:44:51 2002 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 7 Sep 2002 14:44:51 +0100 Subject: Smoothing a discrete set of data References: <3csmdso5.fsf@morpheus.demon.co.uk> Message-ID: "Paul Moore" wrote in message news:3csmdso5.fsf at morpheus.demon.co.uk... > This isn't so much a Python question, as an algorithms question. I > couldn't find a newsgroup for discussing algorithms (is there a good > one?) so as I'm implementing the code in Python I thought I'd try here > - I hope that's OK. > > I have a set of data, basically a histogram. The data is pretty > variable, and I'd like to "smooth" it to find trends. Actually, this > comes up a *lot* for me - some examples: sampled IO rates on a machine > - I want to look for trends (is IO higher overnight or during the day, > etc) or fuel consumption for my car (do I use less fuel since I had > the service). > > Normally, what I do with things like this is draw a graph, and try to > spot the trends "by eyeball". But it feels to me like I should be able > to write something which smooths the data out. I just don't see how > :-) > > Take an example - here's a rough ASCII-art diagram > > 9 XX XX > 8 XX XX XX > 7 XX XX XX XX XX > 6 XX XX XX XX XX XX > 5 XX XX XX XX XX XX > 4 XX XX XX XX XX XX > 3 XX XX XX XX XX XX XX XX XX > 2 XX XX XX XX XX XX XX XX XX XX XX XX XX > 1 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX > > This seems to me to have very clear peaks at the left and right, and a > shallow point in the middle. I'd say that you could "smooth" this to > something that averaged 8 for the first 3 bars, then 2 for the next 9, > then 7 for the last 3. But try to make that precise... > You could change the bin sizes, but I'd generally keep them equal. > When I've tried to formalise this, I've always stumbled over the fact > that it's a trade-off exercise (there most be some sort of "tolerance" > parameter in the algorithm) - on the one hand, the original data is > "best" (in the sense that it matches exactly) whereas on the other > hand, a single horizontal line at the average is "best" (fewest number > of steps). > > My instinct is that you're looking for something that balances number > of steps vs difference from the original data. But for the life of me > I can't see how to make this intuition precise. > > Can anyone help me? I can't believe that this problem has never come > up before, but I can't find any literature on it. > > Thanks in advance, > Paul Moore. You could use something like a moving average, but I'm not sure that will help you answer any specific questions. It sounds like you might be interested in comparing means (for fuel consumption), in which case you'd do something like a (paired?) t-test (and you wouldn't generally throw away information by smoothing the data). IO rates and fuel consumption would generally be approached differently because the data generating processes have different characteristics. (I wouldn't try to answer them both using a single method.) This really sounds like a job that needs a statistical approach. Duncan From llothar at web.de Tue Sep 3 09:49:31 2002 From: llothar at web.de (Lothar Scholz) Date: Tue, 03 Sep 2002 15:49:31 +0200 Subject: Python to surpass C performance by 2030 References: Message-ID: On 27 Aug 2002 15:08:49 +0300, Erno Kuusela wrote: >learn python today, and in 28 years you will have a job writing >the speed-critical parts of c programs in python :) Cool, lets go to the next bank and start a python .com company. You can get the CEO of the ysear with this idea. Please tell me when i can buy stock options from your company :-) From erikprice at mac.com Tue Sep 10 17:09:42 2002 From: erikprice at mac.com (Erik Price) Date: Tue, 10 Sep 2002 17:09:42 -0400 Subject: Python iCalendar API? In-Reply-To: Message-ID: On Tuesday, September 10, 2002, at 04:36 PM, A.M. Kuchling wrote: > In article , > Gerhard H?ring wrote: >> Looks like there is: >> http://webcvs.kde.org/cgi-bin/cvsweb.cgi/kdepim/libical/src/python/ > > This seems to be a copy of the libical library; its official home page > is at http://softwarestudio.org/libical/ . Thanks, Gerhard and amk -- I'll have to check it out. New project!!! Erik -- Erik Price (zombies roam) email: erikprice at mac.com jabber: erikprice at jabber.org From bobx at linuxmail.org Wed Sep 11 21:20:00 2002 From: bobx at linuxmail.org (Bob X) Date: Thu, 12 Sep 2002 01:20:00 GMT Subject: [FEEDBACK] Is this script efficient...is there a better way? References: Message-ID: <4ZRf9.1782$Lg2.248733@news2.news.adelphia.net> Steve Holden wrote: >>#!/usr/local/bin/python -w >> >># import the needed libs >>import sys, string >> >># make sure the command line arguments are there >>if len(sys.argv) < 3: >> print "usage: fread.py [log file] [hit file]" >> sys.exit(1) >> > > Unless the return is important, you'll find > > sys.exit("usage: fread.py [log file] [hit file]") > > more convenient. > > >># open the files with some error checking >>try: >> inFile = open(sys.argv[1],"r") >>except IOError: >> print "Cannot open log file!\n" >> sys.exit(1) >> >>try: >> outFile = open(sys.argv[2],"w") >>except IOError: >> print "Cannot open hits file!\n" >> sys.exit(1) >> > > Your error checking is exemplary. Normally I'm happy to have a Python > exception explain the error condition, but of course your explicit messages > are great. > > >># build list of keywords >>kw = [ "some", "words" ] >> >># loop through the list and print the lines to a file >>for line in inFile.readlines(): >> for badword in kw: >> if line.find(badword) > -1: >> result = '%s %s' % (badword, line) >> print result # Print the result >> outFile.write(result) # Write the result >> > > If you only wanted to know the lines that match at least one of the words > you could follow the write() with a "break", since there's no need to > continue the loop then. > > Also, the "print" looks like a debugging statement. > > >># close the files >>inFile.close() >>outFile.close() >> >># let me know when it's done >>print "Finished processing file..." >> > > Highly commendable. Another approach would be to build a regular expression > from the keywords list and search for the r.e. in each line. The following > code is untested... > > kw = ["some", "words"] > kwpat = "|".join(kw) > pat = re.compile(kwpat) > for line in inFile.readlines(): > if pat.search(line): > outFile.write(line) > > for example. > > regards > ----------------------------------------------------------------------- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/pwp/ > Previous .sig file retired to www.homeforoldsigs.com > ----------------------------------------------------------------------- > > > Thank you very much...as a follow up: #1 Can I use the same sys.exit("message here") on the IO errors as well? #2 For the "print looks like a debugging statement"...how would it be done different...in the context of my script and not a total re-write? #3 I will test your shorter one as I have stayed away from RE till now. #4 On your shorter one should xreadlines still be done for memory sake? Thanks! Bob From robin at jessikat.fsnet.co.uk Wed Sep 4 17:17:30 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 4 Sep 2002 22:17:30 +0100 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> <3d765ce6_4@news.bluewin.ch> Message-ID: ..... it, test_pdfbase_ttfonts.py doesn't look as though it's doing anything particularly odd, certainly I see no references to system/spawn in there. -- Robin Becker From melanie at hotmail.com Sun Sep 22 10:17:37 2002 From: melanie at hotmail.com (melanie at hotmail.com) Date: 22 Sep 2002 14:17:37 GMT Subject: School Corporal Punishment Message-ID: --_NextPart_00009291-000018EB-00838C64-53A0 Content-Type: text/plain Content-Transfer-Encoding: 7bit There's a great new forum called "School Corporal Punishment" at http://www.network54.com/Forum/198833 --_NextPart_00009291-000018EB-00838C64-53A0-- From aleax at aleax.it Fri Sep 27 03:47:09 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 27 Sep 2002 07:47:09 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <7nHk9.172208$pX1.6117207@news2.tin.it> Message-ID: <12Uk9.175615$pX1.6212603@news2.tin.it> Pedro RODRIGUEZ wrote: ... >> The tricks deal with ways to work around this problem, by ensuring that >> and's RHO can never be false, e.g. >> zz = (a and [b] or [c])[0] > > If python had short-circuiting operators ('and then', 'or else'), this > will be the ternary operator : > zz = (a and then [b] or else [c])[0] Python does have short-circuiting operators, and they're spelled 'and' and 'or', exactly like I coded in the snippet you quote. > The problem when talking about conditionnal expression should be to know > what really matters in the context : > - the short-circuit evaluation (only (a,b) or (a,c) are evaluated) > - or the ability to pick a value in a list > > The first one isn't possible in a Python expression AFAIK, Of course it is -- you seem to keep ignoring the semantics of Python's "and" and "or" operators, which ARE short-circuiting (and return one of the operands, differently from C/C++'s short-circuiting && and ||, which return 0 or 1 whatever operands they're given). It's just an ugly hack, that's all. Alex From gua81 at XXXyahoo.com Thu Sep 26 04:24:18 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Thu, 26 Sep 2002 18:24:18 +1000 Subject: LInking cgi error Message-ID: This thing worked before.... I dont know why it didn't work now. this code is in the other page with the link: '%s'% (dirname, filename, filename) This code is the one that crash: all_values=cgi.FieldStorage() kkk=all_values["link"].value start_parse(kkk) when I run it, it gives this error: Traceback (most recent call last): File "parser.cgi", line 53, in ? direc=all_values["link"].value File "/usr/local/lib/python2.1/cgi.py", line 550, in __getitem__ raise KeyError, key KeyError: link From ahindra at hotmail.com Sun Sep 15 19:12:41 2002 From: ahindra at hotmail.com (=?ISO-8859-1?Q?Andr=E9s?=) Date: 15 Sep 2002 16:12:41 -0700 Subject: Python "compiler" is too slow for processing large data files??? References: <3d6d097d$0$321$e2e8da3@nntp.cts.com> Message-ID: <5cc917de.0209151512.1a9e4941@posting.google.com> If you don't need the data files to be human readable you could improve speed saving the lists as python objects with pickle, cpickle or marshal modules, then exec would be faster. From lee100 at sport.rr.com Tue Sep 17 20:55:16 2002 From: lee100 at sport.rr.com (Lee Gray) Date: Wed, 18 Sep 2002 00:55:16 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: Phil Thompson wrote: > On Tuesday 17 September 2002 10:05 pm, Lee Gray wrote: >> >> Can someone point me to a good Python GUI app to demonstrate (other >> than IDLE)? > > http://www.abo.fi/~iporres/Projects/fog0000000023.html > > For SQL based applications PyQt contains a set of data aware widgets. PyQt > includes an example SQL browser, query, reporter in 180 lines of Python. > > Phil This looks very interesting! Thanks, Lee From peeryc at hotmail.com Fri Sep 27 15:11:54 2002 From: peeryc at hotmail.com (Christopher Peery) Date: 27 Sep 2002 12:11:54 -0700 Subject: Python Process that can survive References: Message-ID: <571739c3.0209271111.6514c32f@posting.google.com> sismex01 at hebmex.com wrote in message news:... > > From: peeryc at hotmail.com [mailto:peeryc at hotmail.com] > > > > Alright... I love python but I think I may have found a definite > > problem. I can't seem to run a python process, kick it to the > > back-ground, and then kill the terminal that started it. With most > > other things, the python process would keep running in the > > back-ground regardless. For me, the process always dies with the > > terminal. > > > > So my question: is there a way to separate a python script from the > > underlying terminal so that this will not happen. > > > > I'm hoping for some scheme that's supported by the language. I've > > found a few hacks on-line where the python process is daemonized > > but this requires shutting down all the standard io streams. > > There's got to be a better way especially since it can be done in > > Perl very easily with no special tricks. > > > > By the way, I'm doing this on a linux box. > > > > Chris > > > > This same question I asked a few weeks ago, and got a few > answers back from lotsa nice peepl, so I pass this function > on to you for it's safekeeping (tag, your it ;-) > > def Daemonize(): > "Detach the current process from the console." > import os, sys > if os.fork(): os. exit(0) > > # Close connection to current console. > os.close(sys. stdin .fileno()) > os.close(sys. stdout .fileno()) > os.close(sys. stderr .fileno()) > > # Reopen std handles to /dev/null. > dev null = os.open("/dev/null", 0) > os.dup2(dev null, 0) > os.dup2(dev null, 1) > os.dup2(dev null, 2) > > # Create new OS session. > os.setsid() > > # Reset UMASK. > os.umask(0) > > # Refork to have init as parent. > if os.fork(): os. exit(0) > > > This is a synthesis of several replies I received, and it > seems to work, but others might have some observations > to make to this little function. > > HTH! > > -gustavo > > > > > > > > > > > Advertencia: > La informacion contenida en este mensaje es confidencial y restringida > y > esta destinada unicamente para el uso de la persona arriba indicada, > Esta > comunicacion representa la opinion personal del remitente y no refleja > necesariamente la opinion de la Compa ia. Se le notifica que esta > estrictamente prohibida cualquier difusion, distribucion o copia de > este > mensaje. Si ha recibido esta comunicacion o copia de este mensaje por > error, > o si hay problemas en la transmision, favor de comunicarse con el > remitente. > > > Todo el correo electr nico enviado para o desde esta direcci n > ser > procesado por el sistema de correo corporativo de HEB. Tal correo > electr nico esta sujeto a ser almacenado y puede ser revisado por > alguien > ajeno al recipiente autorizado con el prop sito de monitorear que se > cumplan > las normas de seguridad de la empresa. Yeah I found this hack on the web and I can't believe that this is only way to do this in python. You're basically stripping the process of all it's stream and sending it on its way. This is really messy. Plus in my lab there are a bunch of perl guys and a few python people. To date, what one can do in their script the python guys can do to (only nicer and much more readible). Perl has the ability to have a process continue after the underlying terminal is killed if the process is in the background. What is python doing that doesn't allow this? Chris From heikowu at ceosg.de Sat Sep 7 13:14:04 2002 From: heikowu at ceosg.de (Heiko Wundram) Date: 07 Sep 2002 19:14:04 +0200 Subject: Killing/Terminating a running thread Message-ID: <1031418844.17923.94.camel@d168.stw.stud.uni-saarland.de> Hi to all! I've looked over google groups, but I've found no real answer that satisfied the needs I have. Just a little explanation: I have a Queue module, which stores method-calls and delegates them to threads, which take over running the call. Now it happens that a method takes much longer to complete than I would like it to, and in this case, the thread running the code should just be terminated, discarding all values computed so far. The basic problem I have that it is pretty much impossible to get at the PID of the thread running the code in question; but I have a reference to the thread class in a central "garbage-collector" (the queue object). And anyway, this approach would only work on Unix (I guess), when using pthreads, which create a "real" subprocess with its own PID for a thread. Has anyone had a similar problem, and know of a solution? Yours, Heiko Wundram Netzwart Wohnheim-D Zimmer 2206 - Universit?t 18 - 66123 Saarbr?cken -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From magnus at thinkware.se Tue Sep 17 15:03:34 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Tue, 17 Sep 2002 21:03:34 +0200 Subject: Thinking of joining References: <3D7970DC.5115BCC8@earthlink.net> <20020907095211.24938.00000006@mb-mt.aol.com> Message-ID: <3D877C86.4090403@thinkware.se> TeaAndBikkie wrote: > and won't leave > you pining for the fields. Or fjords! From roy at panix.com Mon Sep 16 15:16:16 2002 From: roy at panix.com (Roy Smith) Date: 16 Sep 2002 15:16:16 -0400 Subject: Converting Python app to C++ completely References: <3D85D9EB.9020102@thinkware.se> <3D86209F.4080501@earthlink.nospam> Message-ID: Joe Knapka wrote: > You might try rewriting it in Python, using lists of characters > instead of strings for the stuff that's causing performance > trouble. Given str, lst = list(str), then do all the processing > (in place) on lst, and ''.join(lst) to turn it back into a string. An interesting idea, I'll try it! The only problem is, I really had two reasons for converting it in the first place. One was to improve performance, the other was to learn C++. If I solve the first problem in Python, I won't solve the second problem at all :-( From henrik.motakef at web.de Tue Sep 17 15:24:30 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 17 Sep 2002 21:24:30 +0200 Subject: CGI question References: Message-ID: <873cs8l8r5.fsf@pokey.henrik-motakef.de> "David LeBlanc" writes: >>> When I want to present another >>> page, I want the url to look like this: http://my.domain.name/?page. {...] >>> Now, my problem is to find out what follows behind the question mark in >>> my CGI script. Everything after the question mark will end up in the QUERY_STRING environment variable (as a raw, URL encoded string). > From what I've heard, the difficulties of writing mod_rewrite rules is > enough to make even seasoned apache warriors shudder. Maybe that's the point where one should mention mod_rewrite's documentation: http://httpd.apache.org/docs/mod/mod_rewrite.html There is also a "rewrite guide" with lots of practical examples: http://httpd.apache.org/docs/misc/rewriteguide.html hth Henrik From nhodgson at bigpond.net.au Wed Sep 4 19:19:05 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Wed, 04 Sep 2002 23:19:05 GMT Subject: embeddable ide? References: Message-ID: Stevek wrote: > We're planning on making extensive use of Python to provide our users with a > powerful scripting mechanism. I've successfully embedded and extended > Python but now I want to give the user a decent development environment for > writing their scripts. The approach that is most likely to succeed is to take one of the current IDEs and reshape it to fit into your application. Full IDEs are quite complex beasts and so this will require quite a bit of effort and learning. Open source IDEs like PythonWin or Boa Constructor would be reasonable candidates although the commercial IDE vendors are also likely to be open to approaches. As Gerhard says a major criterion is that you should choose IDE code that uses the same UI toolkit as your application. Creating a Python IDE component would be a very interesting but difficult project. There are Visual Basic IDE components such as http://msdn.microsoft.com/vba/default.asp An important issue in producing an IDE component is in defining a reasonable scope for the component so that it allows a great deal of flexibility but also allows the application to define limitations like source code being stored within the application's database rather than in files. Neil From tjreedy at udel.edu Sat Sep 14 11:58:58 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Sep 2002 15:58:58 GMT Subject: question about dictionary type.. References: Message-ID: <61Jg9.16334$5r1.665293@bin5.nnrp.aus1.giganews.com> > Interesting is the line "start[key] = start = {}", because first > "start[key] = {}" is evaluated, then "start = {}" (with "{}" being the > same object as in the first assignment). You can check this with "dis", as > I've read in another posting in this newsgroup: Since this is documented in Ref Manual 6.3 "An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right." you can count on this behaviour persisting in future versions. TJR From snacht at xs4all.nl Thu Sep 26 05:10:12 2002 From: snacht at xs4all.nl (Stefaan Nachtergaele) Date: Thu, 26 Sep 2002 11:10:12 +0200 Subject: jython web scripting options Message-ID: Hi all, I'm prototyping a three tier web application in java. I've looked at a lot of java web frameworks but for development speed nothing compares to web scripting languages like php, etc. But that's not an option for me cause I need to talk with my server side java code (php-java integration is dinky). My question is, what options are there for jython. I've looked around and I found PSP (http://www.ciobriefings.com/psp/). It actually seems perferct for me. Has anyone had any experience with this? Is it any good? Are there any such other options than this? I notice there's a lot of solutions for Python, but I need the java integration so that does not seem to be an option for me. Advise welcome. Regards, Stefaan Nachtergaele From marklists at mceahern.com Wed Sep 18 07:25:09 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 18 Sep 2002 06:25:09 -0500 Subject: monetary applications [was: Python GUI app to impress the boss?] In-Reply-To: <20020918052920.GA81158@hishome.net> Message-ID: [Oren Tirosh] > I don't understand what exactly you are complaining about but is sounds > interesting - can you elaborate? Perhaps the lack of a FixedPoint type? // m - From mertz at gnosis.cx Mon Sep 16 20:42:17 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 16 Sep 2002 20:42:17 -0400 Subject: [OT?] Source code References: Message-ID: Lulu of the Lotus-Eaters wrote: > I would reformulate the issue slightly: If you BELIEVE your code is > that valuable, seek psychiatric help. BT (or a billion other folks with the same neurosis) retorted: |> I really don't understand posts like these. |> You think I'm fool to protect my work? Cliff Wells wrote previously: |Obscuring the code will dissuade only the most casual or incompetent |from decompiling/disassembling your code. Sort of like hiding a spare |key to your house under the "Welcome" mat. And that would be illegal, |hence the suggestion to *copyright* your work. >From a factual perspective, Cliff is right. Copyright is the means by which source code can be protected (not that I think copyright laws are good ones, but that's how things actually are). Obscurity isn't. But even though my prior remark was mostly meant as a little quip, there was more to it than just that. There is a particular neurosis that goes into the many grammatically flawed, defensive, and self-aggrandizing posts that one sees so frequently on Usenet. The obsession with protecting code that has not yet been written, but whose greatness is nonetheless certain is just one variant--various other "secrets" and "insights" work the same way. I exaggerate by saying "see psychiatric help"--the neurosis is usually not quite as severe as to require that. But at the risk of being too vulgarly Freudian, it seems like an anal retentive obsessive complex that is going on with this phobic fear of parting with something so very precious. Yours, Lulu... P.S. Horkheimer and Adorno say societies can have neuroses too, not just individuals. Just look at the RIAA, DVDCCA, Disney (&the Senator from Disney), MS, and so on. -- mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o gnosis _/_/ Postmodern Enterprises \_\_ .cx _/_/ \_\_ d o _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e From aleax at aleax.it Fri Sep 20 11:05:35 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 15:05:35 GMT Subject: Destructor never called ??? References: <76710511.0209111450.40999dd8@posting.google.com> Message-ID: <3PGi9.119651$ub2.2538597@news1.tin.it> Aahz wrote: > In article , > Alex Martelli wrote: >>Aahz wrote: >>> >>> There are several different issues. First of all, __del__ does not get >>> called if an object is destroyed by GC (GC gets used to clean up cyclic >>> garbage). Secondly, Jython does not use refcounting; it's pure GC, just >> >>Right, but, I'd put it differently: GC is inhibited from destroying >>objects whose types define a __del__ -- rather, it collects them into >>gc.garbage, because it can't know that finalizing them is safe. > > Thanks (and also to Tim) for correcting my sloppy writing. Reading Tim's post reminded me that _my own_ expression was quite imperfect too -- GC doesn't destroy objects *that are part of the loop* and have a __del__... it DOES destroy object that have a __del__ if they're not part of the loop itself, but rather, are kept alive only by being referenced from objects in the loop, if and when the loop itself is collected/destroyed. Phew... Alex From narnett at mccmedia.com Wed Sep 4 12:40:17 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Wed, 4 Sep 2002 09:40:17 -0700 Subject: Bind threads to addresses -- Windows & urllib? Message-ID: I can't see an obvious easy way to bind threads to IP addresses on a Win2K machine. I have a multi-threaded Web spider, which uses urllib to retrieve pages, and would like to bind each thread to a different address on the machine, if possible. Alternatively, I'd be willing to run separate processes to accomplish the same. So far, my searches aren't coming up with any solution... And it would be wonderful if such an approach were also portable to Linux... Pointers? -- Nick Arnett Phone/fax: (408) 904-7198 narnett at mccmedia.com From dsavitsk at e-coli.net Wed Sep 18 22:54:47 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 19 Sep 2002 02:54:47 GMT Subject: Catching results of an exec References: <3d88f701$0$304$39cecf19@nnrp1.twtelecom.net> Message-ID: >>> class foo: ... def do_it(self, arg): ... exec(arg) ... def get_it(self, arg): ... return eval(arg) >>> f = foo() >>> f.do_it('self.a = "bar"') >>> b = f.get_it('self.a') bar is this too simple? -d "Greg Fortune" wrote in message news:3d88f701$0$304$39cecf19 at nnrp1.twtelecom.net... > Is there any way to "catch" the value produced by an exec? I'm considering > things like print statements that don't really assign a value, but do send > a result to stdout. > > For example, if I execute > > exec('print dir()') > > from an interpreter, there will be some stuff spit out on the console. > What if I really wanted to display the list from dir() in a different way? > I'm working on a really dinky server that will sit on a machine and execute > arbitrary python code. I want the results from the code execution to be > returned to client. > > Even just eval('dir()') exhibits the desired behavior, but only from an > interactive interpreter. > > Right now I've got a nasty hack that redirects stdout, uses an > InteractiveInterpereter from the code module to execute the code, writes to > an output file, reads the result from the file, restores stdout and then > sends the result to the client. Hopefully, that's a terrible way to do it. > It just occured to me that I can probably use a pipe in place of the > output file, but still.... > > It would be great if exec and eval set something somewhere that held the > results of the code execution. I looked in the InteractiveInterpreter > (which, at least, kicks the results of the code execution out to stdout), > but all it does is > > exec code in self.locals > > Did I miss something? > > Greg Fortune From klaatu at nospam.invalid Fri Sep 20 14:18:56 2002 From: klaatu at nospam.invalid (Klaatu) Date: Fri, 20 Sep 2002 18:18:56 GMT Subject: win32comext problem w/adsi Message-ID: Python 2.2.1, win32comext (win32all) 148, Windows 2000 SP3 I've installed the Win32 Extensions to Python from http://starship.python.net/crew/skippy/win32/Downloads.html which states that the 148 version is for Python 2.2. I also have Python 2.2.1 from http://www.python.org/2.2.1 I'm just trying to run test.py stored in (on my system) "D:\Python22\Lib \site-packages\win32comext\adsi". Executing python test.py from the command line gives me a dialog stating that "The dynamic link library pythoncom21.dll could not be found in the specified path...", followed by this traceback: Traceback (most recent call last): File "test.py", line 5, in ? from win32com.adsi import * File "D:\Python22\lib\site-packages\win32comext\adsi\__init__.py", line 25, in ? from adsi import * ImportError: DLL load failed: The specified module could not be found. The string "pythoncom21.dll" is only found within one file: adsi.pyd in that same folder. The DLL does not exist on my system. I do have a pythoncom22.dll in my system32 folder. Is this a problem with the Win32 Extensions package that the author of the package will have to fix? Or is there something I can do to fix this problem, given my fairly limited knowledge of Python. Any other suggestions? TIA From rjones at ekit-inc.com Thu Sep 12 17:56:46 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Fri, 13 Sep 2002 07:56:46 +1000 Subject: ANN: NINZ 1.2.1 In-Reply-To: <20020912135926.A7584@ibook.distro.conectiva> References: <20020912135926.A7584@ibook.distro.conectiva> Message-ID: <200209130756.46405.rjones@ekit-inc.com> On Fri, 13 Sep 2002 2:59 am, Gustavo Niemeyer wrote: > NINZ stands for NINZ Is Not ZSI. And ZSI would be? Richard From python at conquered.org Thu Sep 5 09:55:29 2002 From: python at conquered.org (Luis) Date: Thu, 5 Sep 2002 07:55:29 -0600 Subject: Python class ( Prolog ) ??? Message-ID: <001001c254e3$e5fdcc80$6a01a8c0@LUISLAPTOP> Does anyone have a class that provides the functionality of prolog ??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Wed Sep 4 03:14:09 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Sep 2002 07:14:09 GMT Subject: ANN: New PEP Format: reStructuredText References: <0z+c7LA8mHc9EwYa@jessikat.fsnet.co.uk> Message-ID: <5pid9.5884$e5.1033477@newsb.telia.net> Magnus Lie Hetland wrote: > I like plain-text formats, but I reStructuredText is too convoluted > (and has too many strange constructs, like lots of underscores and > double colons etc) for my taste. I'm sure many others (among them, I'm > sure, the designers) will find it to be the perfect balance of > simplicity and functionality. as long as their logos are always exactly 134 pixels wide, of course... From emile at fenx.com Mon Sep 16 19:31:52 2002 From: emile at fenx.com (Emile van Sebille) Date: Mon, 16 Sep 2002 16:31:52 -0700 Subject: Not sure how to phrase this question References: <000501c25dd4$38711460$9865fea9@arthur> Message-ID: Arthur: > Would hate to have to resort to truely understanding > this stuff to get to where I am hoping to get. > It would help to know where that is... ;-) -- Emile van Sebille emile at fenx.com --------- From thorsten at thorstenkampe.de Sat Sep 7 10:46:07 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 7 Sep 2002 16:46:07 +0200 Subject: Larry Wall's comment on python... References: <3D7958DB.50903@nospam.free.fr> Message-ID: * laotseu >Rod Stephenson wrote: >> Slashdot has a list of questions posed to Larry Wall (perl). When >> asked his thoughts on other scripting languages, he makes the >> following observation about python >> >> "Python is cool to look at small bits of, but I think the "outline" >> syntax breaks down with larger chunks of code. I'm with Aristotle on >> the structure of discourse--a story should have a beginning, and >> middle, and an end. So should blocks" >> [...] > > def fun(args): > #BEGIN > if ceci or cela: > #BEGIN > do_this(with_that) > [snip a lot of code] > #END > #END > > So what the problem with blocks ? Nope. Bad, bad readability, sorry. #||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*BEGINS*_! def fun(args): #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*BEGINS*_! if ceci or cela: do_this(with_that) [snip a lot of code] #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*ENDS*_! #||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*ENDS*_! Thorsten From eugene1977 at hotmail.com Fri Sep 13 19:13:23 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Fri, 13 Sep 2002 23:13:23 +0000 Subject: question about dictionary type.. Message-ID: hi.. i'd like to have a dictionary which looks like table = { category1 : { category2 : { category3 : 'garbage value' } } } category1 has many category2 category2 has many category3 i expected table[ 'computer' ][ 'language' ][ 'python' ] = 0 to create {computer : { language : { python :0 }}} table[ 'computer' ][ 'language' ][ 'java' ] = 0 to becomes { 'computer' : { 'language' : { 'python' :0 , 'java' :0 }}} but python doesn't allow me to do this.. can anyone help me? thank you From duncan at NOSPAMrcp.co.uk Wed Sep 4 08:40:21 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 4 Sep 2002 12:40:21 +0000 (UTC) Subject: newsgroup for zope References: Message-ID: stephan wrote in news:al4tru$o3j$03$1 at news.t- online.com: > Hi perhaps a stupid question, > > but does there exist a newsgrup for zope centric items? No newsgroups. Lots of mailing lists though: see the Zope website for details: http://www.zope.org/Resources/MailingLists -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From edream at tds.net Fri Sep 20 11:09:06 2002 From: edream at tds.net (Edward K. Ream) Date: Fri, 20 Sep 2002 15:09:06 GMT Subject: Setting cursor colors in tkinter References: Message-ID: > from Tkinter import * > root = Tk() > root.configure(cursor='xterm red green') > > doesn't produce an error. The colours seem to be taken into account, but > the xterm cursor isn't really a good example. I tried > root.configure(cursor='gumby red green') and the result was what I expected. > > Maybe there are some issues on Windows? Many thanks, Eric, for this information. I am indeed running on XP. Plain "gumby" works on my system, and the color specs do not. I ran the following test from wish: proc createWindowWithCursor {} { toplevel .panel text .panel.text .panel.text configure -cursor {gumby red green} pack .panel.text } This yields: bad cursor spec "gumby red green" -cursor gumby or -cursor {gumby} work as expected, so this looks to me like a Tk problem on Windows XP. Edward From theller at python.net Thu Sep 26 13:01:09 2002 From: theller at python.net (Thomas Heller) Date: Thu, 26 Sep 2002 19:01:09 +0200 Subject: Python threading? References: Message-ID: Tim Peters wrote: > [Robert Oschler] > >>Having written _many_ state machines in my life, which async programming >>boils down to in one form or another, I feel it depends on the task. >>... >>Contrast this with a simple procedure call where a linear series of >>function calls are made, each with appropriate error handling and status >>adjustment, in a pleasant centrally located manner. > > > [Thomas Heller] > >>I wonder if generators can come to a rescue here? > > > Absolutely. Read the start of PEP 255. > > >>Still trying to get them into my head... > > > Think of them as resumable functions. You're familiar with functions that > remember their own data state across calls, via abusing globals, or via > declaring private static vrbls, in C. Methods on objects often do the same > by stuffing their state into instance attributes between calls. A generator > remembers its data state across resumptions simply by virtue of that its > local variables don't vanish, and also remembers its control-flow state > across resumptions. Remembering local data state by magic is a real > convenience, but can be simulated in many other ways with reasonable effort; > it's the ability to remember and restore control-flow state by magic that > can make generators more than merely convenient. I _have_ written kind of hardware descriptions with it - what you do with VHDL testbenches normally. This was fun! There were several generators like this, manipulating clock, reset and other signals in a counter device. The value yield'ed is simply the time to wait: def run_clock(self): while 1: self.clock = not self.clock yield 50 # wait 50 ns def run_reset(self): self.reset = 1 yield 200 # a 200 ns reset pulse self.reset = 0 The dispatcher goes like this: Creates the generators, pushes them onto a priority queue (together with the time value they will have to be served), serves them by calling the next() method, and pushes the result back onto the queue: def run(*gens): queue = MyList() # a priority queue # insert all generators for g in gens: queue.put((0, g())) # and run them while queue: now, gen = queue.pop(0) try: dt = gen.next() except StopIteration: pass else: queue.put((now + dt, gen)) -------- OTOH, I've been missing the possibility to pass values back _to_ the generators - something like maybe 'work = yield event', probably triggered by calling gen.next(work)). Wouldn't this be useful? I fear I cannot explain this clearly, but I think David Mertz statemachine example would also profit from it. As I understand it, he passes this 'work' around in global variables. Thomas From phil at river-bank.demon.co.uk Tue Sep 10 18:04:17 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Tue, 10 Sep 2002 23:04:17 +0100 Subject: ANN: PyQt v3.4 Released Message-ID: <3D7E6C61.7010700@river-bank.demon.co.uk> Riverbank Computing Limited is pleased to announce the release of v3.4 of PyQt at http://www.riverbankcomputing.co.uk/pyqt/. PyQt is the set of Python bindings for Trolltech's GUI (and SQL and XML) toolkit for UNIX/Linux and Windows. It contains 300 classes and over 5,750 functions and methods. It comes with a debugger and a utility for generating Python code from GUIs created with Qt Designer. The main difference in this release is a change in licensing. PyQt is now licensed in a similar way to Qt itself with a GPL version and a commercial version. The GPL version is only available for UNIX/Linux. If you are using the commercial version of Qt then you also need the commercial version of PyQt. If you are using the GPL version of Qt then you can use the GPL version of PyQt. See the website for more details. Also released are updated (and free) binary packages for the non-commercial edition of Qt under Windows and the GPL version for the iPAQ and Zaurus. SIP v3.4 has also been released. SIP is the C++ bindings generator used to create PyQt. Phil From NineOfSix at gmx.de Mon Sep 2 03:37:51 2002 From: NineOfSix at gmx.de (Axel Grune) Date: Mon, 02 Sep 2002 09:37:51 +0200 Subject: ascii value Message-ID: How can I get the ascii value of char which is in a string, e.g. getting the 97 if the char was 'a'. TIA, Axel From phr-n2002b at NOSPAMnightsong.com Fri Sep 20 20:43:09 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Sep 2002 17:43:09 -0700 Subject: Python question on printout to HTML References: Message-ID: <7x8z1w2mw2.fsf@ruckus.brouhaha.com> "Ken" writes: > Hi, I wonder how you make the program to print out onto HTML such that it > prints at a time delayed setting of about 5-10 seconds between each line of > text so that the steps can be more readable to the user of the interface? HTML isn't really designed to be interactive at that level. Three ways to do it: 1) send as a multipart-MIME file and emit a new part from the server every 10 seconds. Ugh. 2) Forward from one page to another with an HTML META refresh tag, with 10 second refresh time. Ugh. 3) Send all the text on one html page as client side javascript. Have javascript code on the client display a new piece of it every 10 seconds. Ugh. Of the three, the last is probably best for JS-enabled browsers. Better: redesign your user interface to not need these kinds of timeouts. If some users need 10 seconds to view something, then others will need more than 10 seconds and others will get bored waiting that long. It's best to put everything on one page so users can read at their own pace. Next best is have the user navigate the browser him/herself, again at their own pace. From mbonig at hotmail.com Mon Sep 23 13:28:02 2002 From: mbonig at hotmail.com (Matthew Bonig) Date: Mon, 23 Sep 2002 17:28:02 GMT Subject: Jython file manipulation?! References: <2yej9.32454$gA4.4053@sccrnsc02> Message-ID: There are no exceptions raised... If you look at the source Jython uses for the os.rename function it just uses Java's File.renameTo()... that function returns false... which then the os.rename function throws a OSError exception, but it's not helpful in any way. The only thing I can think is happening is that I am doing this renaming on files that are on a netword drive on a win32 box, but I have double checked... the new filename is NOT there... (since win32 won't overwrite the new file if it exists, and therefore return an error, but that's not happening). I've also double checked to make sure I have write permissions on the network drive, which I most definetly do (I usually write 3-5 files onto that drive a day). This is why I thought there might be some sort of security issue with Jython... I'm pretty sure it's in the Jython side since when I tried exactly the same thing (os.rename(oldfilename, newFilename)) in python it worked perfectly. Thanks Matthew "Andreas Ulbrich" wrote in message news:amn87j$73a$1 at mamenchi.zrz.TU-Berlin.DE... > Matthew Bonig wrote: > > I am trying to rename a file in Jython... > > the command I am using is just > > os.rename(filename, newFilename) > > This works for me (Jython 2.1, JDK 1.4.1) > > You should give us some details, i.e. exceptions etc., to get some > better answers here. > From tdelaney at avaya.com Thu Sep 26 19:39:56 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 27 Sep 2002 09:39:56 +1000 Subject: comparing all values of a list to regex Message-ID: > From: Alex Martelli [mailto:aleax at aleax.it] > > I don't see exactly what value the call to map adds in your case. None at all in this case - good catch :) I'll blame it on feeling really buggered yesterday (am today too for some reason - thank goodness it's only about 7 hours until the weekend :) > > # Find out which list to append to > > > > match_list = match_all > > > > if not matches: > > match_list = match_none > > elif matches == 1: > > match_list = match_one > > elif matches != len(alist): > > match_list = match_some > > > > match_list.append(alist) > > Yes, choosing a list first and then appending to the chosen > list is nicer, but you cannot do that within the original > specs (for all I know the match_some list might grow > unbearably large over time, in this case). Hmm - why not? Ignoring that the original specs didn't actually *have* that case, choosing the list to append to, or doing it in-place is merely an implementation detail. Of course, you would need instead to do something like: match_list = None if not matches: match_list = match_none elif matches == 1: match_list = match_one elif matches == len(alist): match_list = match_all if match_list is not None: match_list.append(alist) Tim Delaney From sholden at holdenweb.com Sun Sep 29 07:07:39 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 29 Sep 2002 07:07:39 -0400 Subject: Local Python Server Installation References: <3d8b47c6.277669@news.jaring.my> <3d8c993c.2190426@news.jaring.my> <3d8d4009.375344@news.jaring.my> <3d947c26.2656654@news.jaring.my> <3d952602.1791864@news.jaring.my> Message-ID: :-) regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- "Kenneth Gomez" wrote in message news:3d952602.1791864 at news.jaring.my... > Dear Steve, > > I managed to get it to work!! > > I didnt configure the ScriptAlias directory to where my scripts were. > How silly of me! > > Thanks a lot Steve. > > Regards, > Kenneth > Cheers, > Kenneth Gomez. From pyth at devel.trillke.net Wed Sep 11 07:21:10 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 11 Sep 2002 13:21:10 +0200 Subject: Abstract Syntax Trees In-Reply-To: ; from ajw126NO@SPAMyork.ac.uk.trillke.net on Wed, Sep 11, 2002 at 12:09:38PM +0100 References: Message-ID: <20020911132110.S3893@prim.han.de> Andrew Wilkinson wrote: > Hi, > > I'm having a lot of trouble trying to get the parser and compiler modules to > properly parse some files. > > At the moment the trouble seems to be with any loop construct (i.e. for or > while). > > If you create a test file like this... > > --- > for i in range(10): > print i > --- make sure that this file has a newline at the end. others would say, get a better OS :-) regards, holger From wlfraed at ix.netcom.com Fri Sep 20 17:37:22 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 20 Sep 2002 14:37:22 -0700 Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <7xk7lhb943.fsf@ruckus.brouhaha.com> <3D8B18B7.2040203@thinkware.se> Message-ID: Magnus Lyck? fed this fish to the penguins on Friday 20 September 2002 05:46 am: > In one system it worked well for years, until > the application was ported from VMS to HP-UX. > It would probably have worked on HP-UX as well, > but values calculated on one platform and stored > in the database didn't match values calculated > on the other. > Heck -- a few years back we had that problem going from VAX VMS to Alpha VMS. The Alpha's registers used (if I recall the nomenclature) G-Float for doubles, where the VAX used D-Float. D-Float doubles are essentially a 32-bit float with another 32-bits of mantissa tacked on. G-Float, instead, adds a few bits to the exponent, and less than 32-bits of added mantissa. Along with the problems of having a "double" passed to a subroutine that only worked "single" (on VAX you essentially were ignoring the extended mantissa, on the Alpha the entire exponent was trash). -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From dwelch91 at nospam.attbi.com Sun Sep 29 13:05:01 2002 From: dwelch91 at nospam.attbi.com (djw) Date: Sun, 29 Sep 2002 17:05:01 GMT Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> Message-ID: <3D9732BD.500@nospam.attbi.com> Jurie Horneman wrote: > Once again my attempt to profit from Python's vaunted productivity > increase has come to a screeching halt because some innocent thing > that one would reasonably expect to work in one line, intuitively, and > without even having to think about, turns into a nightmare already > lasting more than an hour, requiring numerous experiments, searching > through the documentation - both manually and using my editor's > find-in-files - finally leaving me no other option but to write a post > to comp.lang.python, knowing that my programming flow for today is > well and truly gone. I hate doing this, because I know I cannot keep > my frustration out of my writing, and also that someone will reply and > gently or not so gently point out something which actually IS written > down in some obscure corner of the documentation, despite my attemps > to RTFM. > > So, what is it this time? No, it's not Unicode, another aspect that > frequently trips me up, causing my face to meet the rough asphalt of > the infobahn. It's importing modules. Again. > > (This is an obscure reference to an attempt on my part to implement > MBCS conversion functions as Python codecs. This failed miserably and > despite the helpful advice I received here, I never did try again. Too > bad, because those conversion functions are pretty good. And since I'm > doing some parenthesized ranting here: does anyone outside of the > Python world use 'codec' to refer to anything except audio / video > codecs? I actually had to post here just to find out that what I was > looking for were *called* codecs. Sheesh.) > > Anyway. > > I have this script, let's call it 'blah.py'. It sits in a directory > far, far away from where my Python is installed. It wants to include a > module called 'intro' from a subdirectory called 'templates'. > > This is evidently impossible. > > Among my vain, futile attempts were: > > *** Solution 1 *** > The World is a Beautiful Place > > >>>>import templates.intro >>> > > Ha! ha! ha! OK, even I knew this was a bit optimistic. > > *** Solution 2 *** > .PTH file > > Put a templates.pth containing the single line 'templates' in the same > place as 'blah.py', then > > >>>>import templates.intro >>> > or > >>>>import intro >>> > > No dice: 'ImportError: No module named...' etc. > > *** Solution 3 *** > IMPorting by hand > > >>>>import imp >>>>f = open('templates\intro.py') >>> > >>>>imp.find_module('intro.py') >>> > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named intro.py > > >>>>imp.find_module('intro') >>> > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named intro > > >>>>imp.find_module('intro', '\\templates\\') >>> > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No frozen submodule named .\templates\.intro > > (No WHAT?) > > >>>>imp.find_module('intro', '\\templates\\') >>> > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No frozen submodule named \templates\.intro > > >>>>imp.find_module('intro', ['\\templates\\']) >>> > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named intro > > >>>>imp.find_module('intro.py', ['\\templates\\']) >>> > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named intro.py > > >>>>imp.find_module('intro', ['.\\templates\\']) >>> > (, > '.\\templates\\intro.py', ('.py', 'r', 1)) > > Whoa! I finally managed to call imp.find_module without raising an > exception! OK, now to call imp.load_module, because the documentation > says: > > "Load a module that was previously found by find_module()" > > Alright, so there seems to be some connection between find_module and > load_module... The latter probably takes the return value of the > former as a parameter, right? Right? Wrong. > > Here are my attemps to call imp.load_module: > > x = imp.find_module('intro', ['.\\templates\\']) > > >>>>y = imp.load_module('intro', f, 'intro.py', x) >>> > Traceback (most recent call last): > File "", line 1, in ? > TypeError: load_module() argument 4, item 0 must be string, not file > > >>>>y = imp.load_module('intro', x) >>> > Traceback (most recent call last): > File "", line 1, in ? > TypeError: load_module() takes exactly 4 arguments (2 given) > > Okay, wait, my assumption was obviously naive, better read the doc... > aha. Almost the same parameters as find_module... wonder why I even > needed to call find_module in the first place. OK: > > >>>>y = imp.load_module('intro', f, 'intro.py', imp.get_suffixes()) >>> > Traceback (most recent call last): > File "", line 1, in ? > TypeError: load_module() argument 4 must be sequence of length 3, not > 5 > > What? But... but... *splutter* the doc says: > > "The description argument is a tuple, as would be returned by > get_suffixes(), describing what kind of module must be loaded." > > So why doesn't this work? OK, I have no idea why I'm bothering with > these kinds of arcana, but for the heck of it I'll try: > > >>>>y = imp.load_module('intro', f, 'intro.py', ('.py', 'r', 1)) >>> > Traceback (most recent call last): > File "", line 1, in ? > File "intro.py", line 29, in ? > ImportError: No module named Base > > Yay! What?! Now my IMPORTED module can't find the modules IT is trying > to import? (It doesn't matter if I put Base next to Blah.py or in > templates - Intro can't find it.) > > Arrrgghhh!!!! OK, enough time spent on this dead end. (Oh, and by the > way not all the functions of the imp module are documented.) > > *** Solution 4 *** > Packages > > OK, more searching, browsing and scouring my hard drive for the word > 'import'. Of course! I forgot that in the Python docs, important > information is cunningly hidden in the Tutorial section! (Really, am I > being unreasonable for assuming that once one has reached a certain > level of knowledge, one shuns the Tutorial and goes straight for the > main documentation, because that's where one can find everything there > is to know? That's only how it works in every language or piece of > software in general I've ever encountered.) > > So there are these things called 'packages'. Wow! Handy, that! All one > needs to do is put an empty file called '__init__.py' in a directory, > and hey! That directory becomes a package and Bob's your uncle. > > So I put an empty file called '__init__.py' in 'templates' and try the > following: > > >>>>import templates.intro >>> > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named templates.intro > > >>>>from templates import intro >>> > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named templates > > This is *exactly* how it's written in the Tutorial, and > it-does-not-work. > > *** Solution 5 *** > Abject Defeat, Ask on Internet, Be Ridiculed by Peers for Not Managing > Basic Operation > > Amusing little anecdote: I've performed all of the above steps twice - > once while growing increasingly frustrated, and a second time while > writing this post. Twice, while typing in the code above, I at some > point entered: > > import intro > > ... and it would work. For real. The symbols were there. Not a peep > out of the interpreter. > > Because I don't trust PythonWin (don't get me started on PythonWin, I > haven't found a better IDE yet, I may actually succumb and PAY for one > soon *shock horror*) I quit and restarted and lo and behold! the > interpreter complained that there was no such module, as it had been > doing all along, the horrible beast. > > In other words, at random, unreproducable moments, Python perversely > imported my module, whereas normally it refused to. > > To cut a long story... hm... Please please help me! Stop me before I > whine again. And please don't be offended by my ranting, I just can't > hide this much frustration. I'm using Python 2.2 by the way. > > Thanks in advance, > > Jurie. Hmmmm... I think you need to look into the documentation under "packages"... this tripped me up too until I figured out this (somewhat) unintuitive mechanism to get modules in subdirs to load. Here's what I did (on a Win2K box) to show you the steps: 1. Create a c:\blah subdir ("far" from Python directory, but doesn't really matter) 2. Create a blah.py in c:\blah that contains 1 line: import templates.intro 3. Create a c:\blah\templates directory 4. Create a blank (empty) file in c:\blah\templates called __init__.py 5. Create a intro.py in c:\blah\templates that contains the line: print "intro!" # this will print when we successfully import intro.py 6. Run blah.py: C:\blah>python blah.py intro! C:\blah> BTW, step #4 is the critical piece. Hope this helps, Don From mnations at airmail.net Wed Sep 18 16:45:23 2002 From: mnations at airmail.net (Marc) Date: 18 Sep 2002 13:45:23 -0700 Subject: Strange Telnet error Message-ID: <4378fa6f.0209181245.7b06124d@posting.google.com> Hi, I have been running some code that all the sudden stopped working. I can not figure out what's happened. I am doing a simple telnet connection that sends and receives info. Now I am getting this error: Traceback (most recent call last): File "C:\Python22\lib\threading.py", line 408, in __bootstrap self.run() File "C:\Python22\lib\threading.py", line 396, in run apply(self.__target, self.__args, self.__kwargs) File "main.py", line 85, in run command[0](*command[1:3]) File "key.py", line 92, in command conn.write(com) File "C:\python22\lib\telnetlib.py", line 272, in write self.sock.sendall(buffer) AttributeError: 'int' object has no attribute 'sendall' Has anyone ever seen this before? If so, what could do this be related to? Thanks, Marc From tjreedy at udel.edu Wed Sep 11 10:35:44 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Sep 2002 14:35:44 GMT Subject: Python primer - comments appreciated! References: Message-ID: <4xIf9.575097$2p2.23759339@bin4.nnrp.aus1.giganews.com> "Thorsten Kampe" wrote in message news:alnipo$1pqmu8$1 at ID-77524.news.dfncis.de... > * Terry Reedy > > Then > > append to the list. This working depends on there being *two* > > references to the list. The one in the dict (possibly new, possible > > not) and the one returned by the method and used by append(). Please reread second sentence!!! > Okay, let's make this clear: > D = {'0': [3, 6], '1': [4]} > D.setdefault('1', []) > ...returns: [4] It returns a reference to the list with current value [4] > [4].append(7) > ...puts [4, 7] on the "stack" NOOOOO!!!!! In context of of original expression, it appends 7 to list pointed to by *both* dict and reference returned by setdefault(). > But where is the instruction saying "store [4, 7] back to D['1']"? The list is never taken out of D['1']. The append is 'in place' via the double reference! Try print id(D['1']), id(D.setdefault('1', [])) to see that same list. > Shouldn't this be: D['1'] = D.setdefault('1', []).append(7) ? Since append returns None, this will not work. Terry J. Reedy From rob Tue Sep 24 13:24:33 2002 From: rob (Rob Andrews) Date: Tue, 24 Sep 2002 17:24:33 GMT Subject: Python highlighting in Kobol Message-ID: This is a rather minor thing to point out, I suppose, but I found it interesting. Kobol, the Linux/Windows COBOL IDE from The Kompany, supports Python highlighting in the editor. http://www.thekompany.com/products/kobol/ I don't think they mention it in their promotional pages on thekompany.com, but I have the IDE and just noticed their highlighting of Python and numerous others. regards, Rob From DennisR at dair.com Thu Sep 19 17:44:26 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Thu, 19 Sep 2002 21:44:26 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: <_yri9.2058$CR.74235141@newssvr14.news.prodigy.com> > I have duplicated your experience with both Netscape and Opera on Win98. I > have neither a fix nor a facile explanation at this time. I have repeatedly > run both browsers on other CGI code in both Perl and native PLD2. I suspect > a recent change here is at fault. The server code for implementing CGI style headers was incorrectly implemented. This is not a recent change but, rather, incorrect coding. When I posted the code URLs, I believed that I had "repeatedly run both browsers on other CGI code...". At this point, I can only conclude that the CGI code has been run on IE only (where it does work despite the header errors). Rather than rush a fix here, I am going to hold off reposting until I have done a proper release. The files sample files whose URLs have previously been given have been deleted so that no one else serves as an inadvertent beta tester. I am sorry for posting immature code. -- Dennis Reinhardt DennisR at dair.com http://www.dair.com From wurmy at earthlink.net Wed Sep 18 18:08:58 2002 From: wurmy at earthlink.net (Hans Nowak) Date: Wed, 18 Sep 2002 22:08:58 GMT Subject: Calling function from command line References: Message-ID: <3D88F9F4.6020306@earthlink.net> GREGORY KNESER wrote: > Hi, > > I have a file func.py which includes a working function definition with some > inputs and some defaults for those inputs. > > I want to type > > c:\python22\python func.py func1('input1','input2') > > or some such thing and run the function with the inputs I fed it rather > than the defaults. Is such a call possible? This code may get you started: ---->8---- # cmdline.py def twice(x): return 2 * x def foo(*args): print "Yay! You used these arguments:" for arg in args: print "-", arg def bar(): print "bar!" if __name__ == "__main__": import sys, string funcname, args = sys.argv[1], sys.argv[2:] arglist = string.join(args, ", ") cmd = "%s(%s)" % (funcname, arglist) print "Executing:", cmd result = eval(cmd) print "Result:", result ---->8----- On my box (Win2K with 4NT), I can call it like this: (P:\test\general) $ cmdline.py twice 4 Executing: twice(4) Result: 8 (P:\test\general) $ cmdline.py foo "bar" 'bar' 42 Executing: foo(bar, 'bar', 42) Yay! You used these arguments: - - bar - 42 Result: None (P:\test\general) $ cmdline.py bar Executing: bar() bar! Result: None Some people may yell at you or me because the eval() function is used, but as long as it's you who executes the code, it's really no biggie. There may be a better way to do this, though, e.g. by inspecting the module's globals and locals, and maybe use apply()... Even better may be, just firing up the interactive interpreter with your module loaded, and type your function calls there. -- Hans "so much code so little time" Nowak The Pythonic Quarter:: http://www.awaretek.com/nowak/ Kaa:: http://www.awaretek.com/nowak/kaa.html From spam at ob_scure.dk Fri Sep 6 06:55:22 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Fri, 06 Sep 2002 12:55:22 +0200 Subject: how could we know which module is imported already ? References: <7153651c.0209060233.2a72caaa@posting.google.com> Message-ID: <3D78899A.2010202@ob_scure.dk> black wrote: > want to know how many and what the module is imported~ Have a look at sys.modules import sys print len(sys.modules) -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From skip at pobox.com Fri Sep 6 10:48:05 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 6 Sep 2002 09:48:05 -0500 Subject: pygtk In-Reply-To: References: Message-ID: <15736.49189.54748.336080@12-248-11-90.client.attbi.com> Martin> Is this a good group to discuss pygtk things or is this just for Martin> python? (I think I have questions in both.) A better place to discuss pygtk is the pygtk at daa.com.au mailing list. Comp.lang.python (aka python-list at python.org) is a newsgroup for discussion of general Python topics. Martin> So now this message is also to say 'Hello' to everybody in this Martin> room. Back atcha... -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From brueckd at tbye.com Fri Sep 6 16:03:59 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 6 Sep 2002 13:03:59 -0700 (PDT) Subject: Larry Wall's comment on python... In-Reply-To: Message-ID: On 6 Sep 2002, Rod Stephenson wrote: > "Python is cool to look at small bits of, but I think the "outline" > syntax breaks down with larger chunks of code. I'm with Aristotle on > the structure of discourse--a story should have a beginning, and > middle, and an end. So should blocks" > > I'm not quite sure what he's trying to get at here - I guess that for > a long heavily indented chunk of code, you could lose track of the > overall structure, but I don't write code this way. > > Any comments? The very idea of Larry Wall lecturing on code readability is hilarious. -Dave From pedronis at bluewin.ch Wed Sep 4 13:52:15 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Wed, 4 Sep 2002 19:52:15 +0200 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> Message-ID: <3d76494d$1_5@news.bluewin.ch> Robin Becker wrote in message rnLbuKAv5jd9Ewzz at jessikat.demon.co.uk... > In article <3d76366a$1_5 at news.bluewin.ch>, Samuele Pedroni > writes > >From: Robin Becker > >> A colleague has been running tests of reportlab under jython-2.1 several > >> of the tests use prodigious amounts of memory (one even failed). We're > >> using win2k+j2sdk1.4.0_01 as the jython engine. > >> > >> Anyone know what sorts of things cause x10 memory usage? I find one > >> particular test needs more that 1Gb and then falls over for lack of > >> memory. > > > >That means you are running jyhton through: > > > >java -mx1024m -cp ...jython.jar org.python.util.jython ... > > > >and it uses all that memory and would need more? > > > >regards. > > > > > well actually we're running with the default jython.bat which doesn't > seem to specify a memory, 1Gig is probably the default or maybe I ran > out of page space. The python process never gets over 90Mb grrrhhhh. then maybe I'm puzzled, have you checked process memory usage or is just that you get an "out of memory" and are estimating based on your total memory. Because the normal jython.bat uses the JVM default which is to scream "out of memory" after 64Mb of object memory has been allocated, see -Xmx here http://java.sun.com/j2se/1.4/docs/tooldocs/windows/java.html#options regards. From chris.gonnerman at newcenturycomputers.net Thu Sep 26 01:21:46 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 26 Sep 2002 00:21:46 -0500 Subject: Python on a Novell server References: <3d928cb5_6@news.newsgroups.com> Message-ID: <008901c2651c$9d600300$0101010a@local> ----- Original Message ----- From: "JB" > We have a Novell net at our school and are trying to install > Python 2.2 on a Novell server. This does not work at the > moment as we get the error message "python.dll not found" > at the moment. > > Is it possible to install Python a a server or has it to be > installed locally on each workstation? I have successfully used the Pythonware distribution stored on a Linux/Samba server from various Win32 clients... I assume something like this is what you want? You need a special startup batch file to run this way, or a starter executable, which can set the PATH to include the Python folder. This should be easy on a Novell system where you can use the login script to set the path appropriately. The python.org version uses the registry to contain some paths; if you use win32all with the Pythonware version, you need to set those registry entries manually. pythonware.com has a FAQ for this (don't have the URL handy). Good luck! Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From shalehperry at attbi.com Thu Sep 12 01:26:53 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 11 Sep 2002 22:26:53 -0700 Subject: [FEEDBACK] Is this script efficient...is there a better way? In-Reply-To: <3D7FF723.3050005@one.net> References: <3D7FF723.3050005@one.net> Message-ID: <200209112226.53151.shalehperry@attbi.com> On Wednesday 11 September 2002 19:08, Michael Schneider wrote: > Bob X wrote: > >> 1) readlines() loads the entire file into a list so if you have a 30+ > >> mb file you just ate 30+mb of memory. Try using xreadlines() > >> instead, it reads the file line by line and is much more memory > >> friendly. > > > > Very cool...I had missed that! > > It is much slower though. I am not sure about your config, but I am > running with a Gig of memory. > I would much rather have the speed then the 30 mb of memory. Again, > check your config. sorry, I am not used to my program being the only piece of software running on a system. Sure his app may only use 30mb out of a 512mb system. But how many other apps are coded just like his and believe all of the machine's memory can be used up by one program. Every time I have made that choice I have had to go back and change it. Plus this allows for the file to not be a file anymore. From spoermeg at voldelig.com Tue Sep 17 19:38:40 2002 From: spoermeg at voldelig.com (Terje Johan Abrahamsen) Date: Tue, 17 Sep 2002 18:38:40 -0500 Subject: Source code References: Message-ID: "Tim Peters" wrote in message news:mailman.1032152959.16896.python-list at python.org... > [Terje Johan Abrahamsen] > > If I would like to write some code that would not be possible for > > others to read, after I distribute the program, would Python be > > suitable? > > No, but I don't know of a language that would be. Unless you're also going > to supply a restricted CPU that prevents stepping through the machine code, > you can't really hide anything from a determined reverse-engineerer of > ordinary skill. > > > ... > > or should I look for a compiled language instead? > > It's very easy to reverse-compile Python bytecode. It's not so easy to > disassemble compiled machine code, but if you think there aren't lots people > who can read machine language almost as easily as high-level source, you're > in for a surprise. Compilers follow predictable patterns too. You could > try writing directly in highly obfuscated assembler; that would raise the > bar high enough to discourage almost everyone, although it would also > attract a class of cracker who would feel challenged to outwit you. > > If you didn't know all that already, you're playing a game you can't win. A > better idea is to question why you want to play it at all . I am not looking to stop people that really want to copy my code. My program is not that unique. However, I want them to have to type the code themselves if they want to duplicate it. Not only to reuse my sourcecode if it can be picked up from Py2Exe. From vitus at communiware.ru Mon Sep 2 04:08:08 2002 From: vitus at communiware.ru (Victor Wagner) Date: Mon, 2 Sep 2002 08:08:08 +0000 (UTC) Subject: Could Python supplant Java? References: <8d3f4438.0208202348.578ff9c8@posting.google.com> Message-ID: In comp.lang.tcl Dan Johnson wrote: > disposal), >> or perhaps kindergarten herder ... > Serious question: > What is so developer-hostile about Windows? "Friendly" interface. To be a "friendly" is to consider oneself equal with his friends. If you want your friend to do something for you, you ASK him, not ORDER him. Developer is one who want be a master of his programs, not a friend. So, best interface for developer machine is slavy one, not friendly. Programs are to obey orders, not to carry out friendly talks. Really, it is true for any user, not just developer. But ignorant users can consider friendlyness helpful. They need even more than friendliness, they need patronage. But developer is by definition a person, who know something about informational technologies. So, arrogance of "frienly" interface is unbearable for him. He knows what we wants his machine to do, and when he sees that machine has its own opinion, as "friendly" interface should and do, it becomes very irritating. -- http://www.communiware.ru http://www.ice.ru/~vitus From ned at nedbatchelder.com Tue Sep 10 07:22:05 2002 From: ned at nedbatchelder.com (Ned Batchelder) Date: 10 Sep 2002 04:22:05 -0700 Subject: How to choose a package name? Message-ID: What's the current thinking on how best to choose package names to avoid conflicts? The last discussion about it was four years ago, and included this message from Guido: http://groups.google.com/groups?q=g:thl404422857d&selm=199801150144.UAA17896%40eric.CNRI.Reston.Va.US He mentions a NIST registry, but on a quick look it seems abandoned. In Java, I know which part of the namespace I already own (based on domain registration). I understand Guido's reservations about that system (code changes ownership). Do we have anything other than "choose something reasonably unique, and search Google, Vaults of Parnassus, Python Starship, and comp.lang.python for conflicts" as a guideline? --Ned. http://www.nedbatchelder.com From brian at sweetapp.com Thu Sep 26 00:00:51 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 25 Sep 2002 21:00:51 -0700 Subject: Getting started In-Reply-To: <3D928488.3060906@cascade-sys.com> Message-ID: <00a801c26511$4e084750$df7e4e18@brianspiv1700> > Some use "weak typing" to mean any type system where the typing can be > foiled by casts; What does "foiled by" mean in this context? Cheers, Brian From grabiller at 3dvf.net Wed Sep 25 11:35:16 2002 From: grabiller at 3dvf.net (Guy Rabiller) Date: Wed, 25 Sep 2002 17:35:16 +0200 Subject: Newbie References Question -> Exemple References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> <3d91d2cf$0$1484$79c14f64@nan-newsreader-01.noos.net> Message-ID: <3d91d7ab$0$13192$79c14f64@nan-newsreader-03.noos.net> Ok I solved it, thanks to sismex. If I want to change a coordinate, I have yo write: p[0][:] = [5,5] and not p[0] = [5,5] I understand that in the first case, the reference pointed ( via dictionary ) by p[0] is lost, a new value is created and rebinded to p[0], so quad and p[0] are not synchonised anymore. In the second case, the reference pointed by p[0] is updated with a new value. p[0] and quad are still synchronised. Is my understanding correct ? Thanks a lot to all. -- guy rabiller 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net Guy Rabiller wrote: > Ok, > > thanks for your answers, I understand now that a variable name is > 'just' a name in a dictionary, and not a container. > > What I want to do is simple, and I suppose that this is my 'way of > thinking' regarding Python that is wrong. > > I have a list of points, and a list of polygons that should contain > 'references' to points. > > So for me: > -> points list: > p = [] > p.append([0,0]) > p.append([0,1]) > p.append([1,1]) > p.append([1,0]) > -> polygon: > quad = [] > quad.append(p[0]) > quad.append(p[1]) > quad.append(p[2]) > quad.append(p[3]) > > But now, if I change the coordinate of one point: > p[0] = [5,5] > I will have: >>>> p > [[5, 5], [0, 1], [1, 1], [1, 0]] > but: >>>> quad > [[0, 0], [0, 1], [1, 1], [1, 0]] > > For me the quad list of point is not 'updated' with the change of one > of its point. > > What I want to do is that, quad keeps a list of 'references' to points > coordinates. > Then if I change one point coordinates, the change is reflected in > the quad list of points. > > I have no clue how to do this. > > > Guy Rabiller wrote: >> Hi, >> >> let say I have: >> i1 = 1 >> i2 = 2 >> and >> p = [i1,i2] >> >> How can I have: >> p=[*i1,*i2] >> rather than >> p=[**i1,**i2] as it is curently ? >> >> ( Sorry for this nasty hybrid syntax ) >> >> Textualy, how if I want that p[0] refere to the 'i1' container, and >> not to the refererence it contains ? >> >> What I want is that if now I set: >> i1 = 4 >> that automaticaly: >> p -> [4,2] >> and not keeping [1,2] >> >> Thanks in advance. From buzzard at urubu.freeserve.co.uk Mon Sep 9 20:09:18 2002 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 10 Sep 2002 01:09:18 +0100 Subject: RPy / Win2k References: Message-ID: "Walter Moreira" wrote in message news:mailman.1031613673.1670.python-list at python.org... > On Sat, Sep 07, 2002 at 01:19:13AM +0100, Duncan Smith wrote: > > Hello, > > Is there anyone out there who has successfully used RPy under > > Win2k? I get the impression (from Brian Ripley) that it should be possible > > to embed R under Win2k, but that it probably isn't straightforward. Can > > anyone help? Cheers. > > Well, actually it is possible thanks to a patch from Rene Hogendoorn. I > have been busy but I will release a Windows version soon. The changes in > the source are not straightforward, indeed. I'll try to do it before > end of september. > > Regards: > Walter > > Thanks Walter, that's good news. When I spoke to Brian he said that R could not be built as a shared library under Windows. Does this mean I won't need to reinstall R? Cheers. Duncan From lee100 at sport.rr.com Tue Sep 17 23:20:02 2002 From: lee100 at sport.rr.com (Lee Gray) Date: Wed, 18 Sep 2002 03:20:02 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: Skip Montanaro wrote: > > Lee> Can someone point me to a good Python GUI app to demonstrate > (other Lee> than IDLE)? > > Lee, > > At IPC 10, Michel Sanner from Scripps took home the best paper award for > his > ViPEr work. References: > > http://www.python10.org/p10-awards.html > http://www.python10.org/p10-papers/10/index.htm > http://www.scripps.edu/~sanner/python/viper/index.html > Very nice! Thanks for the ref. Lee From johandewitte at hotmail.com Tue Sep 3 07:52:53 2002 From: johandewitte at hotmail.com (Johan de Witte) Date: 3 Sep 2002 04:52:53 -0700 Subject: simpleparse example References: <3d62a770.10000379@newszilla.xs4all.nl> Message-ID: baronvm2 at yahoo.com wrote in message news:<3d62a770.10000379 at newszilla.xs4all.nl>... > Hi, > > I'm trying to use SimpleParse to process semistructured data. I have > defined the language and can produce a taglist. > > How can I use the dispatchprocessor to process the taglist? Does > anybody have an example. > > Thanx, > Hans I have plenty of working code to do such a thing. I use it to parse weakly structured HTML pages and strip out the unneeded stuff. The code can however be applied to almost _any_ kind of data. (Theoreticaly it can be applied to _any_ kind of data). You can have tons of examples, and you can use all my stuff as long as you don't sell it. From peter at engcorp.com Sun Sep 1 13:36:52 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 01 Sep 2002 13:36:52 -0400 Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: <3D725034.DF95E07D@engcorp.com> Robert Oschler wrote: > > "Gerhard H?ring" wrote: > > >>> def bar(self): print "bar" > > ... > > >>> Foo.bar = bar > > >>> foo.bar() > > bar > > Thanks but I need a little bit more detail. Suppose I want to do it from > within code? For example, I create a function called > AddBarToFoo(FooObject), that given a object of type Foo (FooObject) adds the > Bar method to it dynamically, what would be the syntax then? Would I have > to put the method declaration code, which you show being typed in to the > interpreter, in a string and then eval/exec it? Is there a more convenient > way than that? Robert, pretty much anything you can type at the interactive prompt can be typed as-is into a source file and executed the same way. That's why the prompt is so good for experimenting and learning. Try doing what you want interactively, the way Gerhard did, and then in your text editor window paste in the bits of code as you get them working. Basically, to do what you are asking you shouldn't have to do anything different than what Gerhard did, but there's no substitute for trying it yourself. (If you have troubles, show us some snippets that you've tried so we can get a better idea where you are trying to do with this.) -Peter From peter at engcorp.com Tue Sep 24 20:06:11 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 24 Sep 2002 20:06:11 -0400 Subject: List/Tuple bug or feature? References: Message-ID: <3d90fdeb$1@news.sentex.net> sismex01 at hebmex.com wrote: > It's one of python's features :-) > > For when you wanna write a long string, SQL for example: > > Query = "SELECT what, when, where, why " > "FROM t1, t2, t2 " > "WHERE t1.id = t2.id_t1 and t3.id_t2 = t2.id and t1.id_t2 = t3.id " > "AND t1.answer = 'OK'" > > Kinda neat. Especially when it actually works... you need the brackets or parentheses around the above strings or it will give you a SyntaxError. -Peter From glingl at aon.at Sun Sep 29 14:52:53 2002 From: glingl at aon.at (Gregor Lingl) Date: Sun, 29 Sep 2002 20:52:53 +0200 Subject: Python and GUI question References: <3d96b808_3@news.bluewin.ch> Message-ID: <3D974C05.4030007@aon.at> Josef B?rgi schrieb: > Dear NG > > I designed a CMS using mySQL and PHP. Now I like to write an administrativ > GUI Client Tool using Python. So I bought a few books about it, saying that > there is more then one GUI interface (Tk, Qt, xvWindow). So can anyone tell > me which one you use and why ? And how do you Design GUI interfaces (IDE) ? There is a nice book (in German): Python and GUI-Toolkits, (mitp), which contains a thorough evaluation of all those toolkits as well as a bunch of tipps concerning their respective strengths and weaknesses, and when to use which one. Regards (from Austria) Gregor (P.S.: As a teacher I use Tkinter, because it comes with Python and everybody who has Python has it. I don't have to delve deep into GUI-programming) > > Best wishes fromSwitzerland > > Joe > > From tismer at tismer.com Sat Sep 21 23:10:09 2002 From: tismer at tismer.com (Christian Tismer) Date: Sun, 22 Sep 2002 05:10:09 +0200 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> Message-ID: <3D8D3491.8010803@tismer.com> Dan Bishop wrote: > Magnus Lyck? wrote in message news:<3D8B1537.4010803 at thinkware.se>... > >>ChrisBarker wrote: >> >>>The only reason I can see >>>to not writing your class in Python is performance, and unless you are >>>doing a lot of calculations, that is probably a non-issue. >> >>Performance issues might well matter in large financial >>systems, but that's not the only reason. > > > Please name one other real-world situation in which decimal arithmetic > is actually *needed*. There is no reason to argue about that. Decimal arithmetic is exact for most of the operations bankers require. They have been demanding for it since decades, and they will not drop it. Having "no rounding issue at all" is better than any consideration about neglectible errors, it cannot be beaten, since *they* understand it. Cannot be discussed. They pay the bill. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From mwh at python.net Wed Sep 25 07:41:29 2002 From: mwh at python.net (Michael Hudson) Date: Wed, 25 Sep 2002 11:41:29 GMT Subject: Remarks to Python 2.3 References: <20020918222421.328088eb.use-net@schabi.de> Message-ID: Markus Schaber writes: > - When replacing list elements using the extended slice syntax - e. G. > in a[::2] = range(0, -2, -1) - the left side must have exactly the same > numer of elements as the right side. So, to cite the example, a[::2] = > range(3) is illegal for a=[0, 1, -1, 3]. > > Now I could image that it makes sense to allow one single additional > element to be added to the list in case only the step is specified and > the operation doesn't produce a gap. So the given example above would be > valid, giving a sequence of five elements, whereas with a=[0, 1, 2] it > would stay illegal (as it would produce a gap). a[0:3:2]=range(3) would > stay illegal as it explicitly specifies the length of the range, > a[0:3:5]=range(3) could be allowed. Wanna implement that? I agree it sounds reasonable. This sort of thing is way harder to get right than you might think, though. If you (or anyone else) submits a patch, I'll review it. Cheers, M. -- Monte Carlo sampling is no way to understand code. -- Gordon McMillan, comp.lang.python From fredrik at pythonware.com Wed Sep 4 03:14:06 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Sep 2002 07:14:06 GMT Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <3d72f007.1990343@News.CIS.DFN.DE> Message-ID: <2pid9.5882$e5.1033577@newsb.telia.net> Gerson Kurz wrote: > Seriously, my thinking was, the re.compile function is there to > compile an expression to a binary representation for optimized > searching. So maybe, a "clean syntax" -> "ugly re syntax" compiler > would be good? note that the SRE engine contains an "ugly syntax" to "internal data structure" parser, and an "internal data structure" to "engine code" compiler. it's probably easier (and definitely more efficient) to turn a clean syntax into an "internal data structure" than into an ugly syntax. (the next step is to use python's own parse tree instead of SRE's internal structure, and use an extension to python's compiler for the final step. make it all pluggable, and you have perl6...) From eppstein at ics.uci.edu Thu Sep 26 02:00:36 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 25 Sep 2002 23:00:36 -0700 Subject: revenge of the python puzzle References: Message-ID: In article , Michal Wallace wrote: > Okay, so you guys think you're so smart. Try this one! No > contest this time, I've learned my lesson. (I suppose if > someone really wants some free hosting bad enough to solve > this puzzle, you could talk me into it, but I'm just posting > this for revenge... Um, I mean "fun".) I'm not going to spoil this, just point out that my cryptogram applet http://www.ics.uci.edu/~eppstein/cryptogram/ (sorry, not written in Python, but Java source available) solves this really easily. You'd have to make it a lot shorter or a lot less like English to make it difficult... of course to a human the keywords in the lines with colons are dead giveaways... -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From pinard at iro.umontreal.ca Sun Sep 8 17:20:25 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Sun, 08 Sep 2002 17:20:25 -0400 Subject: Unicode -> String problem In-Reply-To: <3B48D1DB.C3F726C9@ActiveState.com> (Paul Prescod's message of "Sun, 08 Jul 2001 14:34:19 -0700") References: <20010708204337.MJGP11827.femail4.rdc1.on.home.com@jparlar> <3B48D1DB.C3F726C9@ActiveState.com> Message-ID: > Jay Parlar wrote: >> [...] Is there a simple way to convert the unicode text to StringType, >> removing the resulting unicode strings for unrepresentable characters? [Paul Prescod] >>>> import codecs >>>> codecs.ascii_encode(u"foo\u3333bar", "ignore") > ('foobar', 7) The documentation for Python 2.2.1 does not speak about `ascii_encode', and the interactive documentation is rather terse: ----------------------------------------------------------------------> >>> help(codecs.ascii_encode) Help on built-in function ascii_encode: ascii_encode(...) None ----------------------------------------------------------------------< Where did you find that bit of information? :-) For now, I would presume that `codecs.ascii_encode(UNICODE_STRING)' does the same as `UNICODE_STRING.encode("ascii")' and consequently, we do not need to know about `ascii_encode'. Is that right? -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From duncan at NOSPAMrcp.co.uk Wed Sep 11 09:57:34 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 11 Sep 2002 13:57:34 +0000 (UTC) Subject: Regexp Over Multiple Lines References: <565e316f.0209040740.36573b56@posting.google.com> <565e316f.0209110529.30e61ea4@posting.google.com> Message-ID: vetter at lincom-asg.com (Keith) wrote in news:565e316f.0209110529.30e61ea4 at posting.google.com: > I am sure that this has been discussed... but in a nutshell can you > tell me where python lacks in power behind perl. If I go to rewrite > my Perl code, which has gotten really messy, in Python will I be > saying over and over again, "Man, I can't do =that= in Python!" > I don't claim to know Perl, but sticking my neck out I would say on the basis of long experience of this newsgroup that you should be able to get the results you want in Python, but you may find that the idiomatic way to achieve it requires a significant mental gearshift. Once you learn the idioms you should do fine. BTW, one of the idioms is not to use regular expressions as often as in Perl. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From rwaldron at ihug.co.nz Thu Sep 26 18:20:48 2002 From: rwaldron at ihug.co.nz (Ross Waldron) Date: 26 Sep 2002 15:20:48 -0700 Subject: Whats the Difference between Windows XP and Windows 98.... References: <3fda493d.0209250933.1a99079f@posting.google.com> Message-ID: If the SLP200 is connected via a serial (COM) port it may be to do with the COM port settings under Windows 98. Make sure the COM port settings are: Bits per second: 9600 Data bits: 8 Parity: None Stop bits: 1 Flow Control Xon/Xoff "Use FIFO buffering" should be enabled If you are connected via USB, then it may be the difference between the "dodgy" USB drivers in Win98 and the better USB drivers in XP. Try updating your USB drivers for Win98. Regards Ross Waldron naveed_iq at hotmail.com (Naveed Iqbal) wrote in message news:<3fda493d.0209250933.1a99079f at posting.google.com>... > Whats the Difference between Windows XP and Windows 98....when it > comes to the win32 extensions to python? I used the win32ui and > win32com.client modules to print to a printer from windows. the output > from the XP machine comes out fine, but the output from the 98 machine > looses its formating. I am using a Smart Label Printer 200. this label > printer has drivers for all windows family OS's. > does anybody have an idea as to what is going on? > thanks > Naveed From amdescombes at qualicontrol.com Fri Sep 6 06:30:03 2002 From: amdescombes at qualicontrol.com (Andre Michel Descombes) Date: Fri, 6 Sep 2002 12:30:03 +0200 Subject: Python and Jython inconsistencies when encoding strings Message-ID: Hi, I've noticed the following inconsistency between Python 2.1 and Jython 2.1 : when I do the following in Python : >>> s = u'?' # Alt-0163, pound sign >>> print s I get the following exception, which is a normal exception: Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) >>> I corrected this with using the encode function like this: >>> print s.encode('latin-1') ? >>> now when I do the same thing in Jython 2.1 I get this: >>> s = u'?' # Alt-0163, pound sign >>> print s ? >>> and if I do: >>> print s.encode('latin-1') I get: Traceback (innermost last): File "", line 1, in ? UnicodeError: latin-1 encoding error: ordinal not in range(256) >>> Does anybody know what is causing this inconsistency? Is there any way to avoid it? Thanks, Andre From gerhard.haering at gmx.de Mon Sep 2 01:21:35 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 2 Sep 2002 05:21:35 GMT Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <3d72f007.1990343@News.CIS.DFN.DE> Message-ID: Gerson Kurz wrote in comp.lang.python: > "A.M. Kuchling" wrote: >>The problem with a new syntax is that no one else would be using it, so >>you'd still need to learn the existing syntax for use with grep, vi, Perl, >>&c. (It wouldn't surprise me if Perl 6's revised regexes run into this very >>difficulty and don't gain much adoption.) > > A tounge-in-cheek-answer: I don't use grep, I use python. I don't use > vi, vi? Yuck. vim or die :-P > I use python. I don't use perl, I use python :) > > Seriously, my thinking was, the re.compile function is there to > compile an expression to a binary representation for optimized > searching. So maybe, a "clean syntax" -> "ugly re syntax" compiler > would be good? I think it would. Though the other way round wouldn't be that bad, either. -- Gerhard From hwlgw at hotmail.com Mon Sep 2 05:51:06 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 2 Sep 2002 02:51:06 -0700 Subject: Twisted docs (was Re: Python IPC options) References: <1030829572.943495@irys.nyx.net> <3D715160.2020109@itamarst.org_NOSPAM> <3D728386.2060908@itamarst.org_NOSPAM> Message-ID: Itamar Shtull-Trauring wrote: > I take it you're going to volunteer some time to write > docs? We'd really appreciate it! ;) Okay I will try, but my TODO list is already very long. So it will be a weekend thingy and could take a while to produce something useful, besides I will have to learn Twisted first! What I propose is to show how to develop a medium sized application in the Twisted framework that uses a lot of Twisted's capabilities. It should have asynchronous *and* synchronous communication, *mobile* components and because of that a dynamic network. It should also show how to exchange data with a server / database via its URL on the internet. Also to be fun it needs a GUI so I will use Tkinter, I believe there are examples already how to combine Twisted with Tkinter. Tkinter seems to be the best choice since it is one of Python's included batteries and it is portable and I have some experience with it. Now what kind of application would that be? My idea for the application is a trader agent and its environment. It could be something like a simulation or a game where you have to program an automated trader agent that buys and sells stocks for you. The client should also have an interactive mode so you can do things manually too. There is a central market / database / server online all the time. First I need to set up a website that simulates a stock market, or maybe I can just use an existing one, have to see how stable the data are they produce. www.nyse.com? Does this kind of application show enough of Twisted's features? You have more ideas? Do you think some things are too hard or impossible? Demonstrated features --------------------- * Asynchronous communication: Updates from the market to the client (if it is online) in a send_and_forget fashion. * Synchronous communication: Buying and selling transactions * Mobility: The clients should be able to connect from anywhere and it should maybe be possible to relocate the market. * Dynamicity: See mobility. Also there will be an unknown number of clients at any time. * RPC: client <-> market, but maybe also perhaps client <-> client for forming trade groups? * GUI integration To show what a client does and to be able to do manual trading. * Remote debugging? Remote market profiling? Market logging? Have to go back to my real work now. What surprises me is that the Twisted people did not come up with a demo apllication like this already, the more I think about it the more fun it seems. I did see a MUD-something-application mentioned on the Twisted site, but could not find it. The trader application looks a bit more ``serious'' perhaps, better for public relations? Also make absolutely sure people using Windows can install everything they need with just doubleclicking an .exe or whatever. You can do it, Twisted already has that for the modules. Writing software for installing things and writing documentation is generally considered *boring* and uncool work among programmers. I know. Hope this helps inspiring you to do it and to look at it in another way? For now good luck with writing good docs about things I do not know about yet: Twisted deserves it. So one day it can become one of Python's included batteries too! :: A child of five could understand this! Fetch me a child of five. From loewis at informatik.hu-berlin.de Wed Sep 11 12:07:55 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 11 Sep 2002 18:07:55 +0200 Subject: Background programs on Windows XP References: <3D7F5181.AD09A901@ex.ac.uk> Message-ID: "M.J.Fisher" writes: > However, when one of the users of this program changed from Windows'95 > to WindowsXP (they also changed from Python2.1 to Python2.2 but I didn't > think this was probably relevant) this stopped working. Did it give any information of how it stopped? What happens if you do this in a cmd.exe window? Regards, Martin From aleax at aleax.it Fri Sep 20 05:11:17 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 09:11:17 GMT Subject: How to access XML passed from an XForm References: Message-ID: Jeremy Rew wrote: > I dont know if this has been answered before now, but I couldnt find it > after a fair bit of searching. (is there any way of running a search on > the archives?) Google is your friend -- use an advanced groups search, specifying comp.lang.python as your group of interest. I just did that looking for xform but none of the 6 hits appears relevant to your question. http://groups.google.com/advanced_group_search?hl=en is one way to access Google's page for advanced groups search, by the way. Alex From dubal at khimjiramdas.com Fri Sep 6 02:22:38 2002 From: dubal at khimjiramdas.com (J Dubal) Date: 5 Sep 2002 23:22:38 -0700 Subject: How to install informixdb-1.3 for python2.2 on RH7.3? References: Message-ID: Hello again! I managed to compile and install informixdb module manually for py221. However, when I import it in python2, it gives following error: ImportError: Cannot locate C core module for informix db interface. If I try import _informixdb, it gives following error: ImportError: /opt/informix/lib/esql/libifgen.so: undefined symbol: stat Please help. If we cannot make this work, we will have to go back to 1.5.2 - not very attractive alternative. Thanks in advance. Dubal. dubal at khimjiramdas.com (J Dubal) wrote in message news:... > Hello good people! > > As mentioned in its readme, informixdb-1.3 compiles, installs and > works with the stock python 1.5.2 of RH7.3. However, when we try to > compile it for python 2.2.1, informixdb's ./configure fails because it > is looking for Makefile.pre.in which is not there in python 2.2.1. It > appears that someone has to repackage informixdb with distutils. How > to do this? In the meanwhile can we install this manually? I do not > understand Makefile.pre.in. Please help. Thanks in advance. > Dubal. From syver-en+usenet at online.no Thu Sep 19 14:51:17 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Thu, 19 Sep 2002 18:51:17 GMT Subject: Creating a typelibrary for calling Python COM server from c# References: Message-ID: "Dave Gustafson" writes: > There was a thread recently that suggested creating a typelibrary in > order > > to access a Python based COM server from C# (or .NET). Can anyone > please > > suggest an easy way to create such a library??? Create an .idl file. MSDN has resources for the syntax of this file. Run the midl compiler on the .idl file (midl.exe), this will generate a typelibrary (.tlb) file and c source and header files. If you don't have Visual Studio, I believe that you can get the midl compiler by downloading the Microsft Platform SDK (also on msdn). -- Vennlig hilsen Syver Enstad From k.robert at gmx.de Fri Sep 27 16:17:38 2002 From: k.robert at gmx.de (Robert) Date: Fri, 27 Sep 2002 22:17:38 +0200 Subject: http file upload from Python (multipart/formdata) how-to? References: <3d937091$0$181$9b622d9e@news.freenet.de> Message-ID: <3d957872$0$182$9b622d9e@news.freenet.de> "Tim Roberts" schrieb im Newsbeitrag news:ujp7pu4osgoagpnqr4ls727cibm2ua5jq1 at 4ax.com... > "Robert" wrote: > > >want to upload file data (multipart formdata) - same as upload from > >web-browser > > > >urllib.urlencode + urlopen takes only simple name/value tuples > > > >how do I render multipart formdata ? > > I guess you will have to generate the HTTP/MIME headers and send the file > in your own code. See RFC 1867. > > Are you trying to interface with a web form that already exists, or are you > just trying to do a file transfer from one machine to another? > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. yes think I have to render the RFC1867 HTTP/MIME headers manually and put it as 'data' parameter to urlopen. found no python code to do that upon the last google session. only strange perl hieroglyphs $%()%$//%=?!=... and I have no archeologist ;-) so I am still too lazy to read and implement the RFC and hope that somebody already had the same problem Robert From owen at nospam.invalid Mon Sep 16 13:01:39 2002 From: owen at nospam.invalid (Russell E. Owen) Date: Mon, 16 Sep 2002 10:01:39 -0700 Subject: Tkinter listbox clicking problem References: <2D7E3697CF5D1521.5D9711540E657ED8.7EF0451C598438FC@lp.airnews.net> Message-ID: That's odd, the first thing I looked for in Listbox when trying to answer the original poster's question was the ability to tag items, since binding events to tagged items would have been a good solution. I don't think items in a Listbox can be tagged. I fear I'm missing something, but I'm not sure what. (I imagine one could emulate a Listbox with a Text widget, tag each line and bind to those tags, but it sounds like a fair amount of work to get the selection behavior right.) Fortunately Eric Brunel's suggestion of binding to Button-Release will do the trick. This is the approach taken by Brian Welch in "Practical Programming in Tcl and Tk" (which is where I should have looked to start with). By the time the mouse button is released, you can safely query the list to ask it for the selection and it will match what the user sees. Admittedly the user may be more used to mouse down triggering actions, but that model just doesn't seem to mesh well with the standard bindings for Listbox. -- Russell >Whoa! There's a far easier solution. Read up on 'bindtags' >in and elsewhere. > has a small >example that almost is pertinent. From skip at pobox.com Thu Sep 26 15:43:58 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 26 Sep 2002 14:43:58 -0500 Subject: Strange change in xmlrpclib behavior In-Reply-To: <200209261857.g8QIvwY07046@universal.dca.net> References: <200209261857.g8QIvwY07046@universal.dca.net> Message-ID: <15763.25470.257583.225525@12-248-11-90.client.attbi.com> >>>>> "Walt" == Walt Leipold writes: Walt> Any ideas? (BTW, it's xmlrpclib v0.9.8, Win2000 SP2 and NT4 SP6.) Skip> Have you tried a more recent version of xmlrpclib and/or Python Skip> 2.2.1 or Python from CVS? Walt> I am now using Python 2.1.1, have tried xmlrpclib v0.9.9 without Walt> success, and I'm just about desperate enough to go to the Python Walt> CVS. I haven't moved to Python 2.2 because I'd have to rebuild my Walt> serial library (but I may have to do that). My thinking goes like this... Something had to have changed in your system for it to suddenly stop working. I briefly tried running your code on my Python CVS install here, but it failed because there is no xmlrpcserver module. (It's SimpleXMLRPCServer, and has a different API.) so, to debug this, either you have to move to a newer setup or I have to move to an older setup. Guess which one is not going to happen. Even if you don't deliver your software on a newer platform, installing Python 2.2.1 (which you can do alongside 2.1 on Windows I believe) and porting your example code to use SimpleXMLRPCServer then gives you access to a lot more people who can help debug your problem. Walt> However, what's *really* bugging me is that the code *used* to Walt> work; even if moving to a slightly newer version fixes it, how can Walt> I be sure it won't fail again? I shouldn't turn it over to my Walt> customer until I understand what broke it in the first place... Well, if it used to work, you changed nothing, and now it doesn't work, I'd guess there is some sort of undetected race condition present in your system. Walt> I'll probably end up junking XML-RPC and writing the socket code Walt> using UDP or something similar, just so I can trust it. Changing communication protocols without knowing that xmlrpclib is to blame won't make the problem go away. It might hide it, or it might solve the problem, but you won't know which. Skip From gua81 at XXXyahoo.com Tue Sep 24 03:40:21 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Tue, 24 Sep 2002 17:40:21 +1000 Subject: Python and cgi and problem! References: Message-ID: thanks dudes, everything works fine, im just doing some simple things, nothing that will break the code. Cheers. "Jon Ribbens" wrote in message news:slrnaovmel.dma.jon+usenet at snowy.squish.net... > In article , Chris Liechti wrote: > >>> print '%s' % (filename, filename) > >> > >> I hope none of your filenames have '"', ">" or "&" in. > > > > yeah i avoid characters that are special to the shell in my filenames - i > > even don't use " " very often. > > > > sure there are improvements, but its a start. > > I'm not sure recommending completely broken and insecure code is ever > a good thing. No offence intended. From g0w1s0 at yahoo.ca Sun Sep 1 22:22:00 2002 From: g0w1s0 at yahoo.ca (Cesar) Date: Sun, 01 Sep 2002 22:22:00 -0400 Subject: curses: AttributeError: initscr References: Message-ID: Cesar wrote: > > > I'm running python 1.5/2.2.1 under redhat linux 7.2. > > I'm trying to use the curses module like this : > > 1: import curses > 2: > 3: screen = curses.initscr() > 4: > > and I get this error msg: > > Traceback (innermost last): > File "./curses_test.py", line 6, in ? > screen = curses.initscr() > AttributeError: initscr > > any idea ?? the problem was stupid !!! in the same directory where my script live, there was an old file named curses.py. Then the instruction : "import curses" imported the bad one... I'm new to python.. so.. From marklists at mceahern.com Thu Sep 26 14:00:22 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 26 Sep 2002 13:00:22 -0500 Subject: design question In-Reply-To: Message-ID: [Gon?alo Rodrigues] > Well, I have thought that somewhere further down the way some (though > not all) of the wrapping code could be factored out in some kind of > metaclass, and then I would just set __metaclass__ at module level. But > since I am still at the entrance, I am kinda polling for ideas. > > Assuming that my description of the problem is enough, how would you go > about writing a metaclass as a general wrapper? Hey, no fair calling my bluff! For starters, please tell me how come this isn't sufficient: class Wrapper(object): def __init__(self, wrapped_class): self._wrapped_class = wrapped_class() def __getattribute__(self, name): if __debug__: print "calling __getattribute__(%s)" % name wrapped_class_attr_name = "_wrapped_class" wrapped_class = object.__getattribute__(self, wrapped_class_attr_name) if name == wrapped_class_attr_name: return wrapped_class else: return getattr(wrapped_class, name) def __setattr__(self, name, value): if __debug__: print "calling __setattr__(%s, %s)" % (name, value) wrapped_class_attr_name = "_wrapped_class" if name == wrapped_class_attr_name: object.__setattr__(self, name, value) else: setattr(self._wrapped_class, name, value) // m From bogle at ihug.co.nz Sat Sep 7 20:40:55 2002 From: bogle at ihug.co.nz (Gib Bogle) Date: Sun, 08 Sep 2002 12:40:55 +1200 Subject: Python from C/SDL References: <3D793B29.3198AB0E@ihug.co.nz> <006101c25626$56c9b1c0$0101010a@local> Message-ID: <3D7A9C97.C5FD0817@ihug.co.nz> Mike, Thanks very much for such a detailed response. My programming skills are a bit out of date (little OO experience, no C++, no Python) so what is required here might be a bit of a stretch. I have sent a message to Warren Delano (pymol author) to see if he is interested in giving some assistance. If not I'll probably put this on the back burner until I have the time to teach myself the basics of Python. I have been aware of it for a couple of years now, and if I was 20 years younger ... regards Gib "Mike C. Fletcher" wrote: > > I'll just deal with the OpenGL stuff. Basically, PyOpenGL-based apps > should be able to work like this: > > c draw(): > context = new MyContext; > context.set_current(); > err = Py*_Call*( size ); > > python: > def render( dimensions ): > do_your_rendering_here() > return > > c: > swap_buffers(); > context.unset_current(); > > So, you'd likely need to find, somewhere in pymol, a function to call > which is _after_ the Python context setup and set_current() which you > can call. Depending on the architecture of pymol, that's likely to > require at least sub-classing, and possibly some re-writing, as most > rendering libs go out of their way to be sure they're using the "right" > context before any attempt to render, and most apps assume they'll be > using a context they set up. You'll likely need to pass size of the > window from your code, as some renderers assume they know the current > size of the rendering context (which they won't if they aren't getting > their resize events). > > For example, in OpenGLContext, you'd subclass a Context and override > setCurrent and unsetCurrent to do nothing (or more professionally, you'd > create C "extending" functions that set the appropriate context for your > app, which would allow the Python system to have its own contexts > alongside yours if you wished). In other frameworks those calls aren't > actually split out into easily overridable methods (it's only required > if you're targetting multiple GUI libs), so you might have to re-write > anywhere you see "set current" methods called. Would suggest > contacting the creator of PyMol for suggestions where to apply your lever. > > For a "full" job of creating a PyOpenGL embedded system, you'd also > provide initialisation/creation functions to allow Python code to create > a context within your app (e.g. setting display modes). > > There are similar questions asked once in a while, but not particularly > with pymol AFAIK. "How do I embed PyOpenGL apps" is the basic template. > Suppose I should create a tutorial for it, but I've never done it > directly myself (though conceptually every context in OpenGLContext is > "embedded" in the GUI library it uses, since those are all C libs, it's > just that I do the "calling into Python" from the libs own Python wrappers). > > HTH, > Mike > BTW: out of town in a few minutes, so won't be available to clarify > anything 'til Monday, sorry. > > Chris Gonnerman wrote: > > ----- Original Message ----- > > From: "Gib Bogle" > > > > > >>Hi, > >> > >>I am a complete beginner with Python. My interest in it is focussed on > >>a great piece of open-source software called pymol, a system for > >>visualization of molecules that uses Python and OpenGL. I'd like to get > >>access to pymol's graphical functions from my own program, which is > >>built from C, SDL and OpenGL. > > > ... > >>I will not want to use the GUI at all. SDL would > >>create the surface(s), and handle the buffer swapping. My goal is to be > >>able to send a request to the pymol API asking for a frustum view to be > >>rendered on the provided surface. > >> > >>Sorry if my question is one that gets asked and answered frequently. If > >>there is a place where this has been dealt with please direct me. > > > > > > Never heard this one before... > > > > Good luck! > > > > > > Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net > > http://newcenturycomputers.net > > > > > > -- > _______________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://members.rogers.com/mcfletch/ -- -------------------------------------------- Gib Bogle bogle at ihug.co.nz 1/44 Arthur St Tel: (64-9) 525-6878 Ellerslie, N.Z. Fax: (64-9) 525-6878 -------------------------------------------- From bokr at oz.net Sat Sep 7 13:48:11 2002 From: bokr at oz.net (Bengt Richter) Date: 7 Sep 2002 17:48:11 GMT Subject: Interrupting Python References: <3d796d22@news.sentex.net> Message-ID: On Sat, 7 Sep 2002 06:32:24 -0400, "Bob Easton" wrote: >Yes Peter, it makes sense that PythonWin works that way by design. You are >also right about running from the command prompt after development/debug is >done. > >For this particular program, using a file semaphore is ideal since I can >place it at the right point in the program to enable easy restart, something >not easily done with the random ctrl-break. You can place a test for Ctrl-C and/or Ctrl-Break at "the right point"(s) in your program. See below. > >Thanks to all who helped clear the fog for me. > >-- >Bob Easton > > >"Peter Hansen" wrote in message >news:3d796d22 at news.sentex.net... >> Bob Easton wrote: >> > Using catchCtlC.py in a command line environment works as you expect. >When I >> > hit Ctrl-Break, Windows displays "^C" and then a command prompt. If I >hit >> > Ctrl-C, the exception handler catches it and displays the results as >> > specified in catchCtlC/py >> > >> > However, my preferred execution environment is PythonWin, not a command >> > prompt. There, neither Ctrl-break, not Ctrl-C have any effect. That >could >> > easily be a bug with PythonWin. >> >> Not a bug, I think. The whole Ctrl-C/Ctrl-Break concept is only >> meaningful for command-line ("console") programs, not GUI apps. >> I don't use PythonWin, but my guess is it does not bother passing >> ctrl-c on to the application, possibly by design. >> >> Can't you just run it under the console? What advantages do >> you find by running it under PythonWin other than during >> development? >> >> Also, have you looked at the msvcrt module and kbhit() ? >> >> -Peter >> > ---< interruptpy.py >------ #!/usr/bin/python def test(): import sys, signal class SigHandler: def __init__(self): self.signaled = 0 self.sn=None def __call__(self, sn, sf): self.sn = sn self.signaled += 1 sh = SigHandler() old_SIGINT_Handler = signal.signal(signal.SIGINT,sh) old_SIGBREAK_Handler = signal.signal(signal.SIGBREAK,sh) signames = { signal.SIGINT:'SIGINT', signal.SIGBREAK:'SIGBREAK' } print 'Type Ctrl-C or Ctrl-Break to stop' while not sh.signaled: # put this condition in your program loop pass # (loop body) print 'Interrupted loop with %s (not via exception).' % signames[sh.sn] signal.signal(signal.SIGINT,old_SIGINT_Handler) signal.signal(signal.SIGBREAK,old_SIGBREAK_Handler) if __name__ == '__main__': test() --------------------------- >>> from interruptpy import test >>> test() Type Ctrl-C or Ctrl-Break to stop Interrupted loop with SIGINT (not via exception). >>> test() # now I'll do ctrl-break Type Ctrl-C or Ctrl-Break to stop Interrupted loop with SIGBREAK (not via exception). >>> ^Z [10:55] C:\pywk\pi>interruptpy.py Type Ctrl-C or Ctrl-Break to stop Interrupted loop with SIGINT (not via exception). [10:55] C:\pywk\pi>interruptpy.py Type Ctrl-C or Ctrl-Break to stop Interrupted loop with SIGBREAK (not via exception). Obviously you could sprinkle various tests of sh.signaled into various parts of your code, to check-point variously. You could resond differently to Ctrl-C vs Ctrl-Break also. The above is on NT4 Python 2.2 BTW. BTW2, I suspect I am not the only one who will appreciate it if you decide to adopt usual ng conventions, and discontinue top-posting. Consider it a virtual beer for those who paid attention to your posts anyway ;-) Regards, Bengt Richter From fb at frank-buss.de Sun Sep 1 13:47:34 2002 From: fb at frank-buss.de (Frank Buss) Date: Sun, 1 Sep 2002 17:47:34 +0000 (UTC) Subject: A "for" with "list" question. References: <3b55ea60.0208311330.4608ae71@posting.google.com> Message-ID: BTW: If you want the second case, only, you can write: >>> from operator import xor >>> a = [0, 1, 2] >>> b = [1, 2, 3] >>> [item for item in a + b if xor(item in a, item in b)] [0, 3] -- Frank Bu?, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From robin at jessikat.fsnet.co.uk Mon Sep 16 11:52:42 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Mon, 16 Sep 2002 16:52:42 +0100 Subject: pyro & parallel processing Message-ID: Has anyone used pyro to do symmetric parallel processing. The pyro framework is nice with master slave type applications, but the remote objects don't seem to be able to message back to their invoker. I thought I'd ask if any one has got pyro to work in a more symmetric way? -- Robin Becker From martin at v.loewis.de Tue Sep 17 01:55:22 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Sep 2002 07:55:22 +0200 Subject: More on Protecting Source Code References: Message-ID: "David LeBlanc" writes: > * Owners of property have the right to control it. If you disagree and own a > nice car or house, I'll be right over :-> What are you protecting your car against? Somebody taking it and using it without your permission, right? Not against somebody analysing it and building a similar car. That would be for the car makers to protect; I believe they don't protect it by technical means against a determined engineer. Instead, they protect it with patents and trademarks (and, admittedly, by the fact that you need significant facilities to copy a car). For software, I think the economical risk is that somebody uses your software without giving you the money you want - not that somebody sits down and studies your code for days, to write a program that he could have written himself from scratch in the same time. Regards, Martin From jonathan at onegoodidea.com Sun Sep 29 05:43:59 2002 From: jonathan at onegoodidea.com (Jonathan Hogg) Date: Sun, 29 Sep 2002 10:43:59 +0100 Subject: [Mac] Editor on Macintosh? References: <1fj7za2.1erbqps1uvzpj8N%news@agapow.net> Message-ID: On 28/9/2002 12:19, in article 1fj7za2.1erbqps1uvzpj8N%news at agapow.net, "Paul-Michael Agapow" wrote: > Sadly, it seems like the excellent editor Pepper is going away. (See > .) I found it the best editor for Python on > the Macintosh, having never been really happy with the alternatives. > > So what are other MacPython using? There are some Java-based editors, > but I'm not persuaded that that they'll perform adequately. There's are > numerous X11 based options, but who wants to swap into X everytime they > need to edit a file? The once excellent editor Alpha seems to have > disappeared permanently into testing for its next release. I'm quite happy with BBEdit. One feature I'm growing particularly fond of is the new worksheet windows. These are like MPW worksheets if you're familiar with MPW (Ah! thems were the days). Basically you get an editor window that has a live shell underneath it. By hitting the ENTER key instead of return, the last line typed (or currently selected text) is executed and the stdout inserted at the cursor point in the window. This isn't so useful for very interactive stuff and I wouldn't use it as a substitute for a terminal window, but for recording and monitoring the output of programs it's fantastic. Basically I open a new worksheet window and type something like this at the top: cd /to/project/directory ./start-program --non-interactive --with-lots-of-debugging-output Then I just select the lines, hit ENTER, and watch the output fill the window. Then I can scroll up and down and use BBEdit's grep searching facilities on the output as it's running. Yes, I'm sure Emacs can do all of this, but I don't want a terminal-based editor pretending to be a GUI application. Oh, another thing. BBEdit has a command-line tool now for firing up the editor allowing you to type: % bbedit foo.py bar.py and have them open up in BBEdit. Jonathan (no stock options, just a happy user) From gumuz at looze.net Tue Sep 3 09:25:04 2002 From: gumuz at looze.net (Gumuz) Date: Tue, 3 Sep 2002 15:25:04 +0200 Subject: How to avoid freeing memory on exit? References: Message-ID: <3d74b6dc$0$231$4d4ebb8e@news.nl.uu.net> so what does 'one' underscore prefixing a methodname mean? "Gerhard H?ring" wrote in message news:slrnan9dhv.1vs.gerhard.haering at haering.opus-gmbh.net... > Roy Smith wrote: > > [...] Is there any way to get the interpreter to just exit without doing all > > that memory cleanup? > > os._exit > > -- Gerhard From leipold at universal.dca.net Thu Sep 26 14:57:58 2002 From: leipold at universal.dca.net (Walt Leipold) Date: Thu, 26 Sep 2002 14:57:58 -0400 (EDT) Subject: Strange change in xmlrpclib behavior Message-ID: <200209261857.g8QIvwY07046@universal.dca.net> Skip: > Walt> Any ideas? (BTW, it's xmlrpclib v0.9.8, Win2000 SP2 and NT4 SP6.) > > Have you tried a more recent version of xmlrpclib and/or Python 2.2.1 or > Python from CVS? I am now using Python 2.1.1, have tried xmlrpclib v0.9.9 without success, and I'm just about desperate enough to go to the Python CVS. I haven't moved to Python 2.2 because I'd have to rebuild my serial library (but I may have to do that). However, what's *really* bugging me is that the code *used* to work; even if moving to a slightly newer version fixes it, how can I be sure it won't fail again? I shouldn't turn it over to my customer until I understand what broke it in the first place... I'll probably end up junking XML-RPC and writing the socket code using UDP or something similar, just so I can trust it. Regards, -- Walt ------------------------------------------------------------------ "If ignorance is bliss, why Walt Leipold aren't there more happy people?" leipold at acm.org ------------------------------------------------------------------ From sholden at holdenweb.com Mon Sep 9 15:59:08 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 9 Sep 2002 15:59:08 -0400 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> Message-ID: "Stephen Ferg" wrote in message news:b16e4ef7.0209090552.3ad7691b at posting.google.com... > > you'd better include a clear warning... > > that you'll explain how to do it correctly > > later... > > Can you say a little more? What is it that makes using "bind()" > incorrect? And what is it about using "command" that avoids the > problems? > > This is a genuine request for information, not a challenge to your > statement. I am still learning about Tkinter features. The problem, from a learner's point of view, is that most Tkinter widgets need to be bound to a number of different events. Consider, for example, how the default button in an interface is triggered by an Enter keystroke. The command option is specifically provided to allow the programmer to hook their code in whenever any relevant bound event triggers that widget in the interface. Consequently, which bind() is a valuable technique for Tkinter programmers to know about, it's rather like teaching someone to drive by explaining the mechanical details of the steering and engine. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From david.abrahams at rcn.com Thu Sep 12 00:36:38 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Thu, 12 Sep 2002 00:36:38 -0400 Subject: Any C++/Python sig members here? References: Message-ID: "Robert Oschler" wrote in message news:l1Kf9.1470$Lg2.157618 at news2.news.adelphia.net... > I joined the C++ sig for Python, to talk with others about BoostPython. I > joined more than a day ago and got my subscription confirmation request from > the sig server. I have not seen any messages yet, is it a very low traffic > sig or something? See http://mail.python.org/pipermail/c++-sig/ To answer your question from http://mail.python.org/pipermail/c++-sig/2002-September/002055.html: Yes, Boost.Python works on Linux. See a list of supported platforms and compilers for Boost.Python v1 at www.boost.org/libs/python/doc/index.html. Boost.Python v2 is compatible with even more platforms and compilers. -Dave -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From hst at empolis.co.uk Mon Sep 9 10:39:45 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Mon, 9 Sep 2002 15:39:45 +0100 Subject: xml.minidom is stripping out my CRLF's in attrib values!! Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F412@hendrix.empolisuk.com> sismex01 at hebmex.com wrote: > > Probably not sripped, but normalized: > > for example, your original string: > >>> s = "spotted\x0Awith black and white" > > becomes the normalized string: > >>> s = "spotted with black and white" > > Is something like this happening? > > If it is, then it's the correct behaviour, according > to the XML standard: all text should be normalized, > except if it's in a CDATA block. > > HTH > > -gus White space is usually normalized, but it can be preserved (if your parser supports it) with the xml:space attribute. If an element has the attribute xml:space="preserve" then white space in that element should not be normalized. If you are parsng with a DTD and your root element is called ROOT then change/create the !ATTLIST declaration to be _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From andrew.henshaw at mail.com Wed Sep 11 08:34:42 2002 From: andrew.henshaw at mail.com (Andrew Henshaw) Date: Wed, 11 Sep 2002 08:34:42 -0400 Subject: deleting the first and the last character of a string References: Message-ID: Manuel Hendel wrote: > I got a file with fields seperated by a "|". The problem is that there > is also a "|" at the beginning and at the end of each line although > there no fields in front or behind these "|". Now I want to delete > these two "|". Is there anything which says delete the first or last > character of a string? I checked the string module on the web, but I > couldn't find anything. > > I solved it like this, but I honestly don't like it that way. > > #!/usr/bin/env python > # > import sys > import string > > inputfile = open(sys.argv[-1], "r") > > for line in inputfile.readlines(): > fields = string.split(line, "|") > lineN = string.join(fields[1:-1], "|") > > Isn't there any better solution? ;-) > > Manuel > Just like your slicing of the list, you can slice a string: string[1:-1] Although, I believe that each of your strings will have a \n that needs to be deleted; therefore, string[1:-2] -- Andrew Henshaw From sadams123 at optushome.com.au Mon Sep 16 21:03:09 2002 From: sadams123 at optushome.com.au (Steven) Date: Tue, 17 Sep 2002 11:03:09 +1000 Subject: Source code References: Message-ID: <3d867f4d$0$23173$afc38c87@news.optusnet.com.au> > > This question ("how can I obscure Python byte-code?") comes up at least > > once a month on this list. It's fairly clear that any scheme you come > > up with will take longer to implement than it will to break by a > > competent hacker. > > True.. that's why I'm planning to obfuscate the code then encrypt it. you don't want to go overboard with this, people still have to use the program - where are you going to keep the code that is 'now' (once decrypted) in plaintext? At some stage your code must be in the clear, and at that stage, anyone can get at it. e.g. running it on linux, just start it up, get past whatever encryption you've put on there, when the program is running - and you've either got unencrypted files sittng on disk, or, (you decideed to be tricky and keep it all in memory) just 'cat /proc/kcore > some_file.txt' and you've got a complete memory dump to look through. As everyone has said, you're running against diminishing returns on any security through obscurity. > A hacker (not every programmer) is specialized in modify jmp instructions > and could find the password > to decrypt the .pyc in less than 20 minutes, but maybe 5% of them knows > about python. if they're able to run the code, it'd be a fairly solid bet that they'd know about Python, if not, a quick search on Google would probaly net you all the info you need to find out just what that file is. After all, in order to run the program they'd need to at least install Python somehow - unless you're planning to embed Python in some other app, and run your code in that... I'd say, don't bother, copyright it, and only distribute the compiled python files under a restrictive license. Steven From jorgenhansen at hotmail.com Thu Sep 5 03:25:20 2002 From: jorgenhansen at hotmail.com (=?ISO-8859-1?Q?J=F8rgen_Hansen?=) Date: 5 Sep 2002 00:25:20 -0700 Subject: Max line coords canvas.create_line() can display? References: <5pid9.5885$e5.1033551@newsb.telia.net> Message-ID: <117880a1.0209042325.68193ca7@posting.google.com> "Fredrik Lundh" wrote in message news:<5pid9.5885$e5.1033551 at newsb.telia.net>... > "revyakin" wrote: > > > Is there a limit of line coords (x1,y1,...xn,yn) which a Tk Canvas > > create_line method can display? I found that I can display a line > > consisting of 5000 x,y points, but a line of 20 000 points does not > > get displayed. > > there shouldn't be a limit. > > can you perhaps post a (short) code snippet that illustrates > the problem? Hi the small program below fails to draw the line, when it is called with an integer larger than or equal to 16384. I only tested the script on a Windows 98 machine with Python 2.1.3. Regards Jorgen --- Code start --- import random, sys from Tkinter import * WIDTH = 300 HEIGHT = 200 def randomcoor(n, xmin, xmax, ymin, ymax): """ Generate n sets of random coordinates within the bounds. """ x = [] y = [] for i in range(n): x.append(random.randrange(xmin, xmax, 1)) y.append(random.randrange(ymin, ymax, 1)) return zip(x,y) def draw(coor): """ Draw a line for the list of coordinates. """ root = Tk() canvas = Canvas(root, width=WIDTH, height=HEIGHT) canvas.pack() canvas.create_line(coor) root.mainloop() if __name__ == '__main__': """ Call the script with an integer number. """ coor = randomcoor(int(sys.argv[1]), 0, WIDTH-1, 0, HEIGHT-1) draw(coor) --- code end --- From tim.one at comcast.net Fri Sep 20 03:13:52 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 20 Sep 2002 03:13:52 -0400 Subject: Destructor never called ??? In-Reply-To: Message-ID: [Aahz] > There are several different issues. First of all, __del__ does not get > called if an object is destroyed by GC (GC gets used to clean up cyclic > garbage). If an object is destroyed by GC, and the object has a __del__, the __del__ is called. >>> class adel: ... def __del__(self): ... print "I've been del'ed!" ... >>> class nodel: ... pass ... >>> A = nodel() >>> B = nodel() >>> C = adel() >>> A.B = B # half of a cycle >>> B.A = A # the other half >>> A.C = C # C is not in the cycle, but ... >>> B.C = C # ... will become reachable only from the cycle >>> del C # can only get to C via the cycle now >>> del A # break half the cycle >>> del B # break the other half >>> import gc >>> gc.collect() # force a collection I've been del'ed! 4 >>> What is true is that if an object *in* a trash cycle has a __del__, that cycle will not be collected, but rather shuffled into gc.garbage for the programmer to do something sane with it explicitly. There may be any number of objects with __del__s not in cycles themselves but reachable only from cycles; they don't inhibit collection, and if collection occurs their __del__s will be invoked. It's only the cases where Python can't possibly guess a safe order in which to call destructors where both __del__ and collection are inhibited. __del__-and-gc-go-together-like-windows-and-fork-ly y'rs - tim From emile at fenx.com Sun Sep 1 12:55:04 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 1 Sep 2002 09:55:04 -0700 Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: "Gerhard H?ring" wrote in message news:slrnan4dl3.18h.gerhard.haering at lilith.my-fqdn.de... > Robert Oschler wrote in comp.lang.python: > > [Glyph said:] > > "One of the eye-popping cool features of Python is the ability to > > change code and have existing instances update to use the new > > methods automatically. " > > > > Can someone point me to a code snippet shows how to do this? > > >>> class Foo: pass > ... > >>> foo = Foo() > >>> foo.bar() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: Foo instance has no attribute 'bar' > >>> def bar(self): print "bar" > ... > >>> Foo.bar = bar > >>> foo.bar() > bar > You can also use new.instancemethod to add a method to an specific instance: Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> class Foo: pass ... >>> foo=Foo() >>> fee=Foo() >>> def bar(self): print 'bar' ... >>> import new >>> fee.bar = new.instancemethod(bar, fee, Foo) >>> fee.bar >>> fee.bar() bar >>> foo.bar Traceback (most recent call last): File "", line 1, in ? AttributeError: Foo instance has no attribute 'bar' Emile van Sebille emile at fenx.com From lordmacro at hotmail.com Sat Sep 21 03:09:19 2002 From: lordmacro at hotmail.com (Tom Widrick) Date: Sat, 21 Sep 2002 02:09:19 -0500 Subject: implementing reduce protocol in C References: <3D8A7DA1.7090506@hotmail.com> <62Ai9.136323$pX1.4852975@news2.tin.it> <3D8AF51D.5040305@hotmail.com> Message-ID: Well, I finally got it working with a small amount of contortion. I made an init function for pickle support, called from my module init static void initpickle() { PyObject *builtins, *globals, *build, *copy_reg, *constructor; /* register the proto builder for cPickle */ globals = PyEval_GetGlobals(); if(globals == NULL) return; builtins = PyDict_GetItemString(globals, "__builtins__"); if(builtins == NULL) return; builtins = PyModule_GetDict(builtins); build = Py_FindMethod(mod_methodlist, NULL, "__proto_build__"); copy_reg = PyImport_ImportModule("copy_reg"); constructor = PyDict_GetItemString(PyModule_GetDict(copy_reg), "constructor"); PyObject_CallFunction(constructor, "(O)", build); PyDict_SetItemString(builtins, "__proto_build__", build); } The trick was that I had to make a file-level variable to hold the module object and get the function from it in my reduce function, not Py_FindMethod(). I'm still trying to learn about the internal workings of Python, but it seems that the function object is "changed" when the module is initialized. static PyObject * proto_reduce(HyProtoObject *self) { PyObject *args; PyObject *result; PyObject *builder; if(HyProtoModule == NULL || !PyModule_Check(HyProtoModule)) Py_FatalError("proto extension module not initialized properly."); builder = PyDict_GetItemString(PyModule_GetDict(HyProtoModule), "__proto_build__"); args = PyTuple_New(5); if(args == NULL) return NULL; PyTuple_SET_ITEM(args, 0, self->po_name); Py_INCREF(self->po_name); PyTuple_SET_ITEM(args, 1, self->po_parents); Py_INCREF(self->po_parents); PyTuple_SET_ITEM(args, 2, self->po_children); Py_INCREF(self->po_children); PyTuple_SET_ITEM(args, 3, self->po_doc); Py_INCREF(self->po_doc); PyTuple_SET_ITEM(args, 4, self->po_dict); Py_INCREF(self->po_dict); result = Py_BuildValue("(OO)", builder, args); Py_DECREF(args); return result; }; Who knows if this is "proper" but it works. Tom From michael at stroeder.com Tue Sep 24 12:53:50 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 24 Sep 2002 18:53:50 +0200 Subject: Strange values in Accept-Language header? References: <8FWj9.39597$V7.10466682@twister.socal.rr.com> Message-ID: Alan Kennedy wrote: > Accept-Language: x-ns16W5tM7A2Nh6,x-ns2U210btwUq5f > Accept-Language: en-us,x-ns1jZKcD2t3NhQ,x-ns2r3509OnmPe2 For what it's worth: Python 2.2.1 (#2, May 4 2002, 19:50:26) Type "help", "copyright", "credits" or "license" for more information. >>> import base64 >>> base64.decodestring('ns16W5tM7A2Nh6') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/base64.py", line 44, in decodestring return binascii.a2b_base64(s) binascii.Error: Incorrect padding >>> base64.decodestring('16W5tM7A2Nh6') '\xd7\xa5\xb9\xb4\xce\xc0\xd8\xd8z' >>> base64.decodestring('s16W5tM7A2Nh6') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/base64.py", line 44, in decodestring return binascii.a2b_base64(s) binascii.Error: Incorrect padding >>> base64.decodestring('16W5tM7A2Nh6') '\xd7\xa5\xb9\xb4\xce\xc0\xd8\xd8z' >>> base64.decodestring('2U210btwUq5f') '\xd9M\xb5\xd1\xbbpR\xae_' >>> ... Ciao, Michael. From phr-n2002b at NOSPAMnightsong.com Sun Sep 29 19:14:20 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 29 Sep 2002 16:14:20 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> "Chris Gonnerman" writes: > >>> .70 * .05 > 0.034999999999999996 > > Rounded to two decimals, that's 0.03; but done in proper > decimal numbers, the answer should be 0.035, rounded to 0.04 > using either "classic" or "banker's" decimal rounding. > ... > So, Bengt, how do I do this right using only floats? I can't. > I have to have decimal arithmetic to get the right answer. How about just adding a small amount before rounding at the end? >>> (.70 * .05) + .000000001 rounds to the right thing. From a at b.c Tue Sep 24 21:41:36 2002 From: a at b.c (Daniel T.) Date: Wed, 25 Sep 2002 01:41:36 GMT Subject: Tkinter status bar? Message-ID: I'm going through a pdf file I found on the internet ("An Introduction to Tkinter" by Fredrik Lundh) In chapter 8 he talks about how to put a status bar at the bottom of a window: # File: tkSimpleStatusBar.py class StatusBar(Frame): def __init__(self, master): Frame.__init__(self, master) self.label = Label(self, bd=1, relief=SUNKEN, anchor=W) self.label.pack(fill=X) def set(self, format, *args): self.label.config(text=format % args) self.label.update_idletasks() def clear(self): self.label.config(text="") self.label.update_idletasks() He goes on to say: We could have inherited from the Label widget itself, and just extended it with set and clear methods. This approach have a few drawbacks, though: * It makes it harder to maintain the status bar's integrity. Some team members may cheat, and use config instead of set. That's not a big deal, until the day you decide to do some extra processing in the set method. Or the day you decide to use a Canvas widget to implement a fancier status bar. * It increases the risk that your additional methods conflict with attributes or methods used by Tkinter. While the Frame and Toplevel widgets have relatively few methods, other widgets can have several dozens of widget specific attributes and methods. * Future versions of Tkinter may use factory functions rather than class constructors for most widgets. However, it's more or less guaranteed that such versions will still provide Frame and Toplevel classes. Better safe than sorry, in other words. Now my question. I didn't think to inherit from Label, instead I changed it to: class StatusBar: def __init__(self, master): self.label = Label(master, text="", bd=1, relief=SUNKEN, anchor=W) self.label.pack(side=BOTTOM, fill=X) def set(self, format, *args): self.label.config(text=format % args) self.label.update_idletasks() def clear(self): self.label.config(text="") self.label.update_idletasks() In other words, why inherit from any of the Tkinter classes? From bobx at linuxmail.org Mon Sep 16 21:30:35 2002 From: bobx at linuxmail.org (Bob X) Date: Tue, 17 Sep 2002 01:30:35 GMT Subject: Python equivalent to perldoc? References: Message-ID: <%Avh9.7933$Lg2.1392332@news2.news.adelphia.net> Bob X wrote: > In Perl you can run "perldoc warnings" and get the definition of what > "warnings" does. Is there a equivalent in Python? > Well...I found "pydoc". However I have to explicitly tell python to execute it on Windows XP. I cannot type "pydoc sys" nor "python pydoc sys" but I have to type "c:\python22\libs\pydoc sys" to get it to work. Shouldn't Python know its own libs? Or at least put the "libs" in the ENV variable? Bob From jb at cascade-sys.com Fri Sep 27 05:19:22 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 27 Sep 2002 02:19:22 -0700 Subject: Getting started References: <00a801c26511$4e084750$df7e4e18@brianspiv1700> Message-ID: <3D94229A.6030207@cascade-sys.com> Alex Martelli wrote: >James J. Besemer wrote: > ... > > >>Types are otherwise pretty secure in C++ except the "cast" mechanism >>"foils" the type system and thus allows type errors to occur. >> >> > >Actually, unions are at least as bad -- they're not often used >for type-punning because casts are handier for that, but if you >took cast aways, people would (ab-)use unions (just like they >abuse EQUIVALENCE in Fortran for similar purposes). > You're right. I didn't mean to suggest that casts were the only thing that could make C++ programs type unsafe. Should have inserted an "e.g.," in the sentence, as it was intended only as an example. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From jb at cascade-sys.com Tue Sep 17 01:48:40 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Mon, 16 Sep 2002 22:48:40 -0700 Subject: threads or queue for this task References: Message-ID: <3D86C238.9040306@cascade-sys.com> Alex Martelli wrote: >James J. Besemer wrote: > > >>Generally, Queues never get "full" and you generally don't care if >>they're empty. >> >> > >You can define Queues that can hold a maximum number of items; [...] > >Setting size is just an optional embellishment, though >sometimes it does pay dividends. > Setting size has it's place but otherwise introduces unnecessary complications. Among other things, it forces the queue writer to deal with the situation of what to do if the queue is full. Signal error back to its client? Sleep and try again later? Silently discard the request? Abort? "Generally," NOT having a limit is by far the more elegant solution. Even in the general case, the queue may eventually grow to consume all available memory if one doesn't have the CPU power to keep up with requests. But, like most Python errors, this eventually will raise a specific exception. Anyway, I felt the "general" case was more applicable to this novice's line of questioning. He/she already was confounded by some non-essential details. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From lyle at users.sourceforge.net Mon Sep 9 14:34:35 2002 From: lyle at users.sourceforge.net (Lyle Johnson) Date: Mon, 09 Sep 2002 13:34:35 -0500 Subject: compile error on SWIG file References: <3D7C55EE.D9278B1C@ipm.fhg.de> <3D7CB26B.2040706@users.sourceforge.net> <3D7CBFD2.4E7DFD1F@ipm.fhg.de> Message-ID: <3D7CE9BB.7030703@users.sourceforge.net> Markus von Ehr wrote: > I only extended the std_vector example from the distribution with > one function, see example.i included (there are templates inside). > When I run SWIG with -c++ option, the warnings disappear in fact. > But the error from the compiler is the same... If you named the output file "mvelib.c", you are telling your compiler that it's C source code (and it isn't). It's C++ source code, so give it a C++ extension, e.g. swig -c++ -python -o mvelib.cpp mvelib.i You will also need to update your setup.py script to use the corrected file name ("mvelib.cpp" instead of "mvelib.c"). Lyle From buzzard at urubu.freeserve.co.uk Thu Sep 26 20:47:02 2002 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 27 Sep 2002 01:47:02 +0100 Subject: This is driving me insane! References: Message-ID: "Derek Basch" wrote in message news:mailman.1033084697.25598.python-list at python.org... > Hello, > I created a very simple class that totals some data > but I am not getting the output from it that I would > expect at all. > Here is the class: > http://www.geocities.com/dbasch/insane.txt > > I would expect to get: > [0, 0] > [0, 0] > [[0, 0]] > > but I am getting: > [0, 0] > [0, 0] > [[1, 1]] > > I dont understand how the 'grouptotals' list is > getting the incremented values prior to the > 'grouptotalcounter' function being called. It isn't. self.errorlog is a list containing self.grouptotals. When you increment self.grouptotals and return self.errorlog you will get [[1,1]]. Changing the appropriate line to 'self.errorlog.append(self.grouptotals[:])' will append a copy of self.grouptotals and your function will then return [[0,0]]. Duncan From alanmk at hotmail.com Fri Sep 27 06:41:14 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: 27 Sep 2002 03:41:14 -0700 Subject: Integrate with Flash MX References: <322e5959.0209261444.797a936e@posting.google.com> Message-ID: Peter Bengtsson wrote: > I want to use Flash MX to build a GUI for use on the desktop on > windows, not embedded in a webpage. > ActionScripts don't do it for me so I want to use Python for the > business logic. > > Is there some way to enable this connection? Maybe this is more of a > Flash question. Hmm, I haven't actually done this, but there are two possible approaches I can think of. Method 1. Use the python win32 extensions to control the Flash Player COM object directly. You create the COM object as follows code---- import from win32com.client import Dispatch fl = Dispatch('ShockwaveFlash.ShockwaveFlash.6') code---- >From now you control the Flash COM object 'fl' from python. I don't know what the methods of the Flash COM object are, nor do I know a reference where you can find them. If you do come across such a reference, I'd love to hear about it. Also, I'm not sure how you would achieve interaction between the UI elements in the Flash movie and your python objects. I'm not sure if this can be done without resorting to ActionScript. I suppose it depends on the interface presented by the Flash COM object. The nature of the communication *should* be similar to the two-way communication between DHTML scripting languages and Flash which is described below. Method 2. I know you said that you don't want to embed the GUI inside a web page. However doing that would make you task so very much simpler, that it might be worth considering. Also, perhaps it might be possible to control Internet Explorer behind the scenes with win32com? Embed the Flash movie representing your GUI inside a HTML page, and use Internet Explorer as the "intermediator" between your Flash GUI and your python logic. On the Python side, you write your Python as a DHTML scripting language. The Python win32 extensions permit you to do this. I think it goes something like On the Flash side, you will need to use "fscommand"s to communicate out to the (D)HTML thatr contains your python objects. For an example of this kind of communication, see the following Macromedia reference. Wherever you see "Javascript", substitute that for "PythonScript", i.e. Python running as a DHTML scripting language. http://www.macromedia.com/support/flash/ts/documents/java_script_comm.htm > Anybody got any experience with this? Sorry, it's an unusual approach that you're using, i.e. integrating python and Flash. I've never even considered it (until now), let alone implemented it. I've never heard of anyone doing it. Is there any particular reason why you don't like ActionScript? I know version 4 was fairly limiting, but version 5 has really cleaned up the language a lot, and you can achieve quite a bit. I'd love to know how you get on with this. Best of luck, alan kennedy ---------------------------------------------- check http headers here: xhaus.com/headers email alan: xhaus.com/mailto/alan From jimt at aiinet.com Tue Sep 10 13:27:38 2002 From: jimt at aiinet.com (Jim Taylor) Date: Tue, 10 Sep 2002 13:27:38 -0400 Subject: shared libraries Message-ID: Host: Solaris 2.5.1 Compiler: gcc 2.95 Problem: When Python loads the extension and the module goes to create the method table by calling Py_InitModule(), the information passed as parameters is not correct. I end up getting an address out of bounds error. Compilation of the module is done with: gcc -shared -fPIC -DPIC -I/usr/local/python1.5/SunOS5/include/python1.5 -I/ core -I. -c -o ctlr.o ctlr.c gcc -lposix4 -G -Xlinker --export-dynamic -shared -o ctlr.so ctlr.o The loader is loading the module, however, during the init function when Py_InitModule() is called, a segmentation fault occurs indicating an address out of bounds error. When I try to print the contents of the module table from within the initialization function, I also get a segmentation fault, so the problem is the way in which the module has been loaded. It appears there is an address space issue, but I don't know how to resolve it. Ideas anyone? Thanks Jim Taylor jimt at aiinet.com From gerhard.haering at gmx.de Tue Sep 10 13:09:02 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 10 Sep 2002 17:09:02 GMT Subject: Trouble upgrading to 2.2.1 References: <_qpf9.29862$w51.7937790@news2.news.adelphia.net> Message-ID: Robert Oschler wrote in comp.lang.python: > "Gerhard H?ring" wrote: >> Robert Oschler wrote in comp.lang.python: >> > I'm trying to upgrade from 2.1.1 to 2.2.1. I'm using kpackage (KDE's > rpm ^^ Your newsreader is broken. Please fix it or use something better than this crapware to post to usenet. >> > wrapper). >> >> You should install the OpenSSL libraries in order to fulfill these >> dependencies. If you do have the OpenSSL libraries installed, but >> the libcrypto or libssl version numbers are different on your >> machine, you can try to provide the necessary symlinks so rpm will >> shut up. > > I have 0.9.6b-34 of OpenSLL installed. Is this the wrong version or > do I have a different problem? I have no idea which Linux distribution you're using or which libraries your package installs. To fulfill the dependencies, I'd do this on my box (as root): $ ln -s /usr/lib/libcrypto.so.0.9.6 /usr/lib/libcrypto.so.2 The version number might be different from 0.9.6 on your box, check with ... $ ls -al /usr/lib/libcrypto.so.* /usr/lib/libssl.so.* ... and adjust accordingly if needed. Ditto for libssl. HTH, -- Gerhard From aahz at pythoncraft.com Mon Sep 23 21:55:30 2002 From: aahz at pythoncraft.com (Aahz) Date: 23 Sep 2002 21:55:30 -0400 Subject: Python threading? References: Message-ID: In article , Robert Oschler wrote: > >Also, what is a reasonable number of threads to expect to be able to run >before context switching overhead becomes a problem (I'm using a PIII 500 >Mhz with 512MB ram if that helps). It depends. For pure Python-based computation, more than one thread will cost you more than you gain. If it's almost pure I/O (file or socket stuff), you might be able to use as many as a couple of hundred threads. Mostly, you're probably best off somewhere between five and thirty threads, depending on what you're doing. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From fperez528 at yahoo.com Mon Sep 9 17:54:47 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 09 Sep 2002 15:54:47 -0600 Subject: Save session in python interactive console References: Message-ID: newgene wrote: > Hi, group, > After I was working at python interactive console(activepython > v2.2 at Win2000 platform), I am wondering if possible to save the > current session, so that I can load it again and continue the work > next time. Just like R or Matlab, etc. Although python is a > programming language, one of the best features I like is its > interactive console. By writting my own module, I can make it as my > personal working console. If saving session is possible, it will be > much more convinient. > The pickle module provided by python can save any object,but how > can I save all objects in current session? This problem is non-trivial and a plain pickle solution will fail. You may want to try ipython, which is a better interactive command-line environment than the default one and has _limited_ save/restore abilities. I tried using pickle but failed, so until I have time to dig deeper into the problem I implemented a log save/replay option which while admittedly imperfect, in many cases is a reasonable solution. You'll find ipython at: http://www-hep.colorado.edu/~fperez/ipython/ Cheers, f. ps. Some of ipython's nicest features only work in a proper terminal which Windows lacks, so you'll need either a Unix environment or the Cygwin system under Windows. However the basics stuff is all there under windows. From max at alcyone.com Wed Sep 4 18:00:57 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 04 Sep 2002 15:00:57 -0700 Subject: str() of a tuple References: Message-ID: <3D768299.30517666@alcyone.com> Douglas Zongker wrote: > Why, oh why does the str() of a container use the repr()s of the > objects inside? This seems to violate what the docs claim str() does > -- "return a nicely printable representation of an object." Would a > sane implementation break something? I presume this is an historical issue; perhaps if it were planned again from scratch maybe it would have been done differently. It certainly does seem to cause a fair amount of confusion. > Is there a convenient way to print out a tuple of floats so that the > output is actually readable? You can do it manually yourself: '(%s)' % ', '.join(map(str, T)) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From ponderor at lycos.com Tue Sep 10 11:42:30 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 10 Sep 2002 08:42:30 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 9) References: Message-ID: > > "This is actually the first new program I've coded in C (rather than > Python) in a good four years or so." - Eric S. Raymond > http://mail.python.org/pipermail/python-list/2002-September/121533.html > The direct link to this quote is: http://mail.python.org/pipermail/python-dev/2002-August/028106.html From tdelaney at avaya.com Wed Sep 18 23:25:39 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 19 Sep 2002 13:25:39 +1000 Subject: Minimal debug/rep functionality Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > Mark wrote: > > Hello all, > > > > In a nutshell, what I'd like to do is develop a utility > that would print out > > every line in a python program as the program executes (I > may even just > > want to print line numbers). I can see hints of how to do > this in pdb (and > > more directly in the underlying bdb class) and also in the > code module. > > > > So, > > > > 1) Should I try and inherit a class and override some > methods or should I > > just pull out the relevant code and hand spin a small interpreter. > > > > 2) Anyone have a 20 liner solution for this? > > Sorry, I couldn't find a solution that was larger than six lines: > > >>> def trace(frame, event, arg): > ... if event == 'line': > ... print '%s: %s' % (frame.f_code.co_filename, frame.f_lineno) > ... return trace > ... > >>> import sys > >>> sys.settrace(trace) Having been writing a fairly comprehensive code and path coverage tool (incomplete - currently working on determining what *is* an executable line ... think I need to work with the AST), I'd like to point out a couple of things with the above: 1. frame.f_code.co_filename will return the file that the .pyc was compiled from. Particularly in the case of standard libraries, this will often not be the path to the file in *your* filesystem. There is a way to get the corresponding file in your filesystem (basically, determine the module the frame comes from, then get the module filename using inspect). 2. The above will be *slow*. Very very slow. For a short program, this may not matter. For a long program, it will (I'm talking order of magnitude slower). The approach I have taken is to simply stored the line numbers and file info in a list, then dump it out at the end. Well, that's not *precisely* what I do, but that's the gist of it. I actually do lots of caching of file info, compression of the data, etc ... but you don't want to see that code ;) From dance_code at hotmail.com Tue Sep 24 11:40:49 2002 From: dance_code at hotmail.com (lion) Date: 24 Sep 2002 08:40:49 -0700 Subject: What is the mechanism behide? Message-ID: I'm studying the singleton pattern, there are something I don't understand in the sample code below: class OnlyOne: class __OnlyOne: def __init__(self, arg): self.val = arg def __str__(self): return `self` + self.val instance = None def __init__(self, arg): if not OnlyOne.instance: OnlyOne.instance = OnlyOne.__OnlyOne(arg) else: OnlyOne.instance.val = arg def __getattr__(self, name): return getattr(self.instance, name) print "The output:" x = OnlyOne('sausage') print x y = OnlyOne('eggs') print y z = OnlyOne('spam') print z print x print y print `x` print `y` print `z` Here are the output: The output: <__main__.__OnlyOne instance at 0x00C65AE0>sausage <__main__.__OnlyOne instance at 0x00C65AE0>eggs <__main__.__OnlyOne instance at 0x00C65AE0>spam <__main__.__OnlyOne instance at 0x00C65AE0>spam <__main__.__OnlyOne instance at 0x00C65AE0>spam <__main__.OnlyOne instance at 0x00C62C58> <__main__.OnlyOne instance at 0x00C64400> <__main__.OnlyOne instance at 0x00C5DC20> I'm puzzled that what is behide the statement "print x" ? It seem that the "print x" is implicitly turned into "print x.instance". It was said that the redirection is steered by the function __getattr__(self, name), but the function need two parameter, there is only one, I mean, x. Additionally, the function __str__(self) must also be invoked implicitly in the print-statement. Finally, the difference between statement "print x" and "print `x`" is also unknown for me. It all like magic! Could anyone explain the mechanism for me? Thank in advance, Lion From dyoo at hkn.eecs.berkeley.edu Mon Sep 16 20:31:42 2002 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 16 Sep 2002 17:31:42 -0700 (PDT) Subject: [Tutor] Re: Not sure how to phrase this question In-Reply-To: <000501c25dde$79a8be60$9865fea9@arthur> Message-ID: > In short, I want to avoid a lot of named arguments, want to have the > user interface with "argument smart" classes (in the manner of how I > think method overloading generally works), going so far as wanting > positional arguments that are in effect order insensitive. Give a > Intersection class a plane and a line in any order and it will know what > you are trying to get at. No Intersection(plane=planeinstance, > line=lineinstance). No error on Intersection(planeinstance,lineinstance) > because the class has be set up to receive only (lineinstance, > planeinstance). Hi Arthur, This link might give some more ideas on doing this kind of generalized operations. The code is in Scheme, but the ideas should transfer over gracefully: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-18.html#%_sec_2.5 Can you give a list of operations that you want to provide as well as "Intersection"? Will order always not matter, or are there operations like 'subtract', where order does matter? Perhaps your program might be amendable to a generic-operations approach. What you're doing sounds reasonable: I think the main problem here is that it's out of the experience of most mortals! *grin* Best of wishes to you! From mjackson at alumni.caltech.edu Fri Sep 27 08:01:07 2002 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 27 Sep 2002 12:01:07 GMT Subject: How do you pronounce "__" (double underscore)? References: Message-ID: brueckd at tbye.com writes: > On 26 Sep 2002, Mark Jackson wrote: > > > > > Pat Notz wrote: > > > >> @ = "at" > > > >> ! = "bang" > > > >> . = "dot" > > > >> * = "star" > > > >> > > > >> Is there a short (one or two syllable) pronounciation for "__" (double > > > >> underscore). "Underscore underscore" and "double underscore" are kind > > > >> of long. Somthing like "splat"? Anyone? > > > > > > > > _ = 'under' > > > > > > > > __ = 'under-under' > > > > > > > > > How about "underder"?? > > > > How about "dunder" (double under)? > > How about "score" and "scorescore"? That would make __seven__ "Gettysburg"! -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson Yes, but what if it were a parrot? - Graham Chapman, to John Cleese From aleax at aleax.it Tue Sep 24 10:13:41 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 14:13:41 GMT Subject: list problem References: <_FZj9.158106$pX1.5692316@news2.tin.it> Message-ID: Duncan Booth wrote: > Alex Martelli wrote in > news:_FZj9.158106$pX1.5692316 at news2.tin.it: > >> I _do_ think that reduce(operator.__add__, ...) is the only >> really frequent use of reduce, with such dominance that it might >> even be worth having as a built-in -- clearest and fastest. It >> might even specialcase _strings_ in particular, turning the op >> into a ''.join in this case... just musing... > > The simplest thing could be to modify operator.add to accept any number of > arguments. Then you could use operator.add(*aList) to add up or > concatenate as appropriate all the elements of the list. I suspect that would convert aList to a tuple (but I'd have to double check the internals to make sure) thereby negating any performance benefits. Maybe it would be better to allow operator.add to be called with ONE argument (must be iterable and not empty), OR two (working just like it works now, in this case). This should avoid any issue with type-conversion list-to-tuple or whatever. > It still wouldn't be as fast as ''.join though unless you special cased > it, and it might be hard to special case it effectively: you would have to > check the types of all the objects in the list before deciding whether or > not to use join. Yes, I could write a class X, with an __add__ that's able to accept a string argument (thus an instance of X would work with a reduce(operator.add ...) but is not a string (thus would fail if one of the items in a list passed to ''.join was an instance class X). But I could also simply check the first argument: if a string, FIRST try the equivalent of ''.join -- if that raises a TypeError, fall back to looping on addition. A tiny price to pay, I think, for the rare/weird case of a class with an __add__ that, for the benefit of helping newbies avoid the single most likely performance pitfall of Python. But I'm not sure it's such a good idea anyway. Mostly, the hypothetical builtin sum or one-argument operator.add would be used to tot up numbers, though of course as a nice side effect of polymorphism it would also work for other types (maybe horribly slow for big lists of small strings:-). Alex From magnus at thinkware.se Tue Sep 17 10:46:06 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Tue, 17 Sep 2002 16:46:06 +0200 Subject: Larry Wall's comment on python... References: <3D7958DB.50903@nospam.free.fr> Message-ID: <3D87402E.6020700@thinkware.se> laotseu wrote: > Rod Stephenson wrote: > >> Slashdot has a list of questions posed to Larry Wall (perl). When >> asked his thoughts on other scripting languages, he makes the >> following observation about python >> >> "Python is cool to look at small bits of, but I think the "outline" >> syntax breaks down with larger chunks of code. I'm with Aristotle on >> the structure of discourse--a story should have a beginning, and >> middle, and an end. So should blocks" Don Knuth said: "We will perhaps eventually be writing only small modules which are identified by name as they are used to build larger ones, so that devices like indentation, rather than delimiters, might become feasible for expressing local structure in the source language." See http://www.thinkware.se/cgi-bin/thinki.cgi/PythonQuotes Stephen Edwards said: Python: Perl designed by a sane man. http://www.cs.columbia.edu/~sedwards/classes/2002/w4115/scripting.pdf Of course there is an end for every Python block. The Zen thing to consider is the old: "What is the sound of one hand clapping?" Consider that, and return when you are enlightened. ;) My personal experience from many years of coding C++ etc with curlies and Python without, is that I tend to get lost a lot more in my C++ code than in my Python code. Not to mention the code of others... I've certainly had a number of debugging sessions where I had to help some mediocre C++ coder who couldn't match his own braces... The problem is usually that the blocks get to big... The fact that you can get away with incorrect indentation in the brace-languages makes it worse. Most modern editors have tools like indentation guides and folding that can make it easier to see block structures. Was it one of Beethoven's symphonies that ended so abruptly that the audience didn't understand when to applaud? It was considered a big failure at it's time, and it's considered one of the best works of a genious today... >> I'm not quite sure what he's trying to get at here - I guess that for >> a long heavily indented chunk of code, you could lose track of the >> overall structure, but I don't write code this way. >> >> Any comments? > > > def fun(args): > #BEGIN > if ceci or cela: > #BEGIN > do_this(with_that) > [snip a lot of code] > #END > #END I would recommend against such a coding style. First of all, if it's difficult to understand the code (even after the first 10 minutes of Python exposure) you probably have a bad structure in your code. Too big blocks, or too much nesting in the structure. The solution there is refactoring, not comments. Secondly, you are adding something redundant and foreign to your code. Getting used to how Python actaully looks is a better idea than trying to make it look like Pascal. Thirdly you are creating a maintenace problaem. The main problem with all comments (except that they often don't get written) is that they tend to get out of sync with the code. No syntax checks or test script will detect if your #END markers are incorrect. If the code is bad enough to warrant #END markers, it will be easy to write them incorrectly, and even easier to make mistakes when you change your code, adding or removing a loop or an if- statement in the middle of the structure. If you still feel that you want an explicit end marker to your blocks, do it like this. * Forget about #BEGIN, if you are unable to see where the Python blocks begin, you might as well give up. * Please forget about the ugly capitals. * Add some meaningful information to the end marker so that you see which block you are ending. * Make sure that you have a program that will check / generate the end markers. It could look like this: def fun(args): if ceci or cela: do_this(with_that) [snip a lot of code] #end: if ceci or cela #end: fun(args) It shouldn't be so difficult to write a python script that will remove all lines beginning with #end: and then regenerate them correctly for all blocks. (Not that I find it worth while...) These kinds of scripts are good to run as pre-checkin triggers if your develpment environment supports that kind of routines. From skip at pobox.com Thu Sep 19 15:26:12 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 19 Sep 2002 14:26:12 -0500 Subject: linking extension modules w/ "ld" on Solaris - to be expected? In-Reply-To: <8d148763.0209190901.6276b37e@posting.google.com> References: <8d148763.0209190901.6276b37e@posting.google.com> Message-ID: <15754.9428.370794.424364@12-248-11-90.client.attbi.com> Alan> I've tried compiling both Python 2.1.1 and 2.2.x on Solaris 8 and Alan> 9 with gcc 2.9x and 3.x in my path. I consistently get the same Alan> build error each time, so it is likely that there is some *switch* Alan> I am not setting somewhere. ... Alan> gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include Alan> -DHAVE_CONFIG_H -DBUILD=`cat buildno` -o Modules/getbuildinfo.o Alan> ./Modules/getbuildinfo.c Alan> rm -f libpython2.2.a Alan> ar cr libpython2.2.a Modules/getbuildinfo.o Alan> gmake: ar: Command not found You need /usr/ccs/bin in your PATH. That's where ar and several other compilation- and link-related commands live, not just compilers proper. -- Skip Montanaro - skip at pobox.com The need for gutters to be cleaned is directly proportional to how hard it happens to be raining at the moment. From Oschler at earthlink.net Sat Sep 28 14:38:27 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sat, 28 Sep 2002 18:38:27 GMT Subject: Best way to create a class dynamically on the fly? References: Message-ID: "Robert Oschler" wrote in message news:tFml9.13043$Lg2.3865279 at news2.news.adelphia.net... > What is the best way to create a Python class dynamically at runtime? A > sample or doc would be great. I'm a veteran C++ programmer so this concept > is very alien to me as you can imagine (dynamically created classes). An > example that would show the creation of a descendant (sub-class), and a > another example showing the creation of an ancestor class would be perfect. > > thx I forgot to mention, I would like the classes I create dynamically to be fully "pickle-able". If there are any caveats or limitations in this area please let me know. thx From cbbrowne at acm.org Fri Sep 20 19:54:55 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 20 Sep 2002 23:54:55 GMT Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> Message-ID: In an attempt to throw the authorities off his trail, danb_83 at yahoo.com (Dan Bishop) transmitted: > Magnus Lyck? wrote in message news:<3D8B1537.4010803 at thinkware.se>... >> ChrisBarker wrote: >> > The only reason I can see >> > to not writing your class in Python is performance, and unless you are >> > doing a lot of calculations, that is probably a non-issue. >> >> Performance issues might well matter in large financial >> systems, but that's not the only reason. > > Please name one other real-world situation in which decimal arithmetic > is actually *needed*. > >> [snip] >> And if someone would write >> >> x = Decimal(9.999999999999999) - Decimal(9.9999) >> >> they would not get what they expected (unless they expected >> 0.000099999999998). Ok, they could write > But how often does an error of 10 parts per trillion really matter? > Afaict, not nearly enough to justify having a default number > representation that works against the hardware. This isn't thinking like an ex-COBOL programmer. An ex-COBOL programmer will look at this and say something like: "You stupid buffoons! You're arguing over how to deal with some abstruse fifteenth decimal place. In COBOL, we never had to worry about such idiocy concerning the numeric /error/ that you're describing. If we're working with dollars and cents, we define the variable as: X PIC 999999999V99 And we will have none of these idiotic rounding errors." Add X to a variable with the same format, and there's NO issue of bad rounding. The behaviour of BCD arithmetic is perfectly well defined, and _doesn't_ depend on hoping and praying that the IEEE FP operations will do approximately the right thing. The COBOL (or PL/I, or anyone else accustomed to BCD data types) guy will justifiably look at the bizarro FP rounding as being, well, bizarre. There's _no_ good reason for subtracting two perfectly good decimal values from one another to result in having weird artifacts appear in some 17th decimal place, aside from having a willingness to admit fairly deranged arithmetic. People use FP arithmetic making the ludicrous assumption that FP values are "Real numbers." They aren't, despite some languages that call them REALs. They also generally aren't decimal values, but rather binary fractions, from whence enters the bizarre artifacts of FP. I think there's a good argument for the idea that people should generally be flogged mercilessly if they use FP values without having had a /good/ education in numerical analysis which is /necessary/ in order to be able to competently use them. -- (concatenate 'string "cbbrowne" "@cbbrowne.com") http://cbbrowne.com/info/unix.html "It don't mean a thing, if it ain't got that swing..." From fperez528 at yahoo.com Wed Sep 18 16:59:57 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 18 Sep 2002 14:59:57 -0600 Subject: linux python ideas References: <3D88E578.6010001@diespammerdieuselesspython.com> Message-ID: Rob Andrews wrote: > I'll be giving a presentation on Python to my local LUG > (http://lugoj.org) in a few weeks, and would like to point out at least > a few things that would be of particular interest to linux users. > > The idea is not "how to program in Python", which would take more than > one quick presentation, but a one-off demonstration of ways in which > Python is particularly useful for such a group. > > Any suggestions would be appreciated, since my notes are pretty generic > so far. Check out ipython at http://www-hep.colorado.edu/~fperez/ipython It's not linux-specific, but its best features only work in a linux/unix environment, and it will appeal very much to command-line junkies. Take a look at the screenshots to get a feel for its features and feel free to drop me a line if you have a question. It allows you to use the python shell almost as a system shell, not so much to replace the regular shell for day to day stuff, but rather to have the power of file and directory management when you need to do things with python. For me it's very useful in processing scientific data, since I have both access to Python/Numeric/Gnuplot and at the same time have essentially a system shell. The introspection features (name? and ) also make it very useful for regular programming tasks. Well, check for yourself. In general, python+Numeric+Gnuplot/Grace makes a pretty strong stand against the $$$ likes of Matlab. And in many cases beats them (in others we're still behind, but catching up quickly). Cheers, f. From manuel at hendel.net Tue Sep 17 03:19:00 2002 From: manuel at hendel.net (Manuel Hendel) Date: Tue, 17 Sep 2002 09:19:00 +0200 Subject: problems getting a single item out of a list Message-ID: <20020917071900.GB23629@partagas.as.de.cw.net> I try to get a single item out of a list, but after this, the single item is stil a list item. domainfield = fields[3:4] I just want to get a new variable with a the value of the 3rd item of the list fields. Can anyone help? Thanks, Manuel -- Wisdom eventually comes to all of us. Someday it might even be your turn. -David & Leigh Eddings, "Polgara, The Sorceress" From stuart at bmsi.com Mon Sep 23 17:16:10 2002 From: stuart at bmsi.com (Stuart D. Gathman) Date: Mon, 23 Sep 2002 17:16:10 -0400 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> Message-ID: On Sat, 21 Sep 2002 23:10:09 -0400, Christian Tismer wrote: > Dan Bishop wrote: > > Please name one other real-world situation in which decimal > > arithmetic is actually *needed*. > > There is no reason to argue about that. Decimal arithmetic is exact for > most of the operations bankers require. They have been demanding for it > since decades, and they will not drop it. Let me add a horror story of what happens when financial applications do *not* demand fixed point/decimal arithmetic. We took on a client whose accounting system used binary floats for all dollar amounts. And I mean *dollar* amounts, not penney amounts. Since all pennies were approximate, the total due at the bottom of the invoices would rarely match what the customer would get adding up the line items on a calculator. It was only off by a few cents, but it tended to make customers lose faith in the system. Statements also did not add up, and the Balance Sheet didn't balance. We converted their system to use fixed point, and now everything balances and totals to the penney. Unfortunately, their CPA keeps his own version of their General Ledger on Excel with binary floating point. The CPA balance sheets do not balance. The CPA General Journal transactions do not balance. I demonstrated with a calculator that the CPA figures did not balance, but they insisted that we had to go with the CPA figures because he is a CPA, and I'm just a programmer. This is tricky since their new General ledger does not accept unbalanced transactions. My solution was to create a 'CPA adjustment' account to contain all the discrepancies, and manually decide how to allocate the extra/missing pennies for the CPA transactions. There ought to be severe penalties for idiots that use floating point dollars for financial applications. If forced to use floating point (e.g. because customer demands BASIC), then keep money amounts in whole pennies (or whatever the smallest currency unit for the country is), and divide by 100 (or whatever) for printing only (or just add the decimal point yourself). -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - Mozart background song for the Microsoft "Where do you want to go from here?" commercial. From jdhunter at ace.bsd.uchicago.edu Thu Sep 5 13:10:24 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 05 Sep 2002 12:10:24 -0500 Subject: plex Message-ID: I am writing a plex lexer/scanner to parse a pdf file. Here is the first part, which extracts the streams. I would like to do this a bit more efficiently, namely, to read the streams in multicharacter chunks rather than one character at a time. As it is, the function add_stream has to be called for every character in the stream. Any advice how to do this? Here is the code: from Plex import * def add_stream(scanner, text): scanner.thisStream += text def end_stream(scanner, text): print 'BeginStream: ', scanner.thisStream, 'EndStream:' # do something with the stream here scanner.thisStream = '' scanner.begin('') lexicon = Lexicon([ (AnyChar, IGNORE), (Bol + Str("stream ") + Eol, Begin('stream')), State('stream' , [ ( Bol + Str("endstream") + Eol, end_stream ), ( AnyChar, add_stream), ]), ]) filename = "test.pdf" f = open(filename, "r") scanner = Scanner(lexicon, f, filename) scanner.thisStream = '' while 1: token = scanner.read() if token[0] is None: break Thanks, John Hunter From aahz at pythoncraft.com Thu Sep 12 10:49:19 2002 From: aahz at pythoncraft.com (Aahz) Date: 12 Sep 2002 10:49:19 -0400 Subject: class variable won't icrement! References: <3d8054ef$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: In article , Eric Brunel wrote: > >I always found that inheritance of class attributes to instance attributes >was really misleading, and I even think it would be better if it were >simply removed from Python. IMHO, it would far more conform to the >"explicit is better than implicit" rule that is one of the basis of Python. If I think of it as "scope resolution" rather than "inheritance", I find that it makes more sense. It works exactly the same way as hiding a global with a local. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From debl2nononspammmy at bellatlantic.net Sat Sep 21 19:51:16 2002 From: debl2nononspammmy at bellatlantic.net (David Lees) Date: Sat, 21 Sep 2002 23:51:16 GMT Subject: Math optimization References: <6T5j9.145247$pX1.5195840@news2.tin.it> <3D8D02A0.FF572334@bellatlantic.net> Message-ID: <3D8D0612.A6CE7011@bellatlantic.net> Using the quick and dirty code below and just changing line 9 between prod = n * b and prod = n*7, running on my Win98SE, Python 2.2.1 I get a 13% difference between using a constant and a variable. I don't know much about what Python is doing in the way of optimization or if it is even keeping things as integer arithmetic, so take it with a grain of salt. David Lees import time,string n = string.atoi(sys.argv[1]) total = n prod = 1 b = 7 t0 = time.clock() while (n): prod = n*b n -= 1 t1 = time.clock() n=total t2 = time.clock() while (n): pass n -= 1 t3 = time.clock() A = t1-t0 B = t3-t2 print total, A-B David Lees wrote: > > This depends on your hardware, OS and probably Python version. Further > you need to specify the data type. Integer, floating point or infinite > precision integers. It is quite easy to run benchmarks, which you > should do yourself. > > David Lees > > Zed wrote: > > > > Hi! > > What's faster in python? Divide or multiply? > > (a= b*c is faster than a=b/c)? > > > > Math expressions with constants are calcolated during .pyc creation or real > > time? > > (a=b*5 is faster than a=b*5*2/2 )? > > > > Thanks From mennosimons at gmx.net Tue Sep 24 12:00:39 2002 From: mennosimons at gmx.net (Ulli Stein) Date: Tue, 24 Sep 2002 18:00:39 +0200 Subject: PicklingError with md5.md5() object Von: Ulli Stein Datum: Dienstag, 24. September 2002 17:03:09 Gruppen: comp.lang.python Folgenachricht an: mennosimons@gmx.net Keine Referenzen Message-ID: Hi, while trying to pickle a md5 instance I get the following error: >>> import cPickle, md5 >>> f=open("/tmp/t", "w") >>> p = cPickle.Pickler(f) >>> m=md5.md5() >>> p.dump(m) Traceback (most recent call last): File "", line 1, in ? cPickle.UnpickleableError: Cannot pickle objects What should I do? The marshal module is also not recommended for this task. Thanks. From ckasso at sprynet.com Wed Sep 25 18:02:16 2002 From: ckasso at sprynet.com (Chris Kassopulo) Date: Wed, 25 Sep 2002 18:02:16 -0400 Subject: how to change font and its size in IDLE (in UNIX)? References: Message-ID: <20020925180216.0dce7381.ckasso@sprynet.com> On Tue, 24 Sep 2002 22:22:35 -0700 Kow K wrote: > Hi all, > > I'm trying to figure out how to change the font and its size in IDLE. > It's Courier in 10pt. I don't like Courier, and what's worse, > 10pt is too small for me. I wish I could change it to Fixed 7x13. > > Any input will be appreciated. > > Kow > > >From the file ~/.idle: # IDLE reads several config files to determine user preferences. This # file is the default config file. When IDLE starts, it will look in # the following four files in order: # config.txt the default config file # config-[win/unix/mac].txt the generic platform config file # config-[sys.platform].txt the specific platform config file # ~/.idle the user config file -- Chris Kassopulo From dcswest at flashmail.com Wed Sep 4 00:01:41 2002 From: dcswest at flashmail.com (Dennis B.) Date: 03 Sep 2002 21:01:41 -0700 Subject: Privacy and Inheritance Message-ID: <1031112108.240.28.camel@localhost> Greetings; Have enough confidence in Python to realize this is probably just my misunderstanding, but wondering why Python mangles private, double underscore attributes with the name of the base class even if they're inherited and the instance is that of the sub class. Like the following doesn't even seem to work: class StandardNormal: def letEventZScore(self, eventZScore): self.__eventZScore = float(eventZScore) class DerivativeNormal(StandardNormal): def getCentral(self): if self.__eventZScore < 0: Unless I change that last line to something like: if self._StandardNormal__eventZScore < 0: Maybe just missing the point all together, but wondering if anyone'll point out anything a little more elegant and/or intuitive. Thank you and have a great day, From altis at semi-retired.com Sat Sep 14 19:58:46 2002 From: altis at semi-retired.com (Kevin Altis) Date: Sat, 14 Sep 2002 16:58:46 -0700 Subject: Python11 References: Message-ID: Is Portland, OR the official location, I didn't think that had been decided yet? I haven't seen anything posted on the O'Reilly conference site. I hope it will be in Portland, that would be great. ka "Martin v. Loewis" wrote in message news:m3admk47pf.fsf at mira.informatik.hu-berlin.de... > "Jeff Sasmor" writes: > > > Is there any definitive information on the next Python conference, > > Python 11? I've read the conferences-discuss archive on > > Python.org (http://mail.python.org/pipermail/conferences-discuss/) > > and the discussion seems to be tapering off. IIRC, by last year > > at this time there was already a call for papers. > > Python11 will be colocated with the O'Reilly Open Source Convention > (OSCON), which will take place July 7-11, 2003 in Portland, USA. > > I believe O'Reilly will organize the specific schedule, including > setting dates for the call for papers, submission deadlines, etc. > Given that this is still ten months away, I don't see any urgency. > > HTH, > Martin From loewis at informatik.hu-berlin.de Mon Sep 16 04:06:55 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 16 Sep 2002 10:06:55 +0200 Subject: Book for win32? References: Message-ID: Thomas Guettler writes: > I am interested in book about Python on win32. > > I found one from o'reilly: "Python on win32" > > Are there better books or alternatives? No. Regards, Martin From andrewm at object-craft.com.au Mon Sep 16 20:51:18 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Tue, 17 Sep 2002 10:51:18 +1000 Subject: Pickling slotted instances In-Reply-To: Message from loewis@informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) of "16 Sep 2002 09:25:05 +0200." References: Message-ID: <20020917005118.81D3C3C8FF@coffee.object-craft.com.au> >Or, do you mean, by "instance", an object of a certain type which has >slots? If so, inst.attr is the same as > >getattr(inst.__class__, 'attr').__get__(inst) > >(if not inst.__dict__.has_key('attr')). So 'attr' will be searched in >the class, using the method resolution order. This happens to return >a member descriptor, namely . Yes, that's what I meant - I'd been struggling to work out where attribute descriptors resided, and you've just added the missing detail - thanks (I'd been fiddling with "property()" and not getting the results I expected). That certainly makes pickling harder. >"The bases", for me, would put "proper syntax" before support for >automatic pickling, e.g. via > >class X(object): > def foo # defines a slot foo. > def bar[transient] # defines a transient slot. I'd agree with this. The __slots__ notation is a bit of a wart, but then again, it's consistent with several other tricks. >New-style classes are really the same as traditional types. In the >past, you could not pickle arbitrary types unless you have special >machinery (such as copy_reg manipulation); so it is not surprising >that you can't pickle certain cases of new-style classes >automatically. Notice that you *can* pickle them - just define the >__getstate__. I see your point, but it seems like most of the machinery is already there. It's a shame that slotted classes aren't more "complete", because they are the perfect answer to people who use tuples instead of classes for performance reasons (they are only slightly slower than a tuple). -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From duncan at NOSPAMrcp.co.uk Tue Sep 10 10:00:34 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 10 Sep 2002 14:00:34 +0000 (UTC) Subject: dynamism References: Message-ID: "Mark McEahern" wrote in news:mailman.1031660952.2330.python-list at python.org: > [Duncan Booth] >> New style classes (which are those with 'object' or other builtin >> classes as a base class) do not all allow you to add arbitrary ^^^ >> attributes: > > Au contraire: > > $ python > Python 2.2.1 (#1, Jun 25 2002, 10:55:46) > [GCC 2.95.3-5 (cygwin special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. >>>> class foo(object):pass > ... >>>> f = foo() >>>> f.x = 1 >>>> f.x > 1 >>>> Read what I wrote? The word 'all' was supposed to be a clue. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From sam at localhost.localdomain Wed Sep 11 18:55:46 2002 From: sam at localhost.localdomain (newbie) Date: Wed, 11 Sep 2002 23:55:46 +0100 Subject: I must be an idiot, please pity me! References: Message-ID: Perhaps I wasn't clear, but I don't believe I mentioned anything not functioning properly. I did say "All works fine". I don't have failing code, I simply suspect (hope) the current implentation isn't very good. The pseudo code listed was what I was epecting python to allow me to do, but due to the namespace implementation, it doesn't. I have to do what I considered as a work around, and that is by passing a db connection to pretty much everything to get seperate modules/functions to share a db connection. Maybe that's just the way things are done in python, modules and databases? I don't know, that's why I'm asking. Putting everything into one module works as expected too. But then it's not very good for code reusage, as importing that module brings me back to passing a db connection to everything. I was hoping that I had missunderstood a basic concept, and that there was a nice way of perform something along the lines of the pseudo code listed. On Wed, 11 Sep 2002 18:10:42 +0100, Mark McEahern wrote: > [newbie] >> But it doesn't seem to work like that. > > I don't know about all the mind readers out there, but you really > haven't given us any helpful information. Are you getting an error? > What are the symptoms of failure? What are you expecting to happen? Why > not try to simplify what it is you're trying to do and share *that* > code? > > For instance, the functions in each of your modules--do they take a > database connection as a parameter? > > Have you tried stuffing everything into one module--just to see if it > works? > > Etc. > > // m > > - From Michael.Sparks at rd.bbc.co.uk Fri Sep 13 09:18:54 2002 From: Michael.Sparks at rd.bbc.co.uk (Michael Sparks) Date: Fri, 13 Sep 2002 14:18:54 +0100 Subject: wrapping yield ? References: Message-ID: > Don't forget that iterating with a generator is *much* more efficient than > calling a Python functions thousands of times. ... > the subsequent iterations have virtually no overhead at all. Can't forget something you don't already know - very much appreciated... Best Regards, Michael. From marklists at mceahern.com Fri Sep 13 12:18:40 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 13 Sep 2002 11:18:40 -0500 Subject: question about dictionary type.. In-Reply-To: Message-ID: [eugene kim] > i'd like to have a dictionary which looks like > table = { category1 : { category2 : { category3 : 'garbage value' } } } > > category1 has many category2 > category2 has many category3 > > i expected > table[ 'computer' ][ 'language' ][ 'python' ] = 0 > to create {computer : { language : { python :0 }}} > table[ 'computer' ][ 'language' ][ 'java' ] = 0 > to becomes { 'computer' : { 'language' : { 'python' :0 , 'java' :0 }}} > > but python doesn't allow me to do this.. > can anyone help me? In this case, the problem is obvious, but rather than "python doesn't allow me to do this?" it's generally more helpful to provide exact tracebacks or more explicit information about what's not working. The problem? You're not telling Python to create the sub dictionaries... $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> t = {} >>> t['computer'] = {} >>> t['computer']['language'] = {} >>> t {'computer': {'language': {}}} >>> etc. // m From aahz at pythoncraft.com Sat Sep 14 10:36:38 2002 From: aahz at pythoncraft.com (Aahz) Date: 14 Sep 2002 10:36:38 -0400 Subject: threads or queue for this task References: Message-ID: In article , Mark Hammond wrote: > >Look for Aahz's threading tutorial - URL not at hand, but it can't be >too hard to find. Indeed, I predict he will tell you exactly where it is ;) On my web page, of course. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From schneiker at athenalab.com Thu Sep 26 20:32:08 2002 From: schneiker at athenalab.com (Conrad Schneiker) Date: Fri, 27 Sep 2002 00:32:08 GMT Subject: http://www.python-in-business.org Message-ID: Chris, Do you have anything to do with these people? Is there any sort of analogous North American organization? Conrad From whisper at oz.net Wed Sep 18 00:34:38 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 17 Sep 2002 21:34:38 -0700 Subject: PythonScript In-Reply-To: <362133AB12B2CE4EA3C01E12CD6CCC6E0254E08B@osprey.corp.resmed.org> Message-ID: > The problem I seem to be hitting is utilising python in applications that > embed an ActiveScript Engine. To date I am unable to get one python script > to execute. Other languages vbscript, jscript,perl etc, work in the same > environment so I'm left wondering if its a configuration problem or > something that I might be overlooking. If anyone could give me pointers, > url's, snippets etc. it would be interested. The product I specifically > having problems is FinalBuilder (http://www.atozedsoftware.com) > though have > seen this problem in other applications as well. > > I've tried both ActiveState and Python distribution 2.2.1 with Win32 > 1.48all. > > Regards > > Gavin > Did you register Python as an ActiveScript host? I believe this is done for you automatically if you use the installer and not done for you if you don't. It's possible that it gets done for you the first time you run the PythonWin IDE too. Have a look at this file: \Python22\Lib\site-packages\win32com\readme.htm HTH, Dave LeBlanc Seattle, WA USA From brian at sweetapp.com Wed Sep 25 20:10:35 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 25 Sep 2002 17:10:35 -0700 Subject: "which" command? In-Reply-To: Message-ID: <009c01c264f1$23333690$df7e4e18@brianspiv1700> > A few days ago there was a discussion here about a > "which" written in python (as opposed to running > the OS "which" command). Any pointers to that thread? > As you can imagine it's been difficult to make a > sensible google groups query since I can't think > of any reasonably specific terms to search for... The actual software is available here: http://starship.python.net/~tmick/ Cheers, Brian From skip at pobox.com Thu Sep 19 12:22:49 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 19 Sep 2002 11:22:49 -0500 Subject: Remarks to Python 2.3 In-Reply-To: <20020919152834.592eaa39.leafnode-usenet@schabi.de> References: <20020918222421.328088eb.use-net@schabi.de> <20020919152834.592eaa39.leafnode-usenet@schabi.de> Message-ID: <15753.63961.863682.282501@12-248-11-90.client.attbi.com> Markus> martin at v.loewis.de (Martin v. Loewis) schrieb: >> Or, better yet, submit bug reports. Markus> I'm not really shure whether my remarks are about "bugs" ... By submitting to the bug tracker you provide a single place to gather commentary about an issue. If it's determined its not a bug, it will be marked as such and closed. By carrying out the discussion here, you run the risk that someone interested in the issue will miss one or more messages about it because they got lost within the sea of other messages. -- Skip Montanaro - skip at pobox.com The need for gutters to be cleaned is directly proportional to how hard it happens to be raining at the moment. From marklists at mceahern.com Tue Sep 17 20:34:04 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 17 Sep 2002 19:34:04 -0500 Subject: Splitting a list of strings In-Reply-To: Message-ID: > I need to read a list of strings from a file[...] For those of us who are lazy and lacking in imagination, why not share a few lines of representative sample data? // m p.s. Don't use str as the name of a variable, you'll clobber the builtin str. - From Padraig at Linux.ie Tue Sep 10 09:56:37 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Tue, 10 Sep 2002 13:56:37 GMT Subject: Graph Layout Algorithms References: Message-ID: Duncan Smith wrote: > Hello, > Just wondering if anyone has implemented anything in Python. I > need to lay out my graphs (directed acyclic / undirected / trees) in a > reasonably clear way. So if anyone has already implemented anything, or if > anyone has advice on appropriate algorithms, I'd be glad to hear about it. > Cheers. > > Duncan Do you mean graphically represent or internally in data structures? If graphical you could generate the simple text files required by: http://www.research.att.com/sw/tools/graphviz/ Alternatively you could do a python wrapper for the libgraph of the same toolkit? Actually there is one done already! http://www.cs.brown.edu/~er/software/ P?draig. From cjw at sympatico.ca Fri Sep 27 12:32:57 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 27 Sep 2002 12:32:57 -0400 Subject: Attempt to install and test gnuplot fails Message-ID: <3D948839.4617A278@sympatico.ca> An HTML attachment was scrubbed... URL: From gerhard.haering at opus-gmbh.net Wed Sep 4 05:54:47 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 4 Sep 2002 09:54:47 GMT Subject: Why Python? References: Message-ID: Markus Jais wrote: > hi > one reason is that with every programming language you can learn new > concepts. > [...] > the pragmatic programmers (http://www.pragmaticprogrammer.com - very good, > you should visit it) recommend to learn at least one new language every > year. I used to do that, too. But the last ones I tried to check out (Ocaml and Dylan) didn't solve any of my real problems, so I came back to Python very quickly. Ocaml didn't have enough libraries for me. And Dylan just doesn't look mature enough. > so maybe you should learn both PHP and Python (and Ruby, of course :-) I'd skip PHP. But then, I'm biased. And proud of it :-P -- Gerhard From mcherm at destiny.com Wed Sep 11 15:07:08 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 11 Sep 2002 15:07:08 -0400 Subject: Variables vs. names References: <3D7F8132.2D5CEC24@earthlink.net> Message-ID: Joseph A. Knapka wrote: > Are there languages that > achieve Python's semantics using "real" > variables? Java's semantics seem pretty much > identical to Python's in this respect, yet > nobody in the Java community will object if > you call a thing-with-a-name-and-a-value a > "variable". I can't answer your other questions, but I may have some insight on this one. I agree that the semantics are basically the same (at least for Java objects). But Java doesn't have the ability to access a namespace as a dictionary ( locals(), globals(), .__dict__, etc ). Also, people who talk about Java have a certain tendency to treat Java as the One-True-Way for a language to work, while people who talk about Python try to place it in context of other languages. Of course, maybe there are more concrete reasons that I'm missing. -- Michael Chermside From roy at panix.com Mon Sep 9 06:47:49 2002 From: roy at panix.com (Roy Smith) Date: Mon, 09 Sep 2002 06:47:49 -0400 Subject: Larry Wall's comment on python... References: Message-ID: bslesins at best.com (Brian Slesinsky) wrote: > Of course it's unnecessary and should be entirely optional. One of the biggest impediments to learning Perl is that so much stuff is optional. You learn a concept and think you've got it. Then, you look at a different example of code that purports to do the same thing and it looks entirely different. From robin at jessikat.fsnet.co.uk Thu Sep 5 05:23:21 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 5 Sep 2002 10:23:21 +0100 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> <3d765ce6_4@news.bluewin.ch> <3d767c4a$1_1@news.bluewin.ch> Message-ID: In article <3d767c4a$1_1 at news.bluewin.ch>, Samuele Pedroni writes > >Robin Becker wrote in message >zzKd7KAqhnd9EwxT at jessikat.fsnet.co.uk... >> ..... >> it, test_pdfbase_ttfonts.py doesn't look as though it's doing anything >> particularly odd, certainly I see no references to system/spawn in >> there. >> -- > >have you tried my little program with your JVM. > >If my program work as for me, that means that your py plus jython trigger a >bug of the JVM, because anyway and in any case the JVM ought to scream "out >of memory" well before eating a 1GB of memory. > >regards. > > OK here's the results with outofmem C:\jython-2.1\reportlab\test>javac outofmem.java C:\jython-2.1\reportlab\test>java outofmem 1 2 3 4 5 6 7 8 9 10 11 Exception in thread "main" java.lang.OutOfMemoryError Is it possible I'm using a wrong java engine somewhere? -- Robin Becker From tismer at tismer.com Wed Sep 18 16:14:11 2002 From: tismer at tismer.com (Christian Tismer) Date: Wed, 18 Sep 2002 22:14:11 +0200 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <96904b50.0209181149.429e8533@posting.google.com> Message-ID: <3D88DE93.6080004@tismer.com> Lee Gray wrote: ... > Thanks for all the suggestions, folks! > > I've collected lots of links to a variety of very nice screenshots, > and I've been playing with the wxWindows demo and Boa Constructor. Boa > was a bit disappointing, not as an app, but because of its current > alpha status - but it's got great potential and I'll definitely look > forward to future releases. I'll check out PythonCard too. Boa is in fact quite a bit alpha-ish, but after you're used to the quirks and limitations, it is really great. Also note that you should use the version from CVS which is *far* more developed than the downloadable. I've written a quite big wizard for 3D image processing with wxPython, PIL, Stackless. If you like, I can prepare some screen shots. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Fri Sep 13 12:22:04 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Fri, 13 Sep 2002 18:22:04 +0200 Subject: calling Oracle functions References: <3d81f811$1@news.mt.net.mk> Message-ID: <3d8210a3@news.mt.net.mk> > Oracle differentiates between functions and procedures so you must > identify that you are calling a function, not a procedure. The DB API > does not allow for this, so you must use an anonymous PL/SQL block and > some non DB API code. The way to do this is as follows: ok. I also tried that, I mean a PL/SQL block... but > Replace the data types as appropriate. > v_Vars = v_Cursor.setinputsizes(p_Result = cx_Oracle.NUMBER) didn't know about this :)) thanks. ... > If anyone has suggestions about how to improve this, fire away... :-) yes, put it in the documentation. Actually is there any documentation about cx_Oracle, past the README file? Now a simpler question: is it possible to specify the data source name directly not through the alias defined in tnsnames.ora. In perl DBD I can specify a connection string like cs = "dbi:Oracle:host=1.10.100.200;sid=TEST"? -- ?????? ???????? ?? ????... ...????????? ?? ????. From maxm at mxm.dk Sun Sep 29 15:02:18 2002 From: maxm at mxm.dk (Max M) Date: Sun, 29 Sep 2002 21:02:18 +0200 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> Message-ID: <3D974E3A.3000809@mxm.dk> dsavitsk wrote: > "Jurie Horneman" wrote in message <250 lines and 8.5 KB of quote snipped ...> Please do not quote the full message you are replying to, just to add a few short lines of your own. We can allready read the first message in that post. It is a pretty shure way not to get read. kind regards Max M From aleax at aleax.it Mon Sep 16 15:27:44 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 16 Sep 2002 19:27:44 GMT Subject: threads or queue for this task References: Message-ID: James J. Besemer wrote: ... >>How can one code if you don't >>reliably know when a Queue is empty or full? > > Generally, Queues never get "full" and you generally don't care if > they're empty. You can define Queues that can hold a maximum number of items; in this case, they do get full if they're being filled faster than they're being emptied. Sometimes, this IS what you want -- and generally in such cases you just call method put and let it sleep until a slot frees up, should that be needed -- just the converse of the normal case for empty. For example, suppose an architecture such as: --> W1 supervisor -> Q ---/---> W2 \---> W3 i.e., one supervisor thread that produces work requests and places them in a single queue Q, from which three worker threads peel work requests and produce results (say the W threads place their results in another queue Q1 from which another thread X peels them for output or whatever -- it doesn't really matter). Say that producing a work request takes CPU time T, that processing the work request and producing the result takes 10T, and that 3 or 4 simultaneous threads is ideal to keep the system maximally busy. Round-robin scheduling assumed. Now, if Q is unlimited, the supervisor thread will soon fill it up. In, say, the first 40T or so time units, threads W1, W2 and W3 will each have gotten and processed one work unit, while the supervisor has received 10T time units and thus has produced 10 work units: there are now 7 units in Q. After another 40T have elapsed, Q has grown to now hold 14 units. And so on: Q grows without bounds, assuming there is always more work to perform. Eventually Q overflows available memory, and boom, the whole process goes haywire. Even if the total number of work units to perform is bounded, say N, with this arrangement Q must still grow to hold 0.7N work units at the peak. This might force pagination and at the very least slow things down noticeably. The solution is trivial: just set Q to hold, at most, 3 items. A little bit more, if you want -- doesn't matter. In any case, soon the supervisor thread will find Q full and wait until one of the W threads is done with its work and peels off another work unit, thus freeing a slot in Q. Basically, with this simple device, we have changed the way processing time is being allocated: instead of each 40T units going, 30 to processing 3 work units and 10 to producing 10 work units, giving Q a maximum size automatically balances the number of work units produced and processed when the system is working in steady-state, so we know by this that each 33T units will go, 30 to process 3 work units, 3 to produce 3 more work units. Besides avoiding wasting too much memory on Q, this also speeds up the rate at which results are output in steady state: 3 results come out every 33T time units, instead of every 40T time units. That's an average wait of 11T time units per result produced (best possible, since it takes 1T to produce the work request and 10T to process it!) rather than 13.3T -- in this sense, the system with an unlimited-size Q is about 20% slowes than the variant with a Q of limited size (during the system's overall steady-state). You're welcome to apply queueing theory to analyze variants where times to produce and process working units are not deterministic (or, probably easier, simulate them:-) to determine the effects of Q's size depending on these key system parameters. E.g., if sometimes processing time is very short, we want to set Q's size large enough to ensure there is just about more work for the W thread that got free unexpectedly fast -- and similarly, if sometimes time to produce the next working unit is occasionally quite long. For each assumption about times there will be optimal sizes for Q to optimize system throughput or response times. Rarely will optimal sizes be infinite. > The import thing about Queues is that the reader thread will > automatically be suspended when reading from an empty queue and > furthermore it will automatically wake up when the queue becomes non > empty. > > All you need from Queues is to create them and to get and put data. Yep. Setting size is just an optional embellishment, though sometimes it does pay dividends. > You probably should look for a book on concurrent sequential processes. > Most of the paradigms and pitfalls are pretty standard and would be > spelled out in the book. Unfortunately, I am at a loss to make a > specific recommendation. Perhaps somebody else has an idea. I think the standard reference on this nowadays might be Gregory Andrews' "Foundations of Multithreaded, Parallel, and Distributed Programming", Addison-Wesley. Alex From marklists at mceahern.com Fri Sep 20 16:50:58 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 20 Sep 2002 15:50:58 -0500 Subject: average? In-Reply-To: Message-ID: [Carl Banks] > What I can't figure out is how you got from this to what you > typed. :-) Yeah, holy cow, me neither! Thanks for the reply. Cheers, // mark From warkid at storm.ru Tue Sep 17 06:47:37 2002 From: warkid at storm.ru (Kerim Borchaev) Date: Tue, 17 Sep 2002 14:47:37 +0400 Subject: More on Protecting Source Code In-Reply-To: References: Message-ID: <1134805499.20020917144737@storm.ru> Hello David, Tuesday, September 17, 2002, 7:26:06 AM, you wrote: DL> I suppose one solution is to modify the Python interpreter with different DL> op-codes and that ought to make it somewhat painful for the average hacker. DL> A better solution is to make a .pyc file approximately as hard as a binary DL> .exe file to decompile - however that could be done. Just a thought. Keeping your python modules encripted(e.g. with rotor module?) you can reimplement __import__ builtin to properly handle importing these modules. Best regards, Kerim mailto:warkid at storm.ru From davbucko at deletethis.yahoo.com Sun Sep 1 20:33:44 2002 From: davbucko at deletethis.yahoo.com (davbucko) Date: Mon, 2 Sep 2002 01:33:44 +0100 Subject: Keyerror problem Message-ID: <_lyc9.7164$7N.29584@newsfep3-gui.server.ntli.net> Hi guys, I have a feeling this is going to turn out to be a pretty stupid question, but here goes anyway... I have a class Flags as follows: class Flags: def __init__(self): self.flags = {} def getInverseFlags(self): for i in self.flags.keys(): #switch some keys/values around def setFlag(self,name,value): self.flags[`name`] = value #End of class Flags I then call that class and use it: flags = Flags() powers = Powers() #This class is working fine elsewhere, so I don't think that it is the problem def getComplimentaryGrid(): flags.getInverseFlags() for j in powers.dict[flags.flags['row1']]: #This line doesn't work For some reason, on the line above, I am getting the following error message: Traceback (most recent call last): File "C:\Dave\python\squaresprint.py", line 188, in ? iterateGrids() File "C:\Dave\python\squaresprint.py", line 163, in iterateGrids grid.checkGridCols() File "C:\Dave\python\squaresprint.py", line 78, in checkGridCols getComplimentaryGrid() File "C:\Dave\python\squaresprint.py", line 167, in getComplimentaryGrid for j in powers.dict[flags.flags['row1']]: KeyError: row1 I don't know why this is, as 'row1' is clearly a key. If I enter the following just above the line that is giving me trouble above: for i in flags.flags.keys(): print i, I get the output: 'col1' 'col3' 'col2' 'row3' 'row2' 'sum' 'row1' which shows that 'row1' is a key. I am entirely new to python, so if this is an idiotic question, please say. If you need more code, there (obviously) is more, but imvho it is not causing any problems. Cheers Dave From see_reply_address at something.invalid Wed Sep 18 02:14:08 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 18 Sep 2002 18:14:08 +1200 Subject: Splitting a list of strings References: Message-ID: <3D8819B0.8000702@something.invalid> Sean Ross wrote: > > What I'm interested in knowing is, can I extract all of the "attribute" > strings from lines in such a way that I get my list of "attribute" strings, > but all of those strings have been removed from lines as well, all at the > same time? attributes = [] data = [] for line in lines: c = line[0] if c == "@": attributes.append(line) elif c <> "%": data.append(line) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From syver-en+usenet at online.no Sun Sep 8 11:43:36 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Sun, 08 Sep 2002 15:43:36 GMT Subject: Using Python to call a DCOM server - "'Class not registered" References: <3D787D95.9000907@ob_scure.dk> <5%ce9.1272$_l1.2960@news-server.bigpond.net.au> <3D7A1359.4010607@ob_scure.dk> <3D7AFF61.7070005@ob_scure.dk> Message-ID: Thomas Jensen writes: > Searching for "unregister localserver" I found your book "Python > Programming on Win32" on O'Reilly :-) > If I can find it in Denmark, I think I'll buy it! You should, was my first python book, and really catapulted me into the language. It was easy to obtain in norway, so shouldn't be hard in Denmark either. -- Vennlig hilsen Syver Enstad From jepler at unpythonic.net Wed Sep 11 22:09:44 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Wed, 11 Sep 2002 21:09:44 -0500 Subject: ANN: Thinking in Tkinter In-Reply-To: <20020911150511.GA28720@unpythonic.net> References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> <20020911150511.GA28720@unpythonic.net> Message-ID: <20020911210943.D1555@unpythonic.net> (whoops, I had intended to send this to python-list) On Wed, Sep 11, 2002 at 10:05:53AM -0500, Jeff Epler wrote: > You'd have to read the tcl source for the button bindings to see what's > going on. I'll walk you through them ... > > > bind Button <1> { > tkButtonDown %W > } > bind Button { > tkButtonUp %W > } > bind Button { > tkButtonEnter %W > } > bind Button { > tkButtonLeave %W > } > > proc tkButtonDown w { > global tkPriv > set tkPriv(relief) [$w cget -relief] > if {[string compare [$w cget -state] "disabled"]} { > set tkPriv(buttonWindow) $w > $w configure -relief sunken -state active > } > } > > proc tkButtonUp w { > global tkPriv > if {[string equal $tkPriv(buttonWindow) $w]} { > set tkPriv(buttonWindow) "" > $w configure -relief $tkPriv(relief) > if {[string equal $tkPriv(window) $w] > && [string compare [$w cget -state] "disabled"]} { > $w configure -state normal > uplevel #0 [list $w invoke] > } > } > } > > proc tkButtonEnter w { > global tkPriv > if {[string compare [$w cget -state] "disabled"] \ > && [string equal $tkPriv(buttonWindow) $w]} { > $w configure -state active -relief sunken > } > set tkPriv(window) $w > } > > proc tkButtonLeave w { > global tkPriv > if {[string compare [$w cget -state] "disabled"]} { > $w configure -state normal > } > if {[string equal $tkPriv(buttonWindow) $w]} { > $w configure -relief $tkPriv(relief) > } > set tkPriv(window) "" > } > > When the pointer leaves or enters the button, tkPriv(window) is > set to that widget. When a mouse button is pressed in a button, > tkPriv(buttonWindow) is set. When the mouse button is released, and > window and buttonWindow both match the widget where the release took > place, the button's -command is invoked. > > These routines are actually slightly different for each of unix, mac, > and Microsoft Windows in my copy of tk8.3. > > In my opinion, it's great to understand this, and maybe to reimplement > it in Python as an exercise, but since the vast majority of any GUI > application should use the standard behavior for its components as > defined by the operating system/desktop environment, it makes much > more sense to me to start teaching Tk with basics like -command, -text, > -textvariable, the grid manager, and (in Python) things like Toplevel > subclasses with standard buttons and the like. > > Later, I might have a unit that "teaches" a compound widget like the > "shufflebox", which does require custom bindings such as doubleclick to > move selected items to the opposite box. > > Jeff From eugene1977 at hotmail.com Tue Sep 17 10:15:59 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Tue, 17 Sep 2002 14:15:59 +0000 Subject: question about dictionary type.. References: <61Jg9.16334$5r1.665293@bin5.nnrp.aus1.giganews.com> Message-ID: cool.. thx i read a python book while ago, and trying to refamiliaze myself with it recently, your solution looks so cool.. apreciate it.. have to spend some time what u did =) thanks From maxm at mxm.dk Wed Sep 4 06:12:30 2002 From: maxm at mxm.dk (Max M) Date: Wed, 04 Sep 2002 12:12:30 +0200 Subject: Why Python? References: Message-ID: <3D75DC8E.1060501@mxm.dk> Gerhard H?ring wrote: > Markus Jais wrote: >>so maybe you should learn both PHP and Python (and Ruby, of course :-) > > I'd skip PHP. But then, I'm biased. And proud of it :-P Well PHP will not teach you a lot as a programmer, but it can have good commercial, practical and pragmatic value. It is often used in the wild and it is nice to have a general feel for it. regards Max M From nanotech at europa.com Thu Sep 12 16:29:21 2002 From: nanotech at europa.com (czrpb) Date: Thu, 12 Sep 2002 13:29:21 -0700 (PDT) Subject: Help with regular expression using findall and .*? Message-ID: Could anyone help out with rewriting (still using regular expressions) the following so that it does not cause an exception: import re s1=('macro\n'+'a'*200+'\norcam\n')*10 s2=('macro\n'+'a'*20000+'\norcam\n')*10 p=re.compile(r'macro.*?orcam',re.DOTALL) for x in re.findall(p,s1): print x for x in re.findall(p,s2): print x thanks!! Quentin Crain ------------------------------------------------------------------------- I think we are miscommunicating. I actually expected some confusion with my last response and I am not sure if there actually was some, but I feel like it. So, my message is going to assume I did not make my points, but perhaps you did understand me. If so, then that means *I* did not understand *YOUR* response - in which case you will need to rephrase. From jnana4 at DELETEhotmailCAPS.com Tue Sep 24 00:32:37 2002 From: jnana4 at DELETEhotmailCAPS.com (jano) Date: Tue, 24 Sep 2002 04:32:37 GMT Subject: cgi post problem Message-ID: Hi, I am trying to post a form to a cgi script. The form is as follows:
At the other end, the updatexml.py file currently just echoes back the form data, as follows (with some wrapper code): #!/usr/local/bin/python import sys, traceback, cgi excText = "" def main(): global excText try: form = cgi.FieldStorage() keys = form.keys() print "Content-type: text/html\n\n" print(""" CGI exception """) print "

** ",keys," **

" print "" except: print "Content-type: text/html\n\n" import time errtime = '--- '+ time.ctime(time.time()) +' ---\n' errlog = open('cgi_errlog', 'a') errlog.write(errtime) traceback.print_exc(None, errlog) errlog.close() print(""" CGI exception
""") print "

Sorry, a problem was encountered running the cgi script:


\n" if excText != "": print "

", excText, "

" print "
" if __name__ == "__main__": main() ================== The output of the script is always an empty []. Does anybody know what the problem might be? In a previous thread, the problem was that the user had instead of using name ="", but that is not the case here. Thanks for any help. I have checked usenet and the python faq and used google, to no avail. jano From marklists at mceahern.com Thu Sep 19 14:00:52 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 19 Sep 2002 13:00:52 -0500 Subject: finding last match in a file In-Reply-To: Message-ID: > I have a number of very large files where I have to find the last line > which matches a certain experssion. Currently I'm simply opening the > file and looping through it noteing each time a line matches and at the > end of the loop I see which was the last match. However this is very > slow and inefficient. Is there some way to read through the file > backwards and simply find first match starting from the end of the file. > The files are really too big to read the entire thing into memory. Well this is worth considering: http://groups.google.com/groups?selm=000101bd9b36%2405590020%2451a22299%40ti m // m - From aglyportREMOvethispart at nospam.yahoo.com Thu Sep 5 18:13:49 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Thu, 05 Sep 2002 15:13:49 -0700 Subject: Memory fault - core dumped while compiling python 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> <3D765A05.6030004@nospam.yahoo.com> <3D768753.8030302@nospam.yahoo.com> <3D76A139.1030304@nospam.yahoo.com> <3D76BC56.7020503@nospam.yahoo.com> Message-ID: <3D77D71D.3060305@nospam.yahoo.com> Bengt Richter wrote: > On Wed, 04 Sep 2002 19:07:18 -0700, Anton Graph wrote: > > >>Bengt Richter wrote: >> >>>On Wed, 04 Sep 2002 17:11:37 -0700, Anton Graph wrote: >> > [...] > >>>How about >>> cc -v >>>? >>> >>>what does >>> >>> which cc >>> >>>give you? And >>> >>> which cc | xargs -ld >>>? >> >> >> >>$ which cc >>/bin/cc >>$ /bin/cc -v >>Usage: cc [ options ] files ... >>$ which cc | xargs -ld >>xargs: d is not a valid number of lines, must be a positive integer >> > > Oops, sorry, that should have been > > which cc | xargs ls -ld > > Regards, > Bengt Richter which cc | xargs ls -ld lrwxrwxrwx 1 root sys 31 Oct 26 1999 /bin/cc -> /opt/K/SCO/unixds/5.1.1A/bin/cc cc -V SCO UNIX Development System Release 5.1.1A 27Jul98 Usage: cc [ options ] files ... From brian at sweetapp.com Tue Sep 3 16:43:20 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 03 Sep 2002 13:43:20 -0700 Subject: PyListObject & C Modules In-Reply-To: Message-ID: <006701c2538a$89f12630$df7e4e18@brianspiv1700> Martin, are you sure that you don't have a ref counting bug in your example? Since PyList_GetItem borrows a reference and PyList_SetItem steels one, you need to do an incref in between. Here is my modified version (not tested or even compiled): PyObject* get_first_elem(PyObject *unused, PyObject *args) { PyObject *list; PyObject *first; PyObject *result; if(!PyArg_ParseTuple("O", &list)) return NULL; if(!PyList_Check(list)) { PyErr_SetString(PyExc_TypeError, "get_first_elem expects a list"); return NULL; } if(PyList_Size(list) == 0){ PyErr_SetString(PyExc_ValueError, "empty lists not allowed"); return NULL; } first = PyList_GetItem(list, 0); + if (first == NULL) return NULL; result = PyList_New(1); if (!result) return NULL; + Py_ADDREF(first) - PyList_SetItem(result, 0, first); + if (PyList_SetItem(result, 0, first) != 0) { + Py_DECREF(first) + Py_DECREF(result); + result = NULL; + } return result; } Cheers, Brian From ianb at colorstudy.com Tue Sep 17 15:22:55 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 17 Sep 2002 14:22:55 -0500 Subject: CGI question In-Reply-To: References: Message-ID: <1032290575.8110.159.camel@dsl-65-184-205-5.telocity.com> On Tue, 2002-09-17 at 13:04, John D. Boy wrote: > I am working on a simple CGI script to use as a framework for a website > of mine. Basically, I want it to work as follows: When somebody accesses > the site, a CGI (called e.g. index.py) is run. It takes an html-template > and fills it with content from another file, called e.g. index.dat, and > returns the completed html-document. When I want to present another > page, I want the url to look like this: http://my.domain.name/?page. In > that case, index.py would fill the same template with the content of a > file called e.g. page.dat. BTW, I wouldn't recommend doing it this way. If you have a cgi script at, say, /page.py, you can access URLs like /page.py/path/to/something -- "/path/to/something" will be stored in os.environ['PATH_INFO']. Then your URLs will look like real URLs, and not like queries. And for mod_rewrite people, if you want to serve the root of your domain off that script, I believe this will work: RewriteEngine On RewriteRule ^/(.*)$ /path/to/page.py/$1 (I don't think you can use Alias in this case, but I might be wrong) Ian From ataylor at ucsd.edu Fri Sep 27 18:18:13 2002 From: ataylor at ucsd.edu (Adam Taylor) Date: 27 Sep 2002 15:18:13 -0700 Subject: What does Python fix? Message-ID: > Syntax is skin deep. I'm not part of the "Lisp's problem is Lots of Insipid > Stupid Parentheses" crowd myself, so I never expected that Dylan's choice to > use algebraic syntax would do it good in the end; to the contrary, it > alienated old-time Lisp purists, who were Dylan's best hope for > wider-than-it-got adoption. > > Any language even *inspired* by Lisp is doomed to eternal obscurity. The > Lisp'ers have been gnashing their teeth over "why?!" for decades. It's no > longer my job to explain it, since I abandoned Lisp years ago (I couldn't > understand the concept of nested parentheses ). I'm curious to read a bit more about why Tim Peters (and presumably others) think that Lisp-inspired languages (even non-prefix ones) are doomed to eternal obscurity. Would anyone care to comment and/or give me some pointers to commentary on the subject? It sounds like Tim doesn't want to spend too much time getting into it (which is entirely fair), but maybe others can 'channel' for him, or just point me towards already-written opinions on the matter? Thanks, Adam ----- [Tim] >> And Dylan's subsequent meteoric rise to world domination proved that >> the "Lisp's problem is Lots of Insipid Stupid Parentheses" crowd was >> right all along . [Steven Majewski] > But the syntax that won in Dylan was the algebraic C-like one, NOT > the S-expr syntax. Yup. > How do you explain that ? As my sig said, >> the-reason-lisp-excels-at-getting-ignored-isn't-skin-deep-ly y'rs - tim Syntax is skin deep. I'm not part of the "Lisp's problem is Lots of Insipid Stupid Parentheses" crowd myself, so I never expected that Dylan's choice to use algebraic syntax would do it good in the end; to the contrary, it alienated old-time Lisp purists, who were Dylan's best hope for wider-than-it-got adoption. Any language even *inspired* by Lisp is doomed to eternal obscurity. The Lisp'ers have been gnashing their teeth over "why?!" for decades. It's no longer my job to explain it, since I abandoned Lisp years ago (I couldn't understand the concept of nested parentheses ). leaving-lisp-angst-to-the-lispers-ly y'rs - tim From martin at v.loewis.de Wed Sep 4 03:06:24 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Sep 2002 09:06:24 +0200 Subject: simple xml pickle References: Message-ID: Michael Stenner writes: > Does anyone know of anything else? PyXML offers xml.marshal.generic, and xml.marshal.wddx (which supports the WDDX DTD). They require xml.sax, but are otherwise "mostly" standalone (meaning that they could be ported to pure Python 2.x with little effort - if you do that, please consider contributing your patches). HTH, Martin From roy at panix.com Fri Sep 6 21:01:50 2002 From: roy at panix.com (Roy Smith) Date: Fri, 06 Sep 2002 21:01:50 -0400 Subject: Larry Wall's comment on python... References: Message-ID: Tim Daneliuk wrote: > Well, that's true, but for all of its similarity to line noise, perl has > been an enormous contribution to our profession/community. I would never want > to diminish Wall's stature, therefore. There is no doubt that Perl was a major breakthrough. It sure beats the horrible sed/awk/grep/shell disasters we used to write. The fact that it's showing its age and better things have come along (building on Perl's success and learning from its mistakes) does not in any way diminish the magnitude of Larry's contribution. Not to mention rn and patch (and probably some other stuff I'm forgetting at the moment). > I find almost all compiled languages (even C) intrusive > when writing code for embedded systems. Back in the days when a pdp-11/45 was the hot platform to run Unix on, I used to do a certain amount of M-6800 programming (note: two zeros, not three). I found the best way to write code was to write it in a (self-imposed) simplistic subset of C, and then hand-compile it into assembler. This let me write the basic control logic in a reasonably expressive language, but kept me close to the bare machine. It was almost like flowcharting in pseudocode. Writing for a machine which only has 256 bytes of RAM gives you a somewhat different outlook on programming :-) From Oschler at earthlink.net Sun Sep 1 13:17:56 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 1 Sep 2002 13:17:56 -0400 Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: "Gerhard H?ring" wrote in message news:slrnan4dl3.18h.gerhard.haering at lilith.my-fqdn.de... > >>> class Foo: pass > ... > >>> foo = Foo() > >>> foo.bar() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: Foo instance has no attribute 'bar' > >>> def bar(self): print "bar" > ... > >>> Foo.bar = bar > >>> foo.bar() > bar > >>> Gerhard, Thanks but I need a little bit more detail. Suppose I want to do it from within code? For example, I create a function called AddBarToFoo(FooObject), that given a object of type Foo (FooObject) adds the Bar method to it dynamically, what would be the syntax then? Would I have to put the method declaration code, which you show being typed in to the interpreter, in a string and then eval/exec it? Is there a more convenient way than that? thx From Oschler at earthlink.net Tue Sep 10 15:31:07 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Tue, 10 Sep 2002 19:31:07 GMT Subject: Reset a generator function? Message-ID: <%Lrf9.30107$w51.7961593@news2.news.adelphia.net> How can I reset a generator function so that it begins yielding values as it did when first called? thx From syver-en+usenet at online.no Sun Sep 8 12:45:19 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Sun, 08 Sep 2002 16:45:19 GMT Subject: Mimicing intepreter import behaviour in embedded application Message-ID: I have embedded python in a C++ application. Now I want python code running in this application to reach modules in the same way as code running in the standard interpreter. So I set up a test comparing the sys.path variable under python and my application with the intpreter embedded. Most of the two sys.path's are equal except: Regular python: Embedded: ('d:\\devtools\\python22\\DLLs', 'D:\\devtools\\Python22\\Lib'), ('d:\\devtools\\python22\\lib', 'D:\\devtools\\Python22\\DLLs'), ('d:\\devtools\\python22\\lib\\lib-tk', 'D:\\devtools\\Python22\\Lib\\lib-tk'), This line is caused by the differing locations of the .exe files ('d:\\devtools\\python22', 'h:\\mydocuments\\Kode\\C++\\Applications\\pyexe'), ('d:\\devtools\\python22\\lib\\site-packages\\Numeric', 'D:\\devtools\\Python22'), Here I miss the .pth file that I have for PIL. ('d:\\devtools\\python22\\lib\\site-packages\\PIL', 'D:\\devtools\\Python22\\lib\\site-packages\\Numeric')] Is there a way to more closely mimic "the real interpreter"? -- Vennlig hilsen Syver Enstad From martin at v.loewis.de Mon Sep 2 01:59:20 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Sep 2002 07:59:20 +0200 Subject: Problem compiling Secret Labs RexExp module in pyamazon package References: Message-ID: "Robert Oschler" writes: > I'm not looking for anyone to give me a source code correction. What I > would like is to know how to do one of the following: contact the makers of > xml.dom or Secret Labs and report this? Learn if this is a known problem > due to some Python configuration issue that I need to follow up on. Etc. > In other words what I should generally do to hunt this down and fix it? Posting to this group is a good starting point. I'm surprised you are getting such an error. If I do Python 2.1.3 (#2, Aug 27 2002, 09:38:37) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import re >>> re.compile("&#(/d+);") it works fine for me, on Python 2.1.3. Are you saying that this fails for you? Could you try Python 2.1.3? Regards, Martin From tdelaney at avaya.com Fri Sep 20 00:22:24 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 20 Sep 2002 14:22:24 +1000 Subject: Destructor never called ??? Message-ID: > From: Tim Roberts [mailto:timr at probo.com] > > Well, then, what was all the fuss about deterministic > desctructors in the > newsgroup last year or so? Has this changed, or am I just > remembering this entirely wrong? I'm not getting into this again ... the people (myself included) advocating *non*-reliance on timely finalisation are perfectly aware of CPython's *current* behaviour, which does (in *most* cases) have timely finalisation. Tim Delaney From mhammond at skippinet.com.au Tue Sep 17 23:28:40 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 18 Sep 2002 03:28:40 GMT Subject: Calling Python from C# - please help References: <6de16ac9.0209130508.5d1b56c6@posting.google.com> <0iCg9.2350$Ee4.6516@news-server.bigpond.net.au> <3D82FA5B.3050003@mxm.dk> <3%Dh9.15217$Ee4.45118@news-server.bigpond.net.au> <3d877db8_5@news.bluewin.ch> Message-ID: Samuele Pedroni wrote: > How were you going to support eval and exec? The compiler itself is written in CPython. The intention was to get the compiler good enough to compile itself - then we will have a .NET compiler able to be built into the Python runtime. exec and eval would leverage this. > For the moment the unload granularity of .NET is AppDomains only and only > upon explicit request, and types/modules/assemblies are not garbage > collected but simply live as much as the AppDomain, App Domains can be dynamically created tho, which may help. > that's OK for static languages, or environments with a clear run/design time > distinction (one can setup an AppDomain and tear it down for each > run-cycle), or for running scripts in isolation but not if one wants IL/JIT > speed for a enviroment that allows for redefinitions and eval, ... > > In Jython we create Java bytecode and dynamically load classes for all the > code, also eval code because in Java classes are elegible for garbage > collection. > > In .NET it seems one needs a pure interpreter that does not compile to IL > for exec and eval support, and that seems what JScript does for jsc compiled > code containing eval, that means the script is compiled but the evaluated > code is only interpreted, Im not really convinced of that. Reflection::Emit has IL generation capabilities purely for "dynamic" code - the example used in their docs is that regex engines could compile down to IL on-the-fly. > otherwise a long running process using eval could go out of memory. > > That's something people wanting to write a feature complete impl of Pyhton > for .NET should consider or wait MS to implement a more > dynamic-environment-friendly unload policy. Yes, I see your point, but AppDomains are really quite powerful. I believe there are no restrictions between cross domain calls. Managing the lifetime of the dynamically created domains may be an issue though. Thanks for the comments, Mark. From shalehperry at attbi.com Fri Sep 6 11:30:11 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 6 Sep 2002 08:30:11 -0700 Subject: Getting a proccesses ID In-Reply-To: References: Message-ID: <200209060830.11844.shalehperry@attbi.com> On Friday 06 September 2002 08:05, Micah Mayo wrote: > Hi, > > I'm writing a little tool for SysAdmins on FreeBSD - I'm trying to make > it as portable as possible(as far as the unices go), and have come upon > a problem - one of the things this tool does is restarts various deamons > on the system, in order to do that I have to send a killsignal to the > pid. The problem is getting the process id - right now I've got a hack > using ps, grep, and awk, which I doubt will translate well to other > flavors of *nix because they all seem to have their own method of > delivering info via ps. Can anyone tell me a cross platform way of > grabbing a particular processes ID > > Here's what I'm doing now, by the way: > > pid = os.popen("ps -x | grep sshd | grep -v grep | awk '{ print $1 }'") > pid = pid.atoi() >>> import os >>> os.getpid() 29421 (-: From skip at pobox.com Thu Sep 19 15:30:54 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 19 Sep 2002 14:30:54 -0500 Subject: Larry Wall's comment on python... In-Reply-To: References: Message-ID: <15754.9710.139758.17475@12-248-11-90.client.attbi.com> Christopher> For instance: Christopher> {paragraph Hello {bold Bold} World!} Christopher> Although it might be annoying to have to type the curly Christopher> braces, I really don't know what the alternative would Christopher> be.... I don't think there is a way to do this kind of Christopher> thing using Pythonic syntax. (Danger Will Robinson! I thought curl was a URL fetcher. I never heard of curl the language. The above fragment is the only curl I've ever seen. That said...) Why wouldn't paragraph: Hello bold: Bold World! work? :-) -- Skip Montanaro - skip at pobox.com The need for gutters to be cleaned is directly proportional to how hard it happens to be raining at the moment. From dwelch91 at nospam.attbi.com Sat Sep 21 10:33:00 2002 From: dwelch91 at nospam.attbi.com (dwelch) Date: Sat, 21 Sep 2002 14:33:00 GMT Subject: PyQt setup on Linux Mandrake 8.2 References: <3D8B4898.20808@nospam.attbi.com> Message-ID: <3D8BC2F4.8080107@nospam.attbi.com> Armin Steinhoff wrote: > dwelch wrote in message news:<3D8B4898.20808 at nospam.attbi.com>... > >>I would like to setup PyQt 3.4 on my Mandrake 8.2 box. I am having >>difficulty, and I am worried that if I do the wrong thing, KDE will go >>belly-up on me since it is Qt based. >> >>First, question is: why isn't QTDIR defined by default? >> > > PyQt works with Qt2.x.x and Qt 3.x.x ... so YOU have to choose the > correct directory. > > >>Is QTDIR a >>runtime setting or a development setting? >> > > Both .. > > >>So I set QTDIR to /usr/lib/qt2 (that seems to be where the libqt2 RPMs >>files are). Next question is: Since I have libqt2 already on my system, >>how do I add the Qt development pieces without screwing up Qt/KDE? Is >>/usr/lib/qt2 even the correct location? >> > > Yes ... if you want to use only the latest version of Qt 2.x.x > > >>When I run SIP 3.4 build.py, it complains about tmake not being >>available. Is tmake included with Qt2 development files? >> > > It's available at the Trolltech homepage or its mirrors. > > >>SIP doesn't >>seem to have any docs, so I'm not sure how to proceed. >> > > Nomally you haven't to care about SIP .. > > > >>Also, my RPM manager says that I have libqt2-devel (2.3.1-29mdk) >>installed. No tmake listed in the files, though. And, PyQt-devel >>(2.5-1mdk) is also listed as installed, but there aren't any .py files >>included, only .sip files (I found this curious). >> > > Corious ... there must be examples included. > > I would suggest to dowload the latest version of Qt from the Trolltech > homepage, just for a simple and clean recompilation. > > And do the same with SIP and PyQt from the Riverbank homepage ... > > It seems to be better to forget that outdated stuff provided by the > Mandrake distribution ... > > Armin > > >>Installing software on Linux makes me feel like such an idiot! >> >>Any help or pointers would be much appreciated. >> >>Don >> OK, I found and installed tmake. Now, SIP can't find some of the Qt pieces it needs. So, I still don't understand the situation with Qt. Is it really possible to install and run my applications that I write with say Qt 3.0.5, when KDE on my system is using Qt 2.3.1? How does/would KDE know which version to use? How will my apps know what version to use? I am assuming there can only be one QTDIR active on a system at a time... Thanks for the help, Don From somebody at hotmail.com Wed Sep 4 08:23:25 2002 From: somebody at hotmail.com (stephan) Date: Wed, 04 Sep 2002 14:23:25 +0200 Subject: newsgroup for zope Message-ID: Hi perhaps a stupid question, but does there exist a newsgrup for zope centric items? bye Stephane From jb at cascade-sys.com Thu Sep 26 00:34:22 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 25 Sep 2002 21:34:22 -0700 Subject: Getting started References: <3D920950.323B25B3@alcyone.com> Message-ID: <3D928E4E.3090209@cascade-sys.com> Alex Martelli wrote: >Erik Max Francis wrote: > > >>This is simply a case of differing terminology. >> I agree the whole is ultimately a difference of terminology but the choice is not arbitrary. I've tried to search out and establish the true meaning of the term in an intellectually honest fashion-- I certainly was NOT simply making up and promoting some arbitrary definition of my own. >Bingo -- and I think that if one works through all the references I >gave one will see Cardelli cover all the major issues, though he does >not do so in any single one of them and his exact terminology may >differ from mine, yours, James's, "Some authors'" > I'll stipulate to this. >(Some authors >refer to languages with latent types as weakly typed or dynamically typed >languages.) > About 1/4 of the google references I found used this alternative. Now I better understand why. However, it's better established than the oddball third alternative you've been struggling to defend. >I don't think it's all that pragmatically useful to have >a black/white definition for properties, in real life -- it may be >good maths (or at least, much-simpler maths) > I thought we were talking Computer Science, or at least Computer Programming, which is somewhat more along the lines of maths rather than real life. Some properties are intrinsically boolean, others are not. "Type Safety", "Strongly typed" or "Weakly typed" have definitions that make them boolean properties. >It may be important to know the extent and character of the deviation, >of course. For example, [...] > Absolutely true. The "degree of safeness" or the "list of things that make a language weakly typed," or the "quality of a language's type or object model" are interesting non-boolean properties. But this is not "weak typing". >On the other side of the fence, it's clearly trivial to design >a language which can have no type problems -- > True. >just give the language >just one type, period. It's even easy for the compiler to ensure >that you are indeed using that single type (as it's the only one >you have) wherever it's required (i.e., everywhere). It's of no >bloody practical use whatsoever, of course. > False. Neither sufficient nor necessary. E.g., Unix's "BC" arbitrary precision arithmetic calculator had but a single data type and yet it was extremely useful. >Eg., in another >post James claimed that standard C has no objects -- >[...] >Clearly, James meant "objects as in OO", > You are correct in what you say above and, particularly that the meaning of my alliterative use of "objects" was clear in context. My point was that many references including Cardelli's "Type Systems" specifically cite C as an example of a "weakly typed" language. Since C lacks "objects" (in the OOP sense) then "weakly typed" clearly does not have anything to do with the relative quality of a language's object model (which was your position at the time). Since it was your assertion about OO which I was refuting, my abbreviation C "objects" clearly meant C's OO features. Ha! And I was afraid you were going to accuse me of saying "the original C language was well defined". ;o) Which I did. =8^O. But it was completely tangent to the main argument. Warmest Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From tundra at tundraware.com Tue Sep 3 17:30:03 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: Tue, 03 Sep 2002 21:30:03 GMT Subject: [ANN] 'waccess' 2.0 web log analyzer released Message-ID: Version 2.0 of the 'waccess' web log analyzer is released at: http://www.tundraware.com/Software/waccess/ This version has a bunch of new features and options. This should be it for quite a while barring bugfixes. The FreeBSD port has also been submitted. Summary: -------- 'waccess' is a quick way to check a web access log for particular "hits" or accesses. 'waccess' will search the log looking for and displaying all the access records which contain any of the search keys you name on the command line. By default, a summary of its findings - including total number of records processed, number of accesses per search key, and number of unique IPs accessing each search key - is printed. A rich set of options let you customize 'waccess' to do things the way you like them including setting case sensitivity, ignoring selected address spaces in the analysis, and selecting which log file to process. 'waccess' is not a replacement for a serious web log analysis tool, but is surprisingly useful for "quickie" lookups and day-to-day systems managment. 'waccess' is written in Python and needs a reasonably current version of the langugage on your machine. 'waccess' was written for and tested on FreeBSD 4.6R and is set up to process Apache access logs. However, the code is clearly structured and should port to other systems and web servers pretty trivially. -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From max at alcyone.com Tue Sep 24 00:10:28 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 23 Sep 2002 21:10:28 -0700 Subject: confusion about opening files References: Message-ID: <3D8FE5B4.3FF00F5F@alcyone.com> Mark McEahern wrote: > I read somewhere that 'file' was preferred to the use of 'open' > because of > the symmetry to the type: > > >>> f = file("junk.txt") > >>> type(f) > > > Anyway, that's how I've trained myself to spell 'open'. It probably is, but only works in more recent versions of Python. At any rate, it wasn't what the original poster was asking about, so I didn't bother addressing it. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ The average dog is a nicer person than the average person. \__/ Andrew A. Rooney Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/ A personal guide to Counter-Strike. From revyakin at yahoo.com Mon Sep 30 16:32:18 2002 From: revyakin at yahoo.com (revyakin) Date: 30 Sep 2002 13:32:18 -0700 Subject: xml.dom.minidom parser error Message-ID: Hi all, We recently upgraded from OS X to 10.2, and from python 2.1 to python 2.2. After that my xml parser stopped working: when I attempt to parse an xml string I get the error shown below. I don't know whether it matters, but we also installed PIL recently, and there's a reference to PIL in the error log as well. Any ideas what this could mean? Writing a parser by myself does not sound exciting. Andrey >>> q=xml.dom.minidom.parseString('') Traceback (most recent call last): File "", line 1, in ? File "/BinaryCache/python/python-3.root~193/usr/lib/python2.2/xml/dom/minidom.py", line 965, in parseString File "/BinaryCache/python/python-3.root~193/usr/lib/python2.2/xml/dom/minidom.py", line 951, in _doparse File "/BinaryCache/python/python-3.root~193/usr/lib/python2.2/xml/dom/pulldom.py", line 340, in parseString File "/usr/lib/python2.2/site-packages/PIL/__init__.py", line 93, in make_parser # ;-) xml.sax._exceptions.SAXReaderNotAvailable: No parsers found From aleax at aleax.it Wed Sep 18 16:56:17 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 20:56:17 GMT Subject: Copy with __slots__ References: <3K1i9.110352$ub2.2335897@news1.tin.it> Message-ID: Christian Tismer wrote: ... > You can get this to the single slot-level speed by doing > the slot grabbing phase of above once, after the class It's an important speed-up, yes -- but still quite a bit slower than dealing with a single slot. > speed can be found by not caching the __slots__ but their > get/set wrappers and then just calling these with the new > instance... I've done that too (as a function, but would be trivial to wrap as a custom metaclass): class acceled(withslots): def __copy__(self): result = self.__class__.__new__(self.__class__) for get, set in self._accel: set(result, get(self)) def makeaccel(aclass): slot_names_seen = {} slot_gets_sets = [] for base in aclass.__mro__: for s in getattr(base, '__slots__', []): if s in slot_names_seen: continue slot_names_seen[s] = True slot = getattr(base, s) slot_gets_sets.append((slot.__get__,slot.__set__)) aclass._accel = slot_gets_sets makeaccel(acceled) [alex at lancelot ~]$ python -O slorno.py 1.10 noslots 0.67 withslots 0.37 acceled [alex at lancelot ~]$ python -O slorno.py 1.14 noslots 0.69 withslots 0.37 acceled [alex at lancelot ~]$ python -O slorno.py 1.10 noslots 0.68 withslots 0.36 acceled Not the 0.28 or so that I got by "unwrapping the loop" (i.e., just coding out the assignment for each slot!), but still, an important speedup, as I said. Thanks on behalf of the OP! It's not clear from the above what proportion of the gain is due to just doing some of the work in advance, what to extracting the getter and setter, what simply to avoidance of double work that class withslots did because it copied attribute s1 twice. As the OP clearly needs practice in measuring Python runtimes (he guessed that the 0.28 blazing-fast verson would be SLOWER than the original 1.10 one, and didn't even THINK of doing a measurement to double check his intuition...!!!), I guess I'll leave this homework to him as a useful exercise:-). Alex From clspence at one.net Wed Sep 11 16:53:09 2002 From: clspence at one.net (Chris Spencer) Date: 11 Sep 2002 15:53:09 -0500 Subject: How do I capture just a single keystroke? Message-ID: I'd like to implement a "Press any key to continue..." type function, but it seems like all of Python's input mechanisms REQUIRE the enter key to be hit. If this is documented clearly somewhere, then you have my apologies for wasting bandwidth. Chris. From gua81 at XXXyahoo.com Thu Sep 26 04:24:35 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Thu, 26 Sep 2002 18:24:35 +1000 Subject: Getting last char in string. References: Message-ID: Worked like magic Thanks dude! "James Kew" wrote in message news:amueqq$94qgr$1 at ID-71831.news.dfncis.de... > "CheapSkate" wrote in message > news:amue3q$h59$1 at lust.ihug.co.nz... > > Hi, im writing a simple method that takes in a string input and check if > the > > last charcter is an '/' > > then it will do A else do B > > > > my Q now is how to get the last char??? > > if stuff[-1:] == '/': > > or > > if stuff.endswith('/'): > > -- > James Kew > james.kew at btinternet.com > > > From johnroth at ameritech.net Thu Sep 26 10:15:38 2002 From: johnroth at ameritech.net (John Roth) Date: Thu, 26 Sep 2002 10:15:38 -0400 Subject: object changing itself to another object References: Message-ID: "Glen Murphy" wrote in message news:amu0lv$6ac$1 at otis.netspace.net.au... > I'm creating a program that takes user input, and passes it to an object - > however, I want that object itself, and not the parent to change where that > input goes. In the highly simplified example below, I would like the output > to be "Obj1","Obj2","Obj1" - but not suprisingly, I just get Obj1, Obj1, > Obj1 > > > ### code begin ### > > class Obj1: > def key1(self): > # do obj1 specific stuff > self = Obj2() > print "Obj1" > > class Obj2: > def key1(self): > # do obj1 specific stuff > self = Obj1() > print "Obj2" > > a = Obj1() > > # simulate user keypresses > a.key1() > a.key1() > a.key1() > > ### code end ### > > I know I could achieve the result I want by doing horribly complicated trees > of ifs and such, but I'd like my code to be nice and expandable (in this > example, to easily add new Objs). I've looked through the Python FAQ, Google > Groups and Various O'Reilly books, but I don't really know the terminology > for what I'm looking for, so I haven't found anything so far, so does anyone > have any pointers? > > Any help would be greatly appreciated, > Cheers, > Glen > > -- > Glen Murphy, http://glenmurphy.com/ It's a standard pattern, check out the Patterns book. Unfortunately, my copy is in a storage locker on the other end of the continent, so I can't give you the name off the top of my head. What it requires (I believe) is a level of indirection. The top level is essentially a Facade that calls the real object. You can then change the real object to anything you want as long as it understands the method calls the Facade object makes. John Roth John Roth > > From thoa0025 at mail.usyd.edu.au Thu Sep 12 05:58:29 2002 From: thoa0025 at mail.usyd.edu.au (:B nerdy) Date: Thu, 12 Sep 2002 09:58:29 GMT Subject: [xml.dom.minidom] why cant it parse '&' Message-ID: <9zZf9.24873$_l1.66951@news-server.bigpond.net.au> im using the minidom.parseString() to parse the following text Congo Mombo - Guitar Gable & The Musical Kings Various blues 12 Westwood 2002-03-11 when it comes to the '&' it throws an exception. is there any way around this problem?? cheers asap From richie at entrian.com Tue Sep 17 05:48:15 2002 From: richie at entrian.com (Richie Hindle) Date: 17 Sep 2002 02:48:15 -0700 Subject: Windows AutoRunning Python Hello -- feedback requested References: Message-ID: <8a6ba1da.0209170148.23bca1e8@posting.google.com> Dennis, > the EXE displays "hello" in a browser window and shows > its running directory as evidence that os.py is functioning. I like it. I think using a web browser as a user interface is an excellent way to go for some applications. Every week someone here asks "What's the best GUI toolkit for Python?" and no-one ever says "Netscape" or "Internet Explorer", but given a system like yours plus a framework for building an HTML user interface (based on one of the many web application frameworks for Python) I think this system is just as valid as Tk, wxWindows, Qt or whichever other 'real' toolkit you care to name. Does your system have mechanisms for serving up forms and accepting data back from the user, or is it simply a toolkit for distributing and running browser-based code? My gut feeling is that the latter would be better - sufficiently generic that any Python web application framework could be built into it. Zope-based Windows applications, anyone? -- Richie Hindle richie at entrian.com From mcherm at destiny.com Tue Sep 17 16:09:33 2002 From: mcherm at destiny.com (Michael Chermside) Date: Tue, 17 Sep 2002 16:09:33 -0400 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: Ian Bicking writes: >It has been simplified, but I don't think that changes anything with >regard to getting it into standard Python -- the same barriers still >exist. Martin v. Loewis wrote: > You are making these barriers up in your mind. I don't know why you > are doing that, though. Okay, let's see if we can settle this... because I think it has real potential. I am going to pose a hypothetical situation... please don't argue about whether these conditions are true now, or whether they will be true, but take these as assumptions: (1) Some version of Stackless consists of a quite small non-complicated patch onto C-Python. (2) The default behavior of this Stackless is to NOT allow stack switching... it must be enabled explicitly to be used. (3) Someone (probably NOT Christian) is willing to take on the job of merging it into the core and maintaining it afterward. (4) Stackless works on some architechures (including at least X86, Sparc, PPC and Cygwin). But it does NOT work on some other architectures. So (rather like the thread package) it is not as portable as Python itself. (5) Good reasons exist why Stackless CANNOT be implemented in Jython, in Python for .NET, or other Python implementations -- it's a C-Python-only thing. The question is this: Would the advantages of making Stackless part of standard Python outweigh the disadvantages of non-portability and C-Python specificity? If the answer is "NO", (and I can see good reasons why it would be) then no one need bother worrying about integrating Stackless into the standard. Let it live a separate existance! If the answer is "YES" (and I can see other good reasons why THAT might be) then integration MIGHT be possible, but there's no reason why it has to be, or needs to be hurried. It can wait until someone steps steps up to make (3) take place. And I agree with Christian's sentiment: > Please let me stay what I am: The one who writes Stackless > Python, supports and maintains it. I really do not take > responsibility for being standard or non-standard. ... leave Christian to do what he's doing well, and let someone else worry about possible integration. -- Michael Chermside From mcfletch at rogers.com Sat Sep 7 06:38:43 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 07 Sep 2002 06:38:43 -0400 Subject: Python from C/SDL References: <3D793B29.3198AB0E@ihug.co.nz> <006101c25626$56c9b1c0$0101010a@local> Message-ID: <3D79D733.1070405@rogers.com> I'll just deal with the OpenGL stuff. Basically, PyOpenGL-based apps should be able to work like this: c draw(): context = new MyContext; context.set_current(); err = Py*_Call*( size ); python: def render( dimensions ): do_your_rendering_here() return c: swap_buffers(); context.unset_current(); So, you'd likely need to find, somewhere in pymol, a function to call which is _after_ the Python context setup and set_current() which you can call. Depending on the architecture of pymol, that's likely to require at least sub-classing, and possibly some re-writing, as most rendering libs go out of their way to be sure they're using the "right" context before any attempt to render, and most apps assume they'll be using a context they set up. You'll likely need to pass size of the window from your code, as some renderers assume they know the current size of the rendering context (which they won't if they aren't getting their resize events). For example, in OpenGLContext, you'd subclass a Context and override setCurrent and unsetCurrent to do nothing (or more professionally, you'd create C "extending" functions that set the appropriate context for your app, which would allow the Python system to have its own contexts alongside yours if you wished). In other frameworks those calls aren't actually split out into easily overridable methods (it's only required if you're targetting multiple GUI libs), so you might have to re-write anywhere you see "set current" methods called. Would suggest contacting the creator of PyMol for suggestions where to apply your lever. For a "full" job of creating a PyOpenGL embedded system, you'd also provide initialisation/creation functions to allow Python code to create a context within your app (e.g. setting display modes). There are similar questions asked once in a while, but not particularly with pymol AFAIK. "How do I embed PyOpenGL apps" is the basic template. Suppose I should create a tutorial for it, but I've never done it directly myself (though conceptually every context in OpenGLContext is "embedded" in the GUI library it uses, since those are all C libs, it's just that I do the "calling into Python" from the libs own Python wrappers). HTH, Mike BTW: out of town in a few minutes, so won't be available to clarify anything 'til Monday, sorry. Chris Gonnerman wrote: > ----- Original Message ----- > From: "Gib Bogle" > > >>Hi, >> >>I am a complete beginner with Python. My interest in it is focussed on >>a great piece of open-source software called pymol, a system for >>visualization of molecules that uses Python and OpenGL. I'd like to get >>access to pymol's graphical functions from my own program, which is >>built from C, SDL and OpenGL. > ... >>I will not want to use the GUI at all. SDL would >>create the surface(s), and handle the buffer swapping. My goal is to be >>able to send a request to the pymol API asking for a frustum view to be >>rendered on the provided surface. >> >>Sorry if my question is one that gets asked and answered frequently. If >>there is a place where this has been dealt with please direct me. > > > Never heard this one before... > > Good luck! > > > Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net > http://newcenturycomputers.net > > -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From Oschler at earthlink.net Wed Sep 11 18:19:20 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Wed, 11 Sep 2002 22:19:20 GMT Subject: SuSE 7.3 Yast2-able Python 2.2.1? Message-ID: Anybody seen a "yast2" friendly version of Python for SuSE Linux 7.3 Pro? If so please give me the URL or ftp site. I tried using the KRUD rpm's but the OpenSLL missing dependencies issue (libcrypto.so.2 and libssl.so.2 not found) is kicking my ass. I ended up forcing the issue with 'rpm -ivh --nodeps' using the i386/Linux Python2 rpm I found, but the missing dependencies are causing my favorite Python IDE (WingIDE) to croak. I have the feeling that the lack of yast2's help, especially when it comes to SuSEConfig, is somehow causing other apps not to be able to find the version of OpenSLL that definitely _is_ installed on my system (0.9.6) Any help would be appreciated. thx From vmilitaru at sympatico.ca Thu Sep 12 23:11:22 2002 From: vmilitaru at sympatico.ca (vio) Date: Thu, 12 Sep 2002 22:11:22 -0500 Subject: [mod_python] ANNOUNCE: Mod_Python donated to ASF In-Reply-To: ; from grisha@modpython.org on Thu, Sep 12, 2002 at 06:25:45PM -0400 References: Message-ID: <20020912221122.A1410@eye.neb> Congrats to Gregory for this 'official' recognition for the great work he did with mod_python. And thank you to the apache board for recognising the need for an 'official' python effort in such an open way. Let's face it, there is no better place for an apache module to live but close to apache (httpd)'s place. Certainly the most intuitive place from a user's perspective. And this official blessing brings the additional advantage to cut through the confusion: there are not 10 'official' python' flavored apaches for a newcomer to choose from. (enough headaches just installing the beast and learning it) Regards, Vio * Gregory (Grisha) Trubetskoy [020912 20:57]: > > It is my pleasure to announce that Mod_Python has been donated to the > Apache Software Foundation, and is now a subproject of the httpd server > project (see http://httpd.apache.org/). > > I am grateful to ASF for accepting this donation and committing resources > to further the support of Mod_Python. I believe that this action will > advance the development of Mod_Python, resulting in an ultimately better > and more popular tool for Python developers. I also believe it will serve > to better position Python as a language of choice for web development, a > need that has been expressed by many. > > There are no implications to the current Mod_Python users - the license is > the same with the sole difference in that the copyright belongs to ASF > now. > > As a consequense of the donation, the CVS repository is now hosted on > cvs.apache.org. Do not use the SourceForge repository anymore, it will > soon be removed. > > There will also be website and mailing changes, but the details are still > being finalized and will be announced when ready. > > Regards, > > Grisha Trubetskoy > > > _______________________________________________ > Mod_python mailing list > Mod_python at modpython.org > http://www.modpython.org/mailman/listinfo/mod_python From martin.klaffenboeck at gmx.at Fri Sep 6 09:30:48 2002 From: martin.klaffenboeck at gmx.at (Martin Klaffenboeck) Date: Fri, 06 Sep 2002 15:30:48 +0200 Subject: pygtk Message-ID: Hello, I'm new here in Python, because a few people told me that the implementation of gtk is better in python than in Perl. So now I try do do object orientated programming here... Is this a good group to discuss pygtk things or is this just for python? (I think I have questions in both.) So now this message is also to say 'Hello' to everybody in this room. Maybe you'll here much from me. ;-) Martin From gerhard.haering at opus-gmbh.net Wed Sep 4 13:40:45 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 4 Sep 2002 17:40:45 GMT Subject: Bind threads to addresses -- Windows & urllib? References: Message-ID: Nick Arnett wrote: > I can't see an obvious easy way to bind threads to IP addresses on a > Win2K machine. I have a multi-threaded Web spider, which uses urllib to > retrieve pages, and would like to bind each thread to a different address > on the machine, if possible. I'm not sure what you mean. This is a multithreaded HTTP client app, right? Do you have multiple network connections and want to use more than one? If yes, then that's an issue of configuring the routing on your computer appropriately (if that is at all possible, I doubt it's easy). I'd also be surprised if you could saturate a 100 MBit link with a HTTP spider. -- Gerhard From anton at vredegoor.doge.nl Fri Sep 27 17:12:05 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 27 Sep 2002 23:12:05 +0200 Subject: watching mutables? References: Message-ID: On Fri, 27 Sep 2002 22:06:41 +0200, "Thomas Heller" wrote: >Here's what seems to be available: >http://oomadness.tuxfamily.org/downloads/ >and this is obviously where the EventObject is contained in: >http://oomadness.tuxfamily.org/downloads/EditObj-0.3.tar.gz Very interesting module. I might add that windows doesn't seem to like the .cfg file so this should be moved to some other place before installing with 'python setup.py install'. But... I specifically asked for something that doesn't touch the original object. In eventobj.py's docstring there is the following warning: Caution : As event management is performed by changing the class of the instance, you use eventobj with critical objects at your own risk... ! So, with a lot of thanks for the results sofar ... Is it possible? Anton. From tim.one at comcast.net Thu Sep 26 19:08:10 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 26 Sep 2002 19:08:10 -0400 Subject: Who knows somefunction? In-Reply-To: <3D9382AF.5070800@aon.at> Message-ID: [Gregor Lingl] > Is there a function in Python for which > > something is (id(something)) > > returns invariably true? [Tim] > I'm not sure you're asking the question you intended to ask, but str() > is one answer to the question you actually asked. [Gregor] > I don't think so: > >>> something = [1,2,3] > >>> something is str(id(something)) > 0 > > How did you understand my question? > (Errors should never pass silently) Seemingly in a way other than you asked it . Marc-Andre Lemburg's mxTools extension adds such a function to the sys module (sys.makeref(id)). It's impossible for him to do this safely, so believe his warnings when you read them. conjuring-things-into-existence-by-naming-them-is-a-trick- best-left-to-gods-ly y'rs - tim From max at alcyone.com Tue Sep 24 20:51:50 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 24 Sep 2002 17:51:50 -0700 Subject: Strange python and cgi! References: <3D9101AC.842F0513@alcyone.com> Message-ID: <3D9108A6.F59EC367@alcyone.com> CheapSkate wrote: > what kind of error am I expecting here? > .... errrrrrr I don't know how to access the web server error log. It is likely due to some environmental difference between how you run the script from your shell and how your Web server runs the script. Other than that, there is no way to know without actually checking the logs. We can't check them for you; you're going to have to do that yourself. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ As far as I'm concerned, being any gender is a drag. \__/ Patti Smith Kepler's laws / http://www.alcyone.com/max/physics/kepler/ A proof of Kepler's laws. From loewis at informatik.hu-berlin.de Mon Sep 16 05:59:57 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 16 Sep 2002 11:59:57 +0200 Subject: python performance References: <3D84E66F.6020701@linux.ie> Message-ID: Padraig Brady writes: > > Calling functions adds overhead. Running code within functions > > reduces overhead for object access. > > Ah OK, this because it has to search a smaller namespace? No. Inside a function, local variables are accessed with integer indices, instead of by name. This is possible because there is static knowledge about the local variables in a function. > Wouldn't compiling overcome this? Not if you want to preserve Python semantics; the compiler would need to emit code that performs the same actions that the interpreter currently does. Regards, Martin From yaipa at aol.com Fri Sep 13 14:05:16 2002 From: yaipa at aol.com (yaipa) Date: 13 Sep 2002 11:05:16 -0700 Subject: Is Python 2.1 for Solairs 8 broke on SunFreeware? Message-ID: <8d148763.0209131005.65de04a8@posting.google.com> Problem: I've downloaded Python 2.1 for Sparc Solairs 8 from Sunfreeware and run the pkgadd to install it. All seems fine until I try running a script that works just fine with ActiveState's build of Python 2.1 for Solaris. When I run Python 2.1 from Sunfreeware, Python throws an import error on the 'time' module. % /usr/local/bin/python CronTar.py -c cronTar.cfg Traceback (most recent call last): File "/export/fruid/bin/CronTar.py", line 26, in ? import time ImportError: ld.so.1: /usr/local/bin/python: fatal: libgcc_s.so.1: open failed: No such file or directory % Am I required to have gcc installed also? Our deployment model strictly uses the Solaris pkgadd command, so I require either Python 2.1 or 2.2 in a standard Solaris package format. Any ideas? From syver-en+usenet at online.no Mon Sep 16 05:11:16 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Mon, 16 Sep 2002 09:11:16 GMT Subject: Book for win32? References: Message-ID: Thomas Guettler writes: > Hi! > > I am interested in book about Python on win32. > > I found one from o'reilly: "Python on win32" > > Are there better books or alternatives? > > I am *not* looking for a python introduction, I am > programming more than one year with python, but up to > now mostly on unix. > > Now I am intersted in win32 stuff: > - Opening a file-dialog > - COM > - Accessing the registry > - Maybe GUI Programming Then you can't go wrong with the o'reilly book. It is a most excellent tome for precisely the subjects that you outline there. Be aware that the book is written for Python 1.5 so a couple of things, like the need to convert unicode strings passed in by COM objects are outdated. As you already have been programming python for over year this shouldn't be a problem. -- Vennlig hilsen Syver Enstad From DennisR at dair.com Wed Sep 18 11:10:17 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Wed, 18 Sep 2002 15:10:17 GMT Subject: Python comment stripper References: <16Nh9.248$Wc6.17087796@newssvr13.news.prodigy.com> <3d8807b1$1@news.sentex.net> Message-ID: > > Why not just use .pyc files > > all the time and be done with it? Unstated assumption: .pyc files are often larger than corresponding .py files. With comments stripped, the .py file would definitely be smaller. Otoh, .pyc files are easier to work with in some ways and where the size contribution of libraries is not an issue, .pyc files are great in this application. -- Dennis Reinhardt http://www.dair.com From gmuller at worldonline.nl Sun Sep 22 12:15:57 2002 From: gmuller at worldonline.nl (GerritM) Date: Sun, 22 Sep 2002 18:15:57 +0200 Subject: Smalltalk vs. Python and COM was Re: Byte Magazine and Smalltalk References: <3d87a686@tobjects.> <3d87dd7c$1@tobjects.> <20020918.115128.1605894428.1527@cybermesa.com> Message-ID: "Pino Gargiulo" schreef in bericht news:amkpk0$or2$1 at fe2.cs.interbusiness.it... <...snip...> > For this project I was considering Smalltalk and Python. The first so I > could be > some real stuff done and Python because apparently it permits quite easy > access > the the mysterious (to me) m$ APIs. I really would want to stay away from > VC++, > and I'm looking for some quite turnaround environment since I'll be learning > COM on the job. > > Anybody care to give some advice? I played around with DST but never looked > much at the existance of a COM wrapper/interface. > Long long ago I worked in a large scale Objective-C project. Objective-C inherited many of its good characteristics from Smalltalk. Now I am using Python quite a lot. It has again a lot of the good (dynamic) characteristics, with on top an excellent set of predefined modules. One of them are the win32 modules by Mark Hammond, documented on line of course, but also described extensively in "Python programming on Win32" by Mark Hammond and Andy Robinson, ISBN 1-56592-621-8. I am using the ActiveState distribution, which is a complete distribution including this win32 stuff. In short highly recommended! regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From maurice at akst.tn.tudelft.nl Mon Sep 9 13:17:16 2002 From: maurice at akst.tn.tudelft.nl (Maurice van de Rijzen) Date: Mon, 09 Sep 2002 19:17:16 +0200 Subject: Binary input into NumPy. Message-ID: Dear all, I just downloaded Numerical Python and I think it will be very usefull. However I have one major broblem: I don't know how to import binary data from a file on disk into an array! Can onyone help me with this problem? Thanks From 2002 at weholt.org Mon Sep 23 05:05:55 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Mon, 23 Sep 2002 09:05:55 GMT Subject: Suggesting a filename on a HTTP-request by sending someting in the header of the reply References: Message-ID: > Content-Disposition: file; filename=%(filename)s > > is the proper way to use the http header to show the "filename" of what is > being downloaded. > > > J Lowery Thanks!! It works just fine now. Best regards, Thomas Weholt From aleax at aleax.it Sun Sep 15 03:49:09 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 15 Sep 2002 07:49:09 GMT Subject: html template system? References: <0ro7ouskb8ctv6f846gb8cfpqtl5vs1avc@4ax.com> Message-ID: Aldo Cortesi wrote: > ":B nerdy" wrote: > >>what are good templating systems avaliable for python? ... > Cheetah - http://www.cheetahtemplate.org/ > YAPTU - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305 Speaking as the author of YAPTU -- YAPTU is a neat little toy, but Cheetah is a truly powerful system, particularly if your needs coincide with those it was designed for (e.g., make it feasible for non-programmers to edit the templates). I'd suggest looking into Cheetah (or other powerful systems -- Cheetah looks very good to me, but I don't come close to knowing them all!-), maybe unless you happen to be in a peculiar niche (e.g., if you must bundle your templating system with a small app, and you don't need too much in terms of raw power, YAPTU's tiny size may be a plus). Alex From ods at strana.ru Mon Sep 2 09:04:03 2002 From: ods at strana.ru (Denis S. Otkidach) Date: Mon, 2 Sep 2002 17:04:03 +0400 (MSD) Subject: Must have Python modules? In-Reply-To: Message-ID: On Mon, 2 Sep 2002, Robert Oschler wrote: RO> development!) I want to know what the other favorites are mx, PIL, DocumentTemplate, TAL, MySQLdb -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From amitp at Xenon.Stanford.EDU Thu Sep 5 12:19:35 2002 From: amitp at Xenon.Stanford.EDU (Amit Patel) Date: 5 Sep 2002 16:19:35 GMT Subject: colloquial names for types? References: Message-ID: Inyeol Lee wrote: | holger krekel wrote in message news:... | | > | > I'd try using | > | > something.__class__.__name__ | | Python 2.2.1 (#1, Apr 10 2002, 18:25:16) | [GCC 2.95.3 20010315 (release)] on sunos5 | | >>> "".__class__.__name__ | 'str' | >>> [].__class__.__name__ | 'list' | >>> {}.__class__.__name__ | 'dict' | >>> 3.__class__.__name__ | SyntaxError: invalid syntax | >>> dir(3) | [ ... '__class__', ... ] | | I'm confused. Why 3.__class__ raises exception? It's a syntax error because 3. is a valid (float) literal. So it gets treated like (3.)__class__, and there's no dot there. You can either write (3).__class__ or 3..__class__, but the latter is a float. - Amit -- -- Amit J Patel, Computer Science Department, Stanford University http://www-cs-students.stanford.edu/~amitp/ From dsavitsk at e-coli.net Mon Sep 16 14:17:42 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Mon, 16 Sep 2002 18:17:42 GMT Subject: COM object registration Message-ID: if the module below is run from the command line, it registers and works fine. if, however, it is imported and the register() method is executed it does not work (giving a 'localserver' error). (the registration process works, but it can't then be used via Dispatch) seemingly the name of the class (here testServer) can't be found. even though it doesn't work locally, however, it will still work as a DCOM server, that is, if it is registered from the command line on another computer it works. is this expected behavior? is it a mangled name of some sort? is there a better way to register a COM obect via code. # ------- sample code ------- import pythoncom class testServer: _reg_clsid_ = '{C627B7F9-E078-4872-B06D-7DB33C3BC7A4}' _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER _reg_progid_ = 'test.Server' _public_methods_ = ['GET_VALUE'] def GET_VALUE(self): return 0 def register(): import win32com.server.register win32com.server.register.UseCommandLine(testServer) if __name__ == '__main__': __register() # ------- end sample code ------- From joconnor at cybermesa.com Tue Sep 17 04:17:09 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Tue, 17 Sep 2002 15:17:09 +0700 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: <20020917.151708.502278611.1586@cybermesa.com> In article <96904b50.0209171305.6d65f574 at posting.google.com>, "Lee Gray" wrote: > > Can someone point me to a good Python GUI app to demonstrate (other than > IDLE)? Bioreason makes some products in Python. You can see some screenshots of their Python/Gtk products here: http://www.bioreason.com/lead.html and http://www.bioreason.com/drug.html -- Jay O'Connor joconnor at cybermesa.com http://www.r4h.org/r4hsoftware From aglyportREMOvethispart at nospam.yahoo.com Wed Sep 4 15:08:03 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Wed, 04 Sep 2002 12:08:03 -0700 Subject: Memory fault - core dumped while compiling 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> Message-ID: <3D765A13.7090103@nospam.yahoo.com> Martin v. Loewis wrote: > Andrew Koenig writes: > > >>Looks like the same symptom I had. >> >>If you are using binutils 2.13, try going back to 2.12.1 and >>see if that fixes the problem. > > > Alternatively, use the system C compiler - Python does not support gcc > on SCO, apparently (or else it would not try to pass -belf). > > It is probably easy to add gcc support - just adjust the OpenUnix > fragments in configure.in to SCO. > > Regards, > Martin Ok. I run gmake distclean and configure --without-gcc (output from configure confirmed that it would not use gcc). Compiling: cc -G -KPIC -Ki486 -belf -Wl,-Bexport build/temp.sco_sv-3.2-i386-2.2/arraymodule.o -L/usr/local/lib -o build/lib.sco_sv-3.2-i386-2.2/array.so /bin/sh: 1577 Memory fault - core dumped gmake: *** [sharedmods] Error 139 Did not even take nearly as long for it to coredump. With optionless configure build was going at least for a half an hour and this one bailed out pretty much right away... From erick_papadakis at REMOVEFORSPAM.yahoo.com Tue Sep 17 11:32:10 2002 From: erick_papadakis at REMOVEFORSPAM.yahoo.com (Erick) Date: Wed, 18 Sep 2002 00:32:10 +0900 Subject: can wxpython do this? References: <737aefee.0209151702.3f735252@posting.google.com> <3d854b44@news.sentex.net> Message-ID: > A better option, although I haven't tried it myself, would be > to use py2exe to build an executable, then package that up thanks Peter, but I was talking about something cross-platform. As py2exe's page says: py2exe is a distutils extension to convert python scripts into executable windows programs, which are able to run without requiring a python installation. do you know if it works across platforms? thanks/erick From m2 at plusseven.com Thu Sep 19 10:46:27 2002 From: m2 at plusseven.com (Alex Polite) Date: Thu, 19 Sep 2002 16:46:27 +0200 Subject: debugging "Too many open files" In-Reply-To: References: Message-ID: <20020919144627.GJ2134@matijek.plusseven.com> On Wed, Sep 18, 2002 at 11:23:32PM +0200, Martin v. Loewis wrote: > Alex Polite writes: > > > I'm getting the "Too many open files" error. > > What "the" error? An exception? A message in the system log? An SMS > on your mobile phone? Well first there's a loud voice in my head telling me to eat Christian babies and right after that my python program says "OSError: [Errno 24] Too many open files" or sometimes "IOError: [Errno 24] Too many open files: '/proc/mounts'" and exits. > I recommend you list /proc//fd/ Thanks. This tells me that some of my processes have a LOT of files open, most of them pointing to /dev/hdc. Is this normal? -- Alex Polite http://plusseven.com/gpg/ From pete at shinners.org Wed Sep 18 00:55:56 2002 From: pete at shinners.org (Pete Shinners) Date: Wed, 18 Sep 2002 04:55:56 GMT Subject: How to make a C extension module backwards compatible? References: Message-ID: Andrew McNamara wrote: > Is there any community wisdom on how to make a C extension module that > implements a new-style class (type?) backwards compatible (albeit, > at the cost of some functionality)? > > Put another way, how *should* I make a class implemented in C behave > like a new-style class when installed with python 2.2 and above, and > like an old style class when installed with older pythons? > > Should I just riddle the code with #ifdef's, or is there a more elegant > way? i've gone the #ifdef route, and it's a bit of a pain, but manageable. note that this was all completely undocumented when i put it together. i mainly just copied the builtin types included with python (with my own #ifdef stuff going in). here's related excerpts from the code that do what i want. basically my object is "RectType", and there is an object named "Rect" to construct them. the object is either a function or the actual RectType depending on the python version used. unfortunately i believe this is still currently undocumented, so good luck. static PyTypeObject PyRect_Type = { ... #if PYTHON_API_VERSION >= 1011 Py_TPFLAGS_DEFAULT|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_BASETYPE, #else 0, #endif doc_Rect_MODULE, /* Documentation string */ #if PYTHON_API_VERSION >= 1011 ... rect_new, #endif }; #if PYTHON_API_VERSION >= 1011 /*this is the python-2.2 constructor*/ static PyObject* rect_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { GAME_Rect *argrect, temp; if(!(argrect = GameRect_FromObject(args, &temp))) return RAISE(PyExc_TypeError, "badargs"); return PyRect_New4(argrect->x, argrect->y); } #endif static PyMethodDef rect__builtins__[] = { #if PYTHON_API_VERSION < 1011 { "Rect", RectInit, 1, doc_Rect }, #endif {NULL, NULL} }; void initrect(void) { PyObject *module, *dict, *apiobj; PyType_Init(PyRect_Type); module = Py_InitModule3("rect", rect__builtins__, rectangle_doc); dict = PyModule_GetDict(module); PyDict_SetItemString(dict, "RectType", (PyObject *)&PyRect_Type); #if PYTHON_API_VERSION >= 1011 /*this is the python-2.2 constructor*/ PyDict_SetItemString(dict, "Rect", (PyObject *)&PyRect_Type); #endif } From syver-en+usenet at online.no Tue Sep 17 08:00:25 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 17 Sep 2002 12:00:25 GMT Subject: Using emacs gud/pdb python debugger under windows References: <87elbuo46g.fsf@tleepslib.sk.tsukuba.ac.jp> <87n0qiul6j.fsf@computer.localdomain> Message-ID: <3cs86d38.fsf_-_@online.no> Felix writes: > Syver Enstad writes: > > I am just trying to find out how/when I can > use GNU emacs for debugging my python programs, because I generally > prefer not to leave Emacs. I am downloading the latest emacs sources from > cvs from savannah in order to check out if things work differently with > > that version. > > u just need to fix a few things to make it recogonize the win32 path. > here's how, open gud.el and search for the variable > 'gud-pdb-marker-regexp', > > then modify it to something like: > (defvar gud-pdb-marker-regexp > "^> > \\([-a-zA-Z0-9_/.:\\]*\\|\\)(\\([0-9]+\\))\\([a-zA-Z0-9_]*\\|\\?\\)()\\(->[^\n]*\\)?\n") > > this works well for me. Ha, ha it works, it works! (Dancing around the room) I want to hug you Felix! I didn't think of that, obviously. So it was just pdb failing to recognize the output from the windows version of python. I am a happy man. Thank you very much Felix. The version above had as line break in it. This version is without the linebreak in the re (don't know if it matters. (defvar gud-pdb-marker-regexp "^> \\([-a-zA-Z0-9_/.:\\]*\\|\\)(\\([0-9]+\\))\\([a-zA-Z0-9_]*\\|\\?\\)()\\(->[^\n]*\\)?\n") -- Vennlig hilsen Syver Enstad From loewis at informatik.hu-berlin.de Thu Sep 19 03:43:14 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 19 Sep 2002 09:43:14 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: Thomas Heller writes: > > That is not true. It is more reliable to inspect the source code. > > In general, it is very easy to do so: if there are no callbacks to > > Python, the module is stackless-safe. > > So win32all probably wxPython are incompatible with stackless? No. If a module has callbacks, it is thread safe if it does not put data on the stack whose addresses are used outside the function, and it does not use setjmp, and it does not use exception handling. Notice that the ifs are not if-and-only-ifs; there might be cases where a module puts a global object on the stack and is still compatible with stackless (e.g. if the function that does that does not callback). Reportedly, wxPython is compatible with stackless (by experimentation, not by inspection). Regards, Martin From amk at amk.ca Sun Sep 1 17:07:24 2002 From: amk at amk.ca (A.M. Kuchling) Date: Sun, 01 Sep 2002 21:07:24 -0000 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: In article <3d725881.345921 at news.t-online.de>, Gerson Kurz wrote: > in the match or find function. So basically, couldn't one come up with > a *human readable* syntax for re, and compile that instead? Python Maybe Ka-Ping Yee's rxb? http://web.lfw.org/python/rxb15.py The problem with a new syntax is that no one else would be using it, so you'd still need to learn the existing syntax for use with grep, vi, Perl, &c. (It wouldn't surprise me if Perl 6's revised regexes run into this very difficulty and don't gain much adoption.) --amk From dwelch91 at nospam.attbi.com Sun Sep 29 13:51:32 2002 From: dwelch91 at nospam.attbi.com (djw) Date: Sun, 29 Sep 2002 17:51:32 GMT Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <3d9739c7$0$19818$91cee783@newsreader01.highway.telekom.at> Message-ID: <3D973DA4.4040600@nospam.attbi.com> Jurie Horneman wrote: > "Jurie Horneman" wrote in message > news:9ac02e81.0209290839.4f4d6475 at posting.google.com... > >>rant > > > My thanks to both of the people who have ignored my ranting and tried to > help me. I believe I did what you suggested, but it didn't work, hence my > frustration. > > Right after posting my original problem, I completely removed and > reinstalled Python. And hey, now it works, with solution 4, ie packages as > they are described in the documentation. I don't know what I did to my > installation to make it do that, but my problem appears to be solved. > > For what it's worth - I've already been called on this once in a private > email: although my post was meant to illustrate my frustration and criticism > of the Python docs, it was also meant to be at least partly > self-deprecatory. I should have known better: not because nobody out there > gets that, but because text, and especially text sent out to millions of > people, just is not a good place for irony - especially when one is asking > for help. So if you felt offended: sorry, that wasn't what I intended. > > However, I do stand by my criticisms of the Python docs. > > Jurie. > > > Although I believe that the Python docs are a bit on the brief side sometimes, I don't think this topic has this problem... if you look at the package docs at: http://python.org/doc/current/tut/node8.html#SECTION008400000000000000000 ... it has a nicely done example of a directory layout and how the __init__.py files fit into the picture. What I would fault the docs with is the fact that (having gone through this fustration myself) this information is not easily discoverable. How was I supposed to know that I needed a "package" in order to import a module from a subdirectory? I'm sure many would say, go buy a Python book and look there... but I did that, and the books aren't any better in my opinion in this area. This topic of importing modules from various directories has been my biggest fustration with the language... definitely a "wart" in my opinion. Don't get me wrong, discovering Python-and-All-Its-Splendor has changed my whole approach to software development (and made it fun again), but there are still a few things that could use some polish. Regards, Don From list-python at ccraig.org Tue Sep 3 01:04:45 2002 From: list-python at ccraig.org (Christopher A. Craig) Date: 03 Sep 2002 01:04:45 -0400 Subject: Why it is so dramatical? In-Reply-To: <3D73E035.2040300@nospam.attbi.com> References: <200209021107.25761.b.maryniuk@forbis.lt> <3D73E035.2040300@nospam.attbi.com> Message-ID: djw writes: > Stupid question: > > If ""join() is 100-1000 X faster, why doesn't the Python interperter > translate s = s1 + s2 + ... into s = "".join( [ s1, s2, ... ] ) > automatically? You won't see that kind of dramatic results if you did that. In fact, my testing shows it would be slower. s = "".join(s1, s2) is slower than s=s1+s2. The reason you see that kind of speed up is that list.append(s1) is a ton faster than s+=s1, and "".join() is moved outside the loop. Compare the following (presume 'a' contains some string): method a) s="" for x in xrange(10000): s += a method b) l = [] for x in xrange(10000): l.append(a) s = "".join(l) method c) s="" for x in xrange(10000): s = "".join([s, a]) method a creates 10,000 individual string objects method b creates 1 list object (with a bunch of appends) and 1 string object method c creates 10,000 list objects (each of two elements s and a) and 10,000 string objects. On my system, as I would expect, method a takes about .40 seconds, method b takes .048, and method c takes .51. -- Christopher A. Craig "Imagination is more important than knowledge" Albert Einstein From max at alcyone.com Wed Sep 25 01:46:16 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 24 Sep 2002 22:46:16 -0700 Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <%8ci9.138477$5r1.5541622@bin5.nnrp.aus1.giganews.com> <3D911FE1.1050801@something.invalid> Message-ID: <3D914DA8.A62C0659@alcyone.com> Greg Ewing wrote: > Personally, I rather like > > a if b else c > > but Guido doesn't like that either, unfortunately. > > Perhaps I'll slip it into Pyrex when no-one's looking...:-) I went ahead and added one in empy, since it caused no conflicts; @(expression) can be used for embedding expressions, and so @(test ? thenExpression : elseExpression) can be used for embedding conditional expressions. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Music washes away from the soul the dust of everyday life. \__/ Berthold Auerbach 7 Sisters Productions / http://www.7sisters.com/ Web design for the future. From marten.hedman at btk.utu.fi Fri Sep 6 08:45:04 2002 From: marten.hedman at btk.utu.fi (Marten Hedman) Date: Fri, 06 Sep 2002 15:45:04 +0300 Subject: Win32 question: Problem with NetLocalGroupDelMembers Message-ID: <3D78A350.4010006@btk.utu.fi> Hi, Im writing a script for administrating local user groups on a remote WinNT computer, using Python 2.2.1 and the Win32 extensions, build 148. Getting information about users in a group and adding users to a group works fine, but when I try to delete users from a group I get an exception, 'TypeError: The object can not be converted to a Unicode object'. An interactive example session looks like this: PythonWin 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import win32net >>> server = '\\\\LAVENDER' >>> level = 3 >>> uname = 'BTK\\testperson' >>> group = 'testgroup' >>> u={} >>> u['domainandname'] = uname >>> u=[u] >>> u [{'domainandname': 'BTK\\testperson'}] >>> win32net.NetLocalGroupAddMembers(server, group, level, u) >>> mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, level) >>> mem [{'domainandname': u'BTK\\testperson'}] >>> win32net.NetLocalGroupDelMembers(server, group, mem) Traceback (most recent call last): File "", line 1, in ? TypeError: The object can not be converted to a Unicode object >>> win32net.NetLocalGroupDelMembers(server, group, u) Traceback (most recent call last): File "", line 1, in ? TypeError: The object can not be converted to a Unicode object >>> Have I misunderstood something, or have I stumbled upon a bug? Any help would be apprciated. Yours, Marten Hedman Systems Administrator Turku Centre for Biotechnology Turku, Finland From ifls at rz.tu-clausthal.de Tue Sep 24 07:25:04 2002 From: ifls at rz.tu-clausthal.de (Lutz Schroeer) Date: 24 Sep 2002 11:25:04 GMT Subject: Sessionhandling References: Message-ID: Michael Str?der wrote: : Most users do *not* configure their browsers anyway. Therefore it's : almost useless to use HTTP_ACCEPT_LANGUAGE or similar env vars. Well, at least you can try. My solution to the orignal poster's problem would be to detect the browser's language configuration and additionally offer the possibility to change the language and store it in a (maybe persistent) cookie. Subsequently those with correct browser configuration will get their preferred language and the other 90% will have the opportunity to use the switch. Personally I'm always pleased if a website opens in German because sometimes I'm not aware that a page offers a different language than English. Nevertheless I also like to switch back to English on some pages because the translations are sometimes a bit "creative" :-) -- From newgene at bigfoot.com Mon Sep 9 17:34:55 2002 From: newgene at bigfoot.com (newgene) Date: 9 Sep 2002 14:34:55 -0700 Subject: Save session in python interactive console Message-ID: Hi, group, After I was working at python interactive console(activepython v2.2 at Win2000 platform), I am wondering if possible to save the current session, so that I can load it again and continue the work next time. Just like R or Matlab, etc. Although python is a programming language, one of the best features I like is its interactive console. By writting my own module, I can make it as my personal working console. If saving session is possible, it will be much more convinient. The pickle module provided by python can save any object,but how can I save all objects in current session? Thanks in advance CW From whisper at oz.net Tue Sep 17 23:08:21 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 17 Sep 2002 20:08:21 -0700 Subject: Yet another Tkinter and threads question In-Reply-To: <4936aa67.0209171842.12cacf2a@posting.google.com> Message-ID: > After a short perusal of the group archives I haven't found anything > answering the following, so here goes: > > I am polishing up the GUI for a client that uses FTP to submit MVS > jobs to an IBM S/390, and am adding message boxes for exceptional > circumstances i.e., user mistyped password, connection timeout, etc. > To prevent locking up the GUI, all submissions spawn a thread, which > calls a wrapper function around ftplib that does the right > site-specific hanky-panky to make everything go smoothly. In the > thread function, the code goes something like this: > > try: > submit_job() > except socket.error: > showerror("Socket has barfed") > except ftplib.error_perm: > showerror("You mistyped your password") > > The call to showerror locks the program. Any thoughts? Older posts on > other threading+GUI questions had mentioned that Tk was not > thread-safe; has it become so, or is this still a tar-pit? > > Nick > > A.M.D.G. Yes, very simple. Never ever make a gui call in more then one thread. Make a single gui thread and have it process messages from the other threads to report/display problems such as you show. This is pretty much true for every gui out there, not just Tkinter. Tk is not thread safe, nor wxWindows, nor Win32. There was talk about making Tk thread safe in some future incarnation, but it's a big job and I don't know if it's even started yet. HTH... Dave LeBlanc Seattle, WA USA From kara.klosterman at attbi.com Thu Sep 26 19:43:33 2002 From: kara.klosterman at attbi.com (kara.klosterman) Date: Thu, 26 Sep 2002 23:43:33 GMT Subject: Help! This is driving me insane! Message-ID: Hello, I created a very simple class that totals some data but I am not getting the output from it that I would expect at all. Here is the class: http://www.geocities.com/dbasch/insane.txt I would expect to get: [0, 0] [0, 0] [[0, 0]] but I am getting: [0, 0] [0, 0] [[1, 1]] I dont understand how the 'grouptotals' list is getting the incremented values prior to the 'grouptotalcounter' function being called. furthermore, I can place a 'print grouptotals' right after the errorlog append and it isnt the incremented values! Please tell me this isnt a normal thing! Thanks, Derek Basch From erwin at andreasen.com Mon Sep 16 15:58:41 2002 From: erwin at andreasen.com (Erwin S. Andreasen) Date: 16 Sep 2002 21:58:41 +0200 Subject: Py_CompileString and line numbers? References: Message-ID: <87hegpg0zy.fsf@andreasen.org> Sebastian Andersson writes: > I'm parsing a config file and from there I get embedded python code > which I send to Py_CompileString, with the config file's filename given > as filename argument to Py_CompileString. Later, when errors are found > in the python code, the wrong line numbers are reported. Is there > a way to tell Py_CompileString an offset for the first line that > I give to it? The alternative to Martin's solution is a hack -- simply prepend the right amount of newlines before your code so the line numbers will match up. -- =============================================================== Herlev, Denmark <*> =============================================================== From sonnenbu at informatik.uni-bonn.de Wed Sep 25 16:09:19 2002 From: sonnenbu at informatik.uni-bonn.de (Frank Sonnenburg) Date: Wed, 25 Sep 2002 22:09:19 +0200 Subject: Newbie References Question References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> Message-ID: "Guy Rabiller" schrieb im Newsbeitrag news:3d91c72f$0$8558$79c14f64 at nan-newsreader-02.noos.net... > Hi, > > let say I have: > i1 = 1 > i2 = 2 > and > p = [i1,i2] > > How can I have: > p=[*i1,*i2] > rather than > p=[**i1,**i2] as it is curently ? > > ( Sorry for this nasty hybrid syntax ) > > Textualy, how if I want that p[0] refere to the 'i1' container, and not to > the refererence it contains ? > > What I want is that if now I set: > i1 = 4 > that automaticaly: > p -> [4,2] > and not keeping [1,2] My proposal: THINK OO! In my opinion, this is an excellent example to use the full power of object oriented programming. Of course, this is a lot of overhead and maybe you just wanted a very short approach. But since you told, you are a newbie, maybe you are not quite used to this style of programming. Just try out and experiment a little. =============================================================== # Module point.py class Point: def __init__(self, x=0, y=0): self._x = x self._y = y def __repr__(self): return 'Point (%d,%d)' % (self._x, self._y) def short_repr(self): return '(%d,%d)' % (self._x, self._y) def set(self, x, y): self._x = x self._y = y class Figure: def __init__(self, *points): self._points = [] for p in points: if not isinstance(p, Point): raise TypeError self._points.append(p) def __repr__(self): s = 'Figure' # Derived class instance? classname = self.__class__.__name__ if classname != 'Figure': s = s + ' (%s)' % classname if self._points: s = s + ', def. by' for p in self._points: s = s + ' '+p.short_repr() else: s = s + ', no points defined' return s # # Now it's your turn ;-) # # def set, get, remove, ...... # ... class Quad(Figure): def __init__(self, p0=Point(0,0), p1=Point(0,1), p2=Point(1,0), p3=Point(1,1)): Figure.__init__(self, p0, p1, p2, p3) def set_point(self, index, point): if type(index) != type(0) or index < 0 or index > 3: raise ValueError if not isinstance(point, Point): raise TypeError self._points[index] = point =============================================================== >>> from point import * >>> q = Quad() >>> q Figure (Quad), def. by (0,0) (0,1) (1,0) (1,1) >>> q.set_point(1,Point(555,888)) >>> q Figure (Quad), def. by (0,0) (555,888) (1,0) (1,1) >>> p = Point(1,2) >>> p.set(4,2) >>> p Point (4,2) =============================================================== Frank From dwelch at nospam.vcd.hp.com Thu Sep 26 12:29:04 2002 From: dwelch at nospam.vcd.hp.com (djw) Date: Thu, 26 Sep 2002 09:29:04 -0700 Subject: os.makedirs: difference between nt4 and w2k References: Message-ID: Jens Bloch Helmers wrote: > Suppose unc_path is a UNC path refering to a non existing > directory on another computer. > os.makedirs( unc_path ) throws an exception if this path > is on a windows 2000 machine but creates the directory if > it is on a win-nt machine. > > Is this a feature of win2k, or could I change the setup > of that win2k computer to accept the creation of unc_path? > Could this be done from Python? > (I have administrator privileges on both computers) > > Jens Helmers I recently found that os.makedirs( ) does not work properly on win2k (haven't tried winnt). So, instead, I created a loop that walks the path one level at a time and calls win32file.CreateDirectory() for each directory level that os.path.isdir() returns false (or, you can simply catch the exception code rc==183 if the directory already exists, and continue). I used split('\\') to generate the list of directories to create (element 2 ends up being the server name, element 3 the share name, and the slice [4:] is the remainder of the directories). Of course, this ends up being very Windows specific, but that doesn't sound like an issue for you. So, _roughly_: path = '\\\\server\\share\\dir1\\dir2\\' p = path.split( '\\' ) trg = "".join( [ '\\\\', p[2], '\\', p[3] ) # \\server\share subdirs = p[4:] # [dir1, dir2, ...] for subdir in subdirs: trg = os.path.join( trg, subdir ) if not os.path.isdir( trg ): try: win32api.CreateDirectory( trg, None ) except win32api.error, (rc, fnerr, msg ): if rc == 3 or rc == 53: print msg # File not found error # Do something intelligent here... else: print msg # Some other error Hope this helps. Don From dbasch at yahoo.com Thu Sep 26 19:56:43 2002 From: dbasch at yahoo.com (Derek Basch) Date: Thu, 26 Sep 2002 16:56:43 -0700 (PDT) Subject: This is driving me insane! Message-ID: <20020926235643.37002.qmail@web20806.mail.yahoo.com> Hello, I created a very simple class that totals some data but I am not getting the output from it that I would expect at all. Here is the class: http://www.geocities.com/dbasch/insane.txt I would expect to get: [0, 0] [0, 0] [[0, 0]] but I am getting: [0, 0] [0, 0] [[1, 1]] I dont understand how the 'grouptotals' list is getting the incremented values prior to the 'grouptotalcounter' function being called. furthermore, I can place a 'print grouptotals' right after the errorlog append and it isnt the incremented values! Please tell me this isnt a normal thing! Thanks, Derek Basch __________________________________________________ Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! http://sbc.yahoo.com From daniel.dittmar at sap.com Thu Sep 26 06:25:09 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 26 Sep 2002 12:25:09 +0200 Subject: Getting last char in string. References: Message-ID: CheapSkate wrote: > then what does > s[-1:] do? >>> s = '' >>> s [-1] Traceback (innermost last): File "", line 1, in ? IndexError: string index out of range >>> s [-1:] '' s [-1] returns a single element, s [-1:] returns a sequence. But in the current Python definition (implementation?), single characters are strings of length 1. Daniel From pedronis at bluewin.ch Wed Sep 4 15:15:48 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Wed, 4 Sep 2002 21:15:48 +0200 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> Message-ID: <3d765ce6_4@news.bluewin.ch> Robin Becker wrote in message YR13DVAUNld9EwXH at jessikat.demon.co.uk... > In article <3d76494d$1_5 at news.bluewin.ch>, Samuele Pedroni > writes > ..... > >> > > >> > > >> well actually we're running with the default jython.bat which doesn't > >> seem to specify a memory, 1Gig is probably the default or maybe I ran > >> out of page space. The python process never gets over 90Mb grrrhhhh. > > > >then maybe I'm puzzled, > > > >have you checked process memory usage or is just that you get > >an "out of memory" and are estimating based on your total memory. > > > >Because the normal jython.bat uses the JVM default which is > >to scream "out of memory" after 64Mb of object memory has > >been allocated, see -Xmx here > > > >http://java.sun.com/j2se/1.4/docs/tooldocs/windows/java.html#options > > > >regards. > ...... > we're watching it on the task monitor/performance. No other process > running, this particular thing just eats up the world. then the JVM is buggy (very strange btw) because is should not use more than -Xmx memory and then say "out of memory" and the default should be 64Mb but not 1Gb for sure. [To prove the point consider this example program and two runs: (under w2k btw). * outofmem.java * public class outofmem { public static void main(String args[]) { java.util.ArrayList list = new java.util.ArrayList(); int count = 0; while(true) { list.add(new int[1024/4*1024*5]); // ~5MB System.out.println(++count); } } } * runs * D:\exp\java-out-of-memory>\usr\jdk1.4.0\bin\javac outofmem.java D:\exp\java-out-of-memory>\usr\jdk1.4.0\bin\java -version java version "1.4.0" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92) Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode) D:\exp\java-out-of-memory>\usr\jdk1.4.0\bin\java outofmem 1 2 3 4 5 6 7 8 9 10 11 Exception in thread "main" java.lang.OutOfMemoryError D:\exp\java-out-of-memory>\usr\jdk1.4.0\bin\java -Xmx80m outofmem 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Exception in thread "main" java.lang.OutOfMemoryError ] Are you spawning processes through os.system or something? otherwise you are not telling some piece of the picture. regards. From tundra at tundraware.com Fri Sep 6 17:10:07 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: 06 Sep 2002 21:10:07 GMT Subject: Larry Wall's comment on python... References: Message-ID: > The very idea of Larry Wall lecturing on code readability is hilarious. > > -Dave > > Well, that's true, but for all of its similarity to line noise, perl has been an enormous contribution to our profession/community. I would never want to diminish Wall's stature, therefore. As someone deeply steeped in Algol-derived languages (C, PL/M, PL/I, Java ...), I find Python's indentation approach refreshing on two (pardon the expression), levels: - It makes the compiler/interpreter do the work instead of me - Why should I have type {} and ; when the language can figure it out for itself. - It causes me to factor code better. Python encourages a style that obviates (some of) the need for the kind of syntactic structures found in older block-structured languages. Wall's comment is correct if you insist on Algol-style block structuring. But Python encourages you to factor in a way that makes such block structure different and perhaps less necessary. In particular, the ability to combine functional, procedural, and object constructs in a seamless way gives you the ability to do a lot of structuring and scoping *implicitly* w/o the need for explicit indentation or block delimiting. Python not only "Fits Your Brain", it changes how your brain processes and reduces problems. *This*, in my view is why the absence of block delimiters is not a big deal. On a personal note, I've had an interesting year - I've been coding in nothing but Python (Unix & Win32) and *assembler* (embedded PIC processors). Talk about a contrast! Yet in both cases, the languages "Fit My Brain" for the tasks at hand. For instance, I find almost all compiled languages (even C) intrusive when writing code for embedded systems. Assembler is so much more expressive there because *it directly reflects the state of the hardware being controlled.* Similarly, I love Python for most other (higher level) tasks because *it painlessly reflects the state of the computational problem being solved.* Now, I only wish for an excellent Python optimizing compiler with a retargetable code generator ... *that* would be Bliss (and I don't mean the language ;) -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From rsrchstr at msn.com Sun Sep 29 21:43:56 2002 From: rsrchstr at msn.com (mike henley) Date: Mon, 30 Sep 2002 02:43:56 +0100 Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> Message-ID: "mike henley" wrote in message news:an8924$bujmm$1 at ID-157863.news.dfncis.de... > Just brainstorming on one possible way to do it; please advise if you have: > > what would such a script/application do? > > it would start up with my computer, simply insert itself in my start-up > folder or whatever > it would just wait and detect when i go online > then it when i do get online it would detect what my IP is > and when if i'm disconnected then it will detect that too > and when if i'm reconnected it would detect that too and detect my IP > or it can just simply do this at regular intervals Duh! an IM/jabber client would do this already. > > then it would use jabber/xml-rp or whatever to make a presence for > me/my-webapplication on IM networks > using a username or account name that i can give to others > > so that this way the webapplication will have "presence" > so others will know when the webapplication is online > > and then if they IM it it'll reply with my IP so it appears in the IM as a > hyperlink that they can click to launch their default browser to a url > consisting of http://myIP > > and then perhaps if they wish to be automatically notified of the > webapplication's presence they can insert their username on a form on the > webapplication when they get their which will add it to its buddylist > > or even within the first IM they get from it there can be a link that if > they wish to click on will detect and add their username automatically (as > an option) > > or they reply with a message such as "add me" which will do that > > and either way they can be added, if they wish, to the webapplications > buddylist so next time it goes online it can send them an IM automatically > > of course it should enable them to remove themselves from the buddylist > later on if they wish > > sounds very much like a jabber bot > perhaps i can get an open source one and extend or customize it sounds much like a Jabber bot [and therefore mutli-IM-network (AIM, MSN, Yahoo, ICQ)] that would detect what my (dynamic) IP is whenever i go online, and then send it to others in it's buddylist if they wish so or reply to them with it if they ask it, of course they can add it to their username, and allow others to add/remove themselves to/from its buddylist, and have it send them an IM automatically with the IP > > > got any better ideas or there's something wrong in what i have written? > please tell me, i have read about jabber yet. > > > > > "mike henley" wrote in message > news:an87db$bjtvs$1 at ID-157863.news.dfncis.de... > > i guess i'll rephrase; what i wish for is an "application-to-person" (P2A) > > IM-based "presence", so that a web-application that i host on a personal > > webserver, on my own machine, can let others become aware of its > "presence" > > easily and be easy to connect to with a simple > > click-to-launch-browser-and-go-to-my-ip. This should be easy to do. I just > > don't have experience with Jabber or xml-rpc, or other potential useful > > technologies. > > From zack at cs.unibo.it Mon Sep 2 08:57:50 2002 From: zack at cs.unibo.it (Stefano Zacchiroli) Date: Mon, 2 Sep 2002 14:57:50 +0200 Subject: portability problem with struct.{pack,unpack} References: Message-ID: In article , Radovan Garabik wrote: > are you aware of xtalk? > http://packages.debian.org/xtalk yes, I'm aware of it, but this doesn't solve the portability problem of struct.{pack,unpack} :-))) -- Stefano Zacchiroli - undergraduate student of CS @ Univ. Bologna, Italy zack at cs.unibo.it | ICQ# 33538863 | http://www.cs.unibo.it/~zacchiro "I know you believe you understood what you think I said, but I am not sure you realize that what you heard is not what I meant!" -- G.Romney From lists at gregfortune.com Thu Sep 12 00:18:23 2002 From: lists at gregfortune.com (Greg Fortune) Date: Wed, 11 Sep 2002 21:18:23 -0700 Subject: "str.contains(part)" or alternatives? References: Message-ID: <3d8013e8$0$309$39cecf19@nnrp1.twtelecom.net> > >> I think the current proposal is to move to >> >> if ll in s: >> >> for this construct. Happy? > > I would like .contains more, but at least the proposal is _much_ better > than "if s.find(part) != -1". :-) > > "if part in s" disturbs the pattern "if item in sequence" somewhat but > that has already been weakened by "if key in dict" (that I like, > nonetheless). > > Stefan Why not simply use .count(part) > 0 ? I didn't catch the first part of the conversation, but if I'm looking for a contains, I just do. if(search_me.count(substr) > 0): print 'found' else: print 'not found' Greg Fortune Fortune Solutions From ivan.brkanac at hl.hinet.hr Mon Sep 16 06:59:22 2002 From: ivan.brkanac at hl.hinet.hr (AT&T) Date: Mon, 16 Sep 2002 12:59:22 +0200 Subject: Access to CDDB or FreDB from python ? Message-ID: <3d85b80f_3@news3.prserv.net> I am using python 2.2. on win32 and I wanted to access CDDB from python and there is CDDB python module on source forge. But it is not working at least on Win32 and python 2.2 also while I was looking freedb documentation they stated that to calculate exactly DiscID in win32 you should not use MCI what is method off this library. I would like to ask if somebody have some experience in accessing cddb from python and if so if he can share some code or some link. I managed to access it thru one Ocx control, but this is not really in python spirit since it works only on win32 Ivan From rjones at ekit-inc.com Sat Sep 7 01:48:10 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sat, 7 Sep 2002 15:48:10 +1000 Subject: Available data types in Gadfly 1.0? In-Reply-To: References: Message-ID: <200209071548.10254.rjones@ekit-inc.com> On Sat, 7 Sep 2002 1:14 pm, Jeff Kowalczyk wrote: > I'm experimenting with gadfly, and I'm looking for some documentation on > what data types are available for columns in Gadfly 1.0? so far, I only > know integer, float, varchar to work. Is there a date type? Boolean? Gadfly will happily store any marshallable data (ie. builtin types like strings, lists, None, tuples, ...) in varchar columns. See http://gadfly.sourceforge.net/gadfly.html#id7 As far as the "don't count on that being true" ... I don't know of any plans to make it not be true. Richard From chris.gonnerman at newcenturycomputers.net Fri Sep 20 08:12:19 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 20 Sep 2002 07:12:19 -0500 Subject: sorry for this stupid question about struct module References: <3d8a4ae7$0$280$7a628cd7@news.club-internet.fr> Message-ID: <004801c2609e$f8b66f00$0101010a@local> ----- Original Message ----- From: "Alex Martelli" > Alan Marchand wrote: > > > Hi all, > > > > I tryed this : > > > > e:\temp>python.exe > > Python 2.2.1 ( #34, Apr 9 2002, ...................) > > ........... > >>>> import struct > >>>> x = struct.pack( '>I', 10 ) > >>>> print repr( x ) > > '\x00\x00\x00\n' # why not ! > > > > How can I obtain the result a expect : '\x00\x00\x00\0A' ? << hacked out lucid explanation of repr >> > -- but why is repr's > behavior problematic to you? It isn't, I'd wager. I suspect Mr. Marchand doesn't realize that '\n' == '\0x0A'. His entire original post indicated that he needed that exact value to send to a printer, which is what makes me suspect he didn't know he actually *had* that value. I also suspect he does know by now. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From jeremy at alum.mit.edu Thu Sep 5 15:16:33 2002 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 5 Sep 2002 12:16:33 -0700 Subject: Why read-only nested scopes? References: Message-ID: David Eppstein wrote in message news:... > In article , > Gon?alo Rodrigues wrote: > > > Anyway, I've been directed to PEP 227, cheerfully obeyed, and from what > > I have understood having read-only nested scopes was more of a design > > decision than something else. And while I can live happily with the > > decision (some would even say happier) there is something about the "You > > can look at it but not touch it" attitude that I dislike ;-) > > I'm sure there were good reasons for this decision, but it leads to ugly > workarounds like making each nonlocal variable into a list and assigning > to x[0] instead of x... I agree with you in principle. I think that nested scopes would be cleaner if they allowed rebinding names in enclosing scopes. But it's not a limitation that has ever caused me grief. There are a variety of workarounds. The use of a list to represent a mutable variable is one, but replacing the nested function with a class works, too. Here's what I had to say in PEP 227 about the current state of affairs: There are technical issues that make it difficult to support rebinding of names in enclosing scopes, but the primary reason that it is not allowed in the current proposal is that Guido is opposed to it. His motivation: it is difficult to support, because it would require a new mechanism that would allow the programmer to specify that an assignment in a block is supposed to rebind the name in an enclosing block; presumably a keyword or special syntax (x := 3) would make this possible. Given that this would encourage the use of local variables to hold state that is better stored in a class instance, it's not worth adding new syntax to make this possible (in Guido's opinion). The proposed rules allow programmers to achieve the effect of rebinding, albeit awkwardly. The name that will be effectively rebound by enclosed functions is bound to a container object. In place of assignment, the program uses modification of the container to achieve the desired effect: def bank_account(initial_balance): balance = [initial_balance] def deposit(amount): balance[0] = balance[0] + amount return balance def withdraw(amount): balance[0] = balance[0] - amount return balance return deposit, withdraw Support for rebinding in nested scopes would make this code clearer. A class that defines deposit() and withdraw() methods and the balance as an instance variable would be clearer still. Since classes seem to achieve the same effect in a more straightforward manner, they are preferred. Jeremy From Padraig at Linux.ie Thu Sep 19 08:53:37 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Thu, 19 Sep 2002 12:53:37 GMT Subject: RegEx editors References: Message-ID: Eric Arnold wrote: > Does anybody know of any good graphical regex editors out there? http://laurent.riesterer.free.fr/regexp/ http://regexplorer.sourceforge.net/ http://txt2regex.sourceforge.net/ http://sedsed.sourceforge.net/ (this is a python script) P?draig. From pyth at devel.trillke.net Sun Sep 1 15:54:06 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sun, 1 Sep 2002 21:54:06 +0200 Subject: Python IPC options In-Reply-To: ; from a-steinhoff@web.de on Sun, Sep 01, 2002 at 09:36:05AM -0700 References: <1030829572.943495@irys.nyx.net> Message-ID: <20020901215406.E3893@prim.han.de> Armin Steinhoff wrote: > fburton at nyx10.nyx.net (Francis Burton) wrote in message news:<1030829572.943495 at irys.nyx.net>... > [ clipp ..] > > It would be nice if Python could provide the same kind of > > communication mechanisms. Unfortunately, while Glish is > > freely available, it is heavily C++ biased and runs only on > > some Unix systems. In theory, something similar could be > > implemented on a much wider range of platforms using > > sockets and Python. > > > > Can anyone tell me: has an interprocess communication > > mechanism specifically with a bus architecture been > > implemented in/for Python? > > Corba 2.2 -> http://www.fnorb.org CORBA 2.0 AFAIK. > Python remote objects -> http://www.sf.net/projects/pyro > SOAP -> http://www.pythonware.com/products/soap/ > SPREAD -> http://www.python.org/other/spread/ this one has a bus-like architecture (uses IP-Multicast if possible). > Send/Receive/Reply for QNX6 message passing -> http://www.sf.net/projects/pyqnx Can you summarize this one? Couldn't find details on your project home page :-) regards, holger From bruce_deletethis_dawson at cygnus-software.com Tue Sep 24 01:14:36 2002 From: bruce_deletethis_dawson at cygnus-software.com (Bruce Dawson) Date: Tue, 24 Sep 2002 05:14:36 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <%8ci9.138477$5r1.5541622@bin5.nnrp.aus1.giganews.com> <3D8EB212.1000104@cygnus-software.com> <3D8EB7A9.F7CDE16@alcyone.com> Message-ID: <3D8FF49E.3000102@cygnus-software.com> Good point about the difference, and thanks for the pointer/reminder about operator.truth. It's still good to have bool though - if only for the compactness and readability of it. Erik Max Francis wrote: > Bruce Dawson wrote: > > >>I find the (a and [b] or [c])[0] construct to obscure to be useful - >>the >>space it saves is wasted by the comment I have to put in to explain >>it. ... > > I use this technique frequently enough, but this isn't really what a > conditional expression does. A conditional expression only _evaluates_ > one of its consequents, depending on the value of the test expression. > The (a, b)[operator.truth(p)] evaluates both. > > This is fine in many cases, of course -- such as when you're selecting > between two strings -- but it isn't the full power of a true conditional > expression. > > From tim.one at comcast.net Fri Sep 20 15:19:33 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 20 Sep 2002 15:19:33 -0400 Subject: Destructor never called ??? In-Reply-To: Message-ID: [Tim] > It's only the cases where Python can't possibly guess a safe order in > which to call destructors where both __del__ and collection are > inhibited. [Alex Martelli] > I think it's a bit more than that: Python *COULD" "possibly guess a > safe order" when there is only exactly ONE object with a __del__ that > is part of the cycle -- namely, destroy that one object first. It > doesn't seem to even TRY (note: I'm not saying it SHOULD -- but > "can't possibly" might be a bit too strong as a description of what > is actually going on). I agree. Way back when, the idea was to compute the maximal strongly connected components (SCCs) of the trash reachability graph. The derived graph (viewing each SCC as a node in its own right) is necessarily a DAG (no cycles), and cleanup would then proceed in an order consistent with some topological sort of the DAG nodes (no cycles implies a topsort is always possible). It was noted at the time that if the set of objects corresponding to a single SCC "supernode" contained at most one object with a __del__, then a safe teardown order for those objects could be known (just as you suggest). In practice, computing SCCs is a PITA, and the simpler scheme actually implemented does all of that *except* for dealing with would have been SCC DAG nodes corresponding to a set of objects exactly one of which has a __del__, had SCC DAG nodes been constructed. Refcount semantics automatically tear down everything else in what would have been SCC DAG node order (btw, for those who haven't thought about it, note that "a refcount" is exactly the same as "a predecessor count" in a topological sort algorithm: they have a lot in common). Since you and I are approximately the only two people on the newsgroup whose heads haven't exploded from trying to understand exactly what the hell I'm talking about there , I think it's a Positive Good that Neil skipped all the SCC complications. "Cycles and destructors: don't even think about mixing them" is much easier to remember, and has never done me any harm in real life. From tg5027 at citlink.net Tue Sep 17 21:40:34 2002 From: tg5027 at citlink.net (terry) Date: Tue, 17 Sep 2002 21:40:34 -0400 Subject: Python GUI app to impress the boss? Message-ID: >>?I'm willing to bet, though, that Python will be around for longer >> than VBScript. Cameron, I don't like to disagree with an icon, but I think that you are missing a deficiency in Python that will ultimatly limit it's usefullness in the vast majority of the software that is written in the world. As long as Python refuses to admit that money is the focus of most of the world's software, Python will be relagated to the same status as FORTRAN, BASIC, and etc - except COBOL and VB. Is there any way to get the Python world to allow for the processing of monetary applications without some hokey 60's constructs that involve in-line conversions or anticipations of calculation characteristics? Regards, terry From mhammond at skippinet.com.au Tue Sep 17 07:04:31 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 17 Sep 2002 11:04:31 GMT Subject: Calling Python from C# - please help References: <6de16ac9.0209130508.5d1b56c6@posting.google.com> <0iCg9.2350$Ee4.6516@news-server.bigpond.net.au> <3D82FA5B.3050003@mxm.dk> Message-ID: <3%Dh9.15217$Ee4.45118@news-server.bigpond.net.au> Syver Enstad wrote: > Max M writes: > > >>Mark Hammond wrote: >> >> >>>I have no examples of this, but I should. I'm co-authoring a .NET >>>book which is nearly out :) - >> >> >>That sounds great. I enjoyed the win32 book, and still use it as a >>reference. >> >>Are you by any chance still developing Pyhton .NET, or has it >>completely stopped? >> >>regards Max M > > > Now that J# (Java .NET) has been released, I was wondering about the > possibility of compiling Jython with the MS J# compiler to create a > Jython .NET. Has anyone considered the possibility? I'd love to see some Jython technology used for .NET. At the time Python.NET started, there was very strict NDA, so discussing the project with jython-dev, or even python-dev, was taboo. Greg Stein and I made a pragmatic decision to go with the p2c tool as a framework over jython as we alrady had experience with p2c and didnt have the time-lines to understand jython before embarking on our pilot code. But see my previous post - time (generally represented as money ) is the commodity most scarce. Mark. From johnroth at ameritech.net Tue Sep 3 08:47:40 2002 From: johnroth at ameritech.net (John Roth) Date: Tue, 3 Sep 2002 08:47:40 -0400 Subject: Would you like a Snobol pattern matcher? (Re: Making regex suck less) References: <3d725881.345921@news.t-online.de> <3D740DFC.1040009@something.invalid> Message-ID: "Greg Ewing" wrote in message news:3D740DFC.1040009 at something.invalid... > John Roth wrote: > > > http://www.perl.com/pub/a/2002/06/04/apo5.html > > > > http://www.perl.com/pub/a/2002/08/22/exegesis5.html > > > I just had a brief look at this, and the underlying > ideas seem to be a lot like the way Snobol patterns > work. > > Maybe it's time for me to resurrect the Snobol-style > pattern matching module that I started on a while > back and never got around to releasing. > > Would anyone be interested in this? Its > syntax is similar to that of Plex REs, except that > the primitives are Snobol-like, and it uses a > backtracking matching algorithm that's much more > powerful than a DFA (you can write entire parsers > in it, for example). I don't know much about Snobol, unfortunately. I think my biggest issue here is that we shouldn't reinvent the wheel unless there is a good reason. In other words, Larry is taking Perl in a specific direction. Assuming we want to make major changes to regex, is there any _good_ reason for doing something conceptually different and consequently adding to the cacophony? John Roth > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > From markus.vonehr at ipm.fhg.de Tue Sep 10 10:42:12 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 10 Sep 2002 16:42:12 +0200 Subject: import Error SWIG extension Message-ID: <3D7E04C4.A68ADF6E@ipm.fhg.de> Hi again, I succeeded compiling my extension (done with SWIG) but trying to import it I have the following error: import mvelib Traceback (most recent call last): File "", line 1, in ? import mvelib SystemError: _PyImport_FixupExtension: module mvelib not loaded I tried compiling the elemlist example from Alex Martelli (it's made without SWIG) and it works. I copied both of the extensions in my python home dir, so the problem has to be in the code? I had to rename the init_mvelib function to initmvelib that disutils have been able to compile it. Is it possible that the error is in the init function? Anybody knows the cause of the error? Markus From fredrik at pythonware.com Wed Sep 4 03:14:12 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Sep 2002 07:14:12 GMT Subject: MD4 and DES for unicode strings (samba passwd file manipulation) References: Message-ID: <8pid9.5889$e5.1033526@newsb.telia.net> Arcady Genkin wrote: > And yet I can't create the right crypted strings: > > >>> from Crypto.Hash import MD4 > >>> > >>> m = MD4.new() > >>> m.update( u'111222333' ) > >>> m.hexdigest().upper() > 'A672E5EDFDAD90A15228E0AEC2AA9161' > >>> # SAMBA-encoded password "111222333": > >>> samba > 'B66B458E27BD714F99A05EE3C479FBF1' > > Perhaps the problem lies with Unicode encoding? Samba's man page (see > the link below) says that the string is obtained by taking MD4 hash on > the password, represented as a string of 16-bit little-endian unicode > characters. if you want a string of 16-bit little-endian unicode characters, make sure you have one: m = MD4.new() m.update(password.encode("utf-16-le")) m.hexdigest().upper() (I don't have the MD4 library, so I cannot verify this. But if it works, it works for both 8-bit strings with ASCII text, and Unicode strings) From kokohh at hotmail.com Thu Sep 12 23:06:43 2002 From: kokohh at hotmail.com (koko) Date: Fri, 13 Sep 2002 03:06:43 GMT Subject: mime types Message-ID: <7Dcg9.8153$yt3.4264497@newssrv26.news.prodigy.com> i am trying to retreve urls. if it is mime text file, save the file. if not, pass e.g. url=http://www.uchicago.edu mimetypes.guess_type(url) sometimes it can give text/html. But a lot of them is text/html, but it only gives (None, None) Is there any accurate ways to determine the mine type? From uwe.schmitt at procoders.net Tue Sep 10 17:33:47 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 10 Sep 2002 21:33:47 GMT Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> <6afb9d2c.0209091641.1d9b652e@posting.google.com> Message-ID: Naveed Iqbal wrote: > Thank you all for your help. I am really a novice when it comes to > python. Will someone tell me how to install the win32ui module in > windows? > thanka > naveed I suceeded without win32all: I generated a postscript file and copied it to the 'file' "prn:" using shutil.copyfile(). Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at num.uni-sb.de than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From tjabo.kloppenburg at unix-ag.org Tue Sep 3 15:31:40 2002 From: tjabo.kloppenburg at unix-ag.org (Tjabo Kloppenburg) Date: Tue, 3 Sep 2002 21:31:40 +0200 Subject: Help with mod_python In-Reply-To: References: Message-ID: <20020903213140.5a43330f.tjabo.kloppenburg@unix-ag.org> hi "Joseph Youssef", JY> Hello, I've been trying to get python to work on apache, so JF> I downloaded mod_python... I have the same problem on my debian linux box (woody). I changed apache.py to print sys.path (the variable with the paths where python searches modules) -- the directory of the webserver was missing!? After this "experience" I tried the "PythonHandler mod_python.publisher" examples -- they run perfectly. Next I decided to use PHP for the project... :-) tk. -- Tjabo Kloppenburg --=- In 111.14 Tagen ist Weihnachten! -=-- -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jcc at ibdosnorte.com Tue Sep 24 03:53:43 2002 From: jcc at ibdosnorte.com (=?ISO-8859-1?Q?Juan_Carlos_CORU=D1A?=) Date: 24 Sep 2002 00:53:43 -0700 Subject: COM: Returning IDispatch or NULL References: Message-ID: Mark Hammond wrote in message news:... > Juan Carlos CORU?A wrote: > > Hello, > > > > I'm trying to develop a COM Server in python, that has a method that > > returns an IDispatch object but sometimes it must return nothing. See > > the following example programmed in C/SIDE (Microsoft Navision > > Financials ERP): > > > > ---> > > otherCOMServer := COMServer.returnOtherCOMServer(); > > IF ISCLEAR(otherCOMServer) THEN MESSAGE('otherCOMServer is clear'); > > <---- > > > > Definition of ISCLEAR (extracted from MS Navision help): > > The return value is TRUE if: > > -the automation variable has not been created. See CREATE. > > -the automation variable has been cleared. See CLEAR. > > -the automation variable has been assigned NULL by an automation > > server. > > > > I thing that in this case I must assign NULL to the otherCOMServer > > variable in order to keep the otherCOMServer variable CLEARED. > > What must I return from "COMServer.returnOtherCOMServer()" method to > > assign NULL? > > I have tried: > > return None > > return wrap(None) > > return 1==0 > > return > > > > but without success. The environment responds "data type not > > supported". > > None is the way to do this. What responds "data type not supported"? > Have you registered your object for debugging and seen the output? > There may be a traceback printed. > > Mark. After executing "return None" Navision responds "This data type is not supported by C/SIDE". The debugging output is correct: OutMessage created Object with win32trace dispatcher created (object=) Returning wrapped in _Invoke_ with 1000 1024 1 (,) in _Invoke_ with 1002 1024 1 (1000,) returning None The invoke with 1002 is the call to the method that returns NULL or an object after 1000 ms of timeout. From timr at probo.com Thu Sep 26 23:43:22 2002 From: timr at probo.com (Tim Roberts) Date: Thu, 26 Sep 2002 20:43:22 -0700 Subject: Can't suspend a thread? References: Message-ID: "Robert Oschler" wrote: > >"Tim Roberts" wrote: >> >> It is worth pointing out that this "restriction" is not a Python thing; it >> is an operating system thing. > >You mean a Linux/Python restriction? Windows can suspend threads so I >assume that's what you mean. Note I'm not saying that you can't suspend >threads on Linux (POSIX), I don't know if that's possible or not, I just >know you can on Windows. Hmm, you're quite right. I didn't realize you could suspend another thread in Win32. The documentation does caution against using it in anything other than a debugger, but it certainly exists. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sonnenbu at informatik.uni-bonn.de Wed Sep 18 10:09:02 2002 From: sonnenbu at informatik.uni-bonn.de (Frank Sonnenburg) Date: Wed, 18 Sep 2002 16:09:02 +0200 Subject: 'Real' global (write var to different namespace) References: <29242dfa.0209180310.94c915d@posting.google.com> Message-ID: "Maarten van Hulsentop" schrieb im Newsbeitrag news:29242dfa.0209180310.94c915d at posting.google.com... > Hi y'all > > I'm sorry if it's a FAQ but i honestly can't find to solution to my > problem; i've created a 'store' (a class) to store vars using the > (really cool) pickle classes. Now i can store a var doing: > "mystore['varname'] = myvar" and read it again by "myvar = > mystore['varname']". My question is if it's possible to create a > function like 'mystore.RestoreVars()' that sets ALL the stored vars in > the _calling_ namespace at once. > > Hope it's clear enough, i'm still a python newbie so excuse me if i > used the wrong terms or if i didn't explain it enough. > > Thanks > > Maarten van Hulsentop Maybe you will use this class prototype: ====================================================== class store: "Storage class for arbitrary data" def writeto(self, obj): "Make contents of storage instance visible in obj" obj.__dict__.update(self.__dict__) ====================================================== You have to pass the calling namespace explicitly, maybe you will see this as a disadvantage, but it fits to python philosophy: explicit is better than implicit. ====================================================== Examples: 1 - Instantiating of storage >>> st = store() >>> st.storage_var = 42 2 - Make visible in main scope >>> import sys >>> st.writeto(sys.modules['__main__']) >>> dir() ['__builtins__', '__doc__', '__name__', 'st', 'storage_var', 'store', 'sys'] >>> storage_var 42 3 - Make visible in some object >>> class c: ... pass ... >>> o = c() >>> st.writeto(o) >>> dir(o) ['storage_var'] >>> o.storage_var 42 4 - Usage in instance method >>> class cc: ... def f(self): ... st.writeto(self) ... >>> oo = cc() >>> oo.f() >>> oo.storage_var 42 ====================================================== Hope it is nearly what you desired -- Frank From eddie at holyrood.ed.ac.uk Thu Sep 12 12:56:36 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 12 Sep 2002 16:56:36 +0000 (UTC) Subject: Reading all text in telnet connection References: <4378fa6f.0209120722.227fe930@posting.google.com> Message-ID: mnations at airmail.net (Marc) writes: >Hi: >Having a small problem trying to capture all the text in a telnet >connection. I've used all the options of eager, lazy, etc., and can't >seem to find the right combo. >What I'm doing is intermittently writing data and then reading all of >the response. Unfortunately, all of the response might not immediately >appear. I started off using read_until, but there's nothing really >consistent that I can read to. So I need the ability to simply read >everything current in the buffer until EOF. I suspect you don't mean EOF, that only occurs when the connection is closed. There's really only 2 ways to know when output is finished: 1) Find a string to match on 2) keep reading until enough time has passed that you're fairly sure there will be no more output Because (2) is both slow and generally flaky option (1) is by far the best. However you say that there is nothing to match on, if that's really true you have to resort to hacks like waiting for time to pass. Because (1) is by far the best it is worthwhile making the effort to find a way of using it. If the problem is that there are several alternatives that might match you can use telnet.expect(). If there really is no sensible thing such as a prompt to match on it may be possible to match on your own echoed input if it's unique (this is especially true if you can send comments, I use this in speaking to routers where the prompt keeps changing - I send #gurgle and then look for this comimg back). There is one more possibility but I don't think it's appropriate from your description. If what you are doing is sending a few pre-determined commands collecting all the output and closing the connection then you MAY be able to get away with sending all the commands in advance (hoping the far end buffers them up) and use telnet.read_all() to wait for all the results (this depends on the far end closing the connection as a consequence of the commands you send). Essentialy, if there is nothing to match on you cannot reliably automate it. Eddie From nhodgson at bigpond.net.au Thu Sep 26 17:34:44 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Thu, 26 Sep 2002 21:34:44 GMT Subject: Pythonwin (win32all build 148) on Python 2.2.1 on Win2K, bogus syntax e References: Message-ID: Aaron: > Well, I did that, and that seems to be the problem. Is there a Pythonwin > setting I can set to make it do standard line endings? PythonWin itself does standard CRLF line endings. There is a script in the Python distribution Python22\Tools\Scripts\lfcr.py for fixing files. The script may be located elsewhere in older versions. Neil From jon+usenet at unequivocal.co.uk Mon Sep 23 23:19:50 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Tue, 24 Sep 2002 03:19:50 -0000 Subject: Python and cgi and problem! References: Message-ID: In article , Chris Liechti wrote: >>> print '%s' % (filename, filename) >> >> I hope none of your filenames have '"', ">" or "&" in. > > yeah i avoid characters that are special to the shell in my filenames - i > even don't use " " very often. > > sure there are improvements, but its a start. I'm not sure recommending completely broken and insecure code is ever a good thing. No offence intended. From max at alcyone.com Tue Sep 24 18:39:11 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 24 Sep 2002 15:39:11 -0700 Subject: List/Tuple bug or feature? References: <8765wv6o0d.fsf@nospam.eml.cc> Message-ID: <3D90E98F.95541F66@alcyone.com> Mahesh Padmanabhan wrote: > If this is a concatenation feature, how can I prevent something like > this happening in the future ? It's a standard feature, and doesn't have anything to do with tuples or lists: >>> 'a' 'b' 'ab' -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Once the people begin to reason, all is lost. \__/ Voltaire Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From aahz at pythoncraft.com Fri Sep 20 00:33:32 2002 From: aahz at pythoncraft.com (Aahz) Date: 20 Sep 2002 00:33:32 -0400 Subject: Destructor never called ??? References: <76710511.0209111450.40999dd8@posting.google.com> <4e8lou018f9uosl5p9mb0tt6691mfivamj@4ax.com> Message-ID: In article <4e8lou018f9uosl5p9mb0tt6691mfivamj at 4ax.com>, Tim Roberts wrote: >aahz at pythoncraft.com (Aahz) wrote: >>In article , >>Tim Roberts wrote: >>> >>>However, Python is a garbage-collected system. Unlike in COM, an object is >>>NOT destroyed as soon as its reference count goes to 0. Your object will >>>only be destroyed if the garbage collector happens to run, and decides that >>>it might be a convenient time to actually free up the space your object >>>occupies. >> >>Wrong. CPython uses reference counting backed by GC. > >Well, then, what was all the fuss about deterministic desctructors in the >newsgroup last year or so? Has this changed, or am I just remembering this >entirely wrong? There are several different issues. First of all, __del__ does not get called if an object is destroyed by GC (GC gets used to clean up cyclic garbage). Secondly, Jython does not use refcounting; it's pure GC, just like Java. Therefore, if you want to write portable applications, you should not rely on refcounting. Finally, there's a stylistic issue in programming. Some people believe that the "explicit is better than implicit" design goal requires cleaning up after oneself. Actually, it's unfair to say that it's "just" a stylistic issue -- it's certainly possible that calling out to libraries requires that one issue explicit close() calls. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From huaiyu at gauss.almadan.ibm.com Fri Sep 13 18:32:52 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Fri, 13 Sep 2002 22:32:52 +0000 (UTC) Subject: Restricting methods in derived classes References: Message-ID: Mark McEahern wrote: >Huaiyu, > >I feel compelled to gently ask, "What's the point of this rigamarole?" Maybe to show how to make a solution larger than the problem itself? :-) But seriously, your first solution actually contains all I needed. Here's what I adopted in the end: def undefined(self, *args, **kwargs): raise NotImplementedError _common = ['__class__', '__defined__', '__dict__', '__doc__', '__getattribute__', '__init__', '__new__'] def restrict(foo): for a in dir(foo): if a not in _common + foo.__defined__: setattr(foo, a, undefined) class foo(dict): def __init__(self, *args): print "foo", args def put(self, x): pass __defined__ = ['put', 'get', 'keys', 'items', 'values'] restrict(foo) if __name__ == '__main__': f = foo() print f.keys print f.keys() f['a'] = 'b' Maybe there is a simple way to wrap up restrict() in a metaclass, so that instead of restrict(foo) we can say class foo(dict, restricted): ... I'm still not so used to metaclasses to figure that out, however. Huaiyu From martin at v.loewis.de Wed Sep 4 17:39:03 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Sep 2002 23:39:03 +0200 Subject: Why read-only nested scopes? References: Message-ID: bokr at oz.net (Bengt Richter) writes: > OTOH, if "everything is an object," then the namespace of > an enclosing scope could also be an object, and as such > could support rebinding of names therein ;-) It is an object - the frame object. There is just no easy way to refer to that object. Regards, Martin From akakakhel at attbi.com Sat Sep 14 18:43:52 2002 From: akakakhel at attbi.com (Ali K) Date: Sat, 14 Sep 2002 22:43:52 GMT Subject: IDLE References: Message-ID: OS: Win98 Version 2.2 double clickidle.pyw yes From gustav at morpheus.demon.co.uk Sat Sep 21 15:42:07 2002 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: 21 Sep 2002 20:42:07 +0100 Subject: Python 2.2.1 compatible with Tcl/Tk 8.4? References: Message-ID: loewis at informatik.hu-berlin.de (Martin v. L?wis) writes: > Andrew Koenig writes: > > > Now that Tcl/Tk 8.4 is out, can anyone tell me whether Python 2.2.1 > > will work with it? > > It appears to work fine here, and I can't see a reason why it would be > incompatible. Notice that the setup.py of 2.2.1 is already prepared to > search for Tcl/Tk 8.4 on its own. Can ActivePython be persuaded to use TCL 8.4? I notice it has its own internal TCL 8.3 DLLs etc. If I install TCL 8.4, will Python notice? Hmm, experimenting, it looks like it doesn't. So I must have to tell Python to use the installed TCL 8.4. How? Thanks, Paul. From lpgray at uop.com Wed Sep 18 15:50:00 2002 From: lpgray at uop.com (Lee Gray) Date: 18 Sep 2002 12:50:00 -0700 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: <96904b50.0209181149.429e8533@posting.google.com> lpgray at uop.com (Lee Gray) wrote in message news:<96904b50.0209171305.6d65f574 at posting.google.com>... > I'm a fairly new programmer with experience in ASP/VBScript/DHTML. [...] > Can someone point me to a good Python GUI app to demonstrate (other > than IDLE)? Thanks for all the suggestions, folks! I've collected lots of links to a variety of very nice screenshots, and I've been playing with the wxWindows demo and Boa Constructor. Boa was a bit disappointing, not as an app, but because of its current alpha status - but it's got great potential and I'll definitely look forward to future releases. I'll check out PythonCard too. Regarding .Net AND Python, that's certainly a possibility down the road, but unfortunately I don't have the time to devote to learning both at the moment, and if we definitely go .Net, no one (besides me) is going to see any value in adding Python. Thanks again... and feel free to send more ideas! Lee From b.maryniuk at forbis.lt Tue Sep 3 03:52:31 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 3 Sep 2002 09:52:31 +0200 Subject: Why it is so dramatical? In-Reply-To: <20020902.104707.1789376348.1554@cybermesa.com> References: <20020902.104707.1789376348.1554@cybermesa.com> Message-ID: <200209030952.31569.b.maryniuk@forbis.lt> On Monday 02 September 2002 05:47, Jay O'Connor wrote: > As a result Perl is much faster at some kinds of operations than > Python, and vice-versa. Yeah, actually, but I just would like to find some optimal Python solution :) -- Regards, Bogdan We did it for smallpox, we'll also win over on ISO 8859-1 ... ;-) -- Markus Kuhn after eradicating one more ISO 8859-1 file from his disk From brobbins333 at shaw.ca Mon Sep 30 12:53:13 2002 From: brobbins333 at shaw.ca (brobbins333 at shaw.ca) Date: Mon, 30 Sep 2002 16:53:13 GMT Subject: rank-0 arrays? Message-ID: <3d988160.79509684@news> In Numeric Python, what are rank-0 arrays? Must not arrays have at least 1 dimension? BR From stefanus.arief at ai.astra.co.id Mon Sep 23 23:26:44 2002 From: stefanus.arief at ai.astra.co.id (Arief) Date: Tue, 24 Sep 2002 10:26:44 +0700 Subject: confusion about opening files In-Reply-To: <3D8FD2F3.81F3831C@alcyone.com> Message-ID: >-----Original Message----- >> O. K. Now I am confused. I thought that when I imported the os >> module, i >> would have to call its functions like this: os.open() Why am I just >> using >> the function name? > >Because there are two different open functions here. One is in the >builtins, one is in the os module. They are not the same: > >>>> import os >>>> print open.__doc__ >file(name[, mode[, buffering]]) -> file object > >Open a file. The mode can be 'r', 'w' or 'a' for reading (default), >writing or appending. The file will be created if it doesn't exist >when opened for writing or appending; it will be truncated when >opened for writing. Add a 'b' to the mode for binary files. >Add a '+' to the mode to allow simultaneous reading and writing. >If the buffering argument is given, 0 means unbuffered, 1 means line >buffered, and larger numbers specify the buffer size. >Note: open() is an alias for file(). > >>>> print os.open.__doc__ >open(filename, flag [, mode=0777]) -> fd >Open a file (for low level IO). > >The os.open is a low-level API and is rarely going to be the one you >want. The os.open is os syscall (system call). It is used to open file, fifo, device, etc in UNIX or Linux environment (I don't know about MS Windows). Because it is an os syscall, so any further operation should use appropriate os syscall too, for example: import os fname = '/tmp/a.txt' fd = os.open(fname) # open file, get file descriptor used by OS os.write(fd, 'this is only example\n') # further operation - write file ... os.read(fd, 1024) # further operation - read file 1024 bytes ... os.close(fd) # closing file The built in function: "open" uses c function "fopen". It is a buffered version of os syscall "open" implementation. You should use appropriate function for further operation too, for example: fname = '/tmp/a.txt' f = open(fname, 'w') f.write('this is only example\n') f.close() It is "not guaranteed" that as soon as you complete the f.write call, the file is written with data you've feed. Because it is a buffered operation. So to assure the OS to write your text immediately, you should do this: fname = '/tmp/a.txt' f = open(fname, 'w') f.write('this is only example\n') f.flush() # flush buffered data for previous write operation f.close() I hope it would help you. Any correction is welcomed ... ----- Arief From phncontact.libero.it at Fri Sep 20 03:28:52 2002 From: phncontact.libero.it at (Benjamin) Date: Fri, 20 Sep 2002 07:28:52 GMT Subject: general thoughts Message-ID: hi everybody first: only read this post if you have enough time (real meaning: please don't flame me just because i don't ask any concrete questions "wasting" your time :) i have an unusual problem with programming python, nothing tecnical, something which goes "deeper". you may call it inspiration, see me as an artist who lacks of inspiration (i know there are many people who think programming is an art). some weeks ago i began learning python as my first (i hope some others will follow) programming language, i've been going through some tutorials, but they begin to bore me. the only interesting thing (from a beginners point of view, of course) i programmed is a small database script which receives user input and stores things in a txt file. that was real fun, writing code, debugging, rewriting, analyzing, trying to figure out the problem, in one word: coding. but now i don't know what to programm. sounds weird, doesn't it? :) what should i program?? at the moment i have windowsXP installed, but i hope to switch soon to some linux distribution or freeBSD. maybe my problem gets better then. i've been learning python not for becoming a programmer (i study modern languages at the university), but for having fun. my personal motto is "i want to know how it works". i am always trying to deepend my computer knowledge. maybe i should learn more about computer security and write security stuff, or cryptography (hey i could try to write the ultimative windows security patch that fills all security holes in m$'s os & co. and get rich ^_^). it certainly wouldn't be boring. i don't think i will ever write programs for living, as a job. when i finished highschool many people thought i will study computer science because i were (and still am) into computers - i actually did quite the opposite. i think if it's a job, it's something i MUST do - and therefore not interesting anymore -, and not something i CAN do if i want. well, i hope i didn't bore you :) i would really like if you share your opinions about those things with me/us. bye, benjamin From imbosol at vt.edu Fri Sep 20 15:10:47 2002 From: imbosol at vt.edu (Carl Banks) Date: Fri, 20 Sep 2002 15:10:47 -0400 Subject: average? References: Message-ID: Mark McEahern wrote: > I know I can average a sequence like this: > > def average(seq): > return reduce(operator.add(seq) / len(seq)) > > Yes, I see that will raise ZeroDivisionError if seq == []. Aside from that, Appropriate, I'd say, since the average of a zero-length sequence is undefined. > 1. Is there anything else dumb about the above? Well, yes; it seems to me you meant this: def average(seq): return reduce(operator.add,seq)/len(seq) What I can't figure out is how you got from this to what you typed. :-) > 2. Am I missing a builtin cousin of min, max that would do this for me? In pure Python, I don't think so. I would be surprised if the above function (when typed correctly) isn't the fastest way in pure Python. -- CARL BANKS http://www.aerojockey.com From jggramlich at yahoo.com Tue Sep 3 14:40:49 2002 From: jggramlich at yahoo.com (Joshua Gramlich) Date: 3 Sep 2002 11:40:49 -0700 Subject: PyListObject & C Modules Message-ID: Hello, I have a problem where I need to pass a Python list to a C module, and have a differnent list passed from the C module back to Python. I am trying to find examples of this type of activity. I've found the documentation at www.python.org (the C api), but I'm a bit green (new) and cannot read the List Objects page with any, well, usefulness. Thus, I cannot figure out exactly if this can or cannot be done and what the syntax of usage of PyListObject should be... Little help? From mark at freelance-developer.com Wed Sep 18 18:59:35 2002 From: mark at freelance-developer.com (Mark Nenadov) Date: Wed, 18 Sep 2002 18:59:35 -0400 Subject: linux python ideas References: <3D88E578.6010001@diespammerdieuselesspython.com> Message-ID: <20020918.185929.653468858.1365@x1-6-00-d0-09-7e-c7-3e.wido3.on.cogeco.ca> In article <3D88E578.6010001 at diespammerdieuselesspython.com>, "Rob Andrews" wrote: > I'll be giving a presentation on Python to my local LUG > (http://lugoj.org) in a few weeks, and would like to point out at least > a few things that would be of particular interest to linux users. The > idea is not "how to program in Python", which would take more than one > quick presentation, but a one-off demonstration of ways in which Python > is particularly useful for such a group. Any suggestions would be > appreciated, since my notes are pretty generic so far. Since you aren't trying to teach the language, but rather provoke some interest in Python, it may be a good idea to just show a few specific libraries and problem domains in which Python can excel. Here are some topics that might suffice: 1) Overview of open source projects that use Python 2) About GUI libraries available for Python 3) Zope 4) ReportLAB (a Python library for PDF generation) 5) Jython ~Mark (http://www.freelance-developer.com) From jb at cascade-sys.com Tue Sep 17 02:32:01 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Mon, 16 Sep 2002 23:32:01 -0700 Subject: How to represent sets References: <7xn0qjacx6.fsf@ruckus.brouhaha.com> Message-ID: <3D86CC61.3080909@cascade-sys.com> Paul Rubin wrote: >"James J. Besemer" writes: > > >>For dense sets isomorphic with integers, the long integer >>implementation probably will be superior. >> >> > >Using immutable long integers to represent mutable sets doesn't make >much sense. Better to use arrays like the ones implemented by the >array module. > First off, by "superior" I meant superior to a dictionary implementation. Second, I don't see why arrays would be that much better than long integers. Depends on the relative efficiency of arrays vs. long integers. Perhaps I give the Python implementers too much credit, but I also expect that the implementation of long integers would be about as good as it gets in Python with arbitrary bit vectors. I may be overly optimistic on this last point but even if the implementation of long integers is mediocre, I'd expect it to be better than arrays. Given the generality of having to handle a variety of sub-types, off hand, I'd expect arrays to have a little more built-in overhead. Furthermore, the array module has no methods for doing arithmetic on the entire array. Thus to AND or OR two arrays together, you need to write an explicit loop or map(). I can't believe it would be as fast as the builtin operations for long integers. And the work to make the result array the proper length would have to be spelled out in long hand, while it's atomic with long integers. You seem to attach some special significance to the fact that long integers are "immutable" while arrays are not. However, from the little bit that I've studied, the implementation is smart enough to reuse the erstwhile 'immutable' values of intermediate results from expressions, thus eliminating a pair of create/destroy operations. I believe they also optimize special cases like bits1 |= bits2 and reuse the 'immutable' representation of the value of bits1 if the reference count is 1. If not, then it should do. In the more general cases, both implementations (arrays or long ints) would have to create a new destination result and probably free an old one. Maybe you're right but I just don't see why an array implementation of a bit set would be faster than a long integer implementation. Do you have any benchmarks to support your argument? Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From BPettersen at NAREX.com Mon Sep 16 17:26:05 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 16 Sep 2002 15:26:05 -0600 Subject: file mode attributes... Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019201253349@admin56.narex.com> > From: Martin v. L?wis [mailto:loewis at informatik.hu-berlin.de] > > "Bjorn Pettersen" writes: > > > I was wondering if this was the best way of implmenting these > > functions (windows)? > > Yes. Thanks. Do you think there would be any interest in adding these kinds of utility functions to e.g. the os.path module? [snip] > Notice that, on WNT/2k/XP, you might also need to modify the > access control list to give users permissions, especially if > the files are on NTFS. Access and modification of the ACL is > not supported in standard Python. win32all isn't standard on Windows ? Seems like it would be pretty straightforward (although tedious) with win32security.ACL() etc. Thankfully I don't have to deal with that for this project (I just need to make sure the current process doesn't delete the files accidentally :-) -- bjorn From pyth at devel.trillke.net Fri Sep 20 18:02:46 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 21 Sep 2002 00:02:46 +0200 Subject: Minimal debug/rep functionality In-Reply-To: ; from tdelaney@avaya.com on Fri, Sep 20, 2002 at 11:18:35AM +1000 References: Message-ID: <20020921000246.D30315@prim.han.de> Delaney, Timothy wrote: > > From: holger krekel [mailto:pyth at devel.trillke.net] > > > > Delaney, Timothy wrote: > > > > From: Peter Hansen [mailto:peter at engcorp.com] > > > > > > > As I said, I *expect* to be able to release (there's no > > commercial reason > > > not to, and we have done so with such things in the past). > > > > Maybe we are turning circles [1] but why don't you do it, then? > > > > Maybe you need to invest some time in obfuscating your > > source code and you don't want to do it? > > > > Why do you *expect* others to solve this problem for you? > > Holger, what the hell are you talking about? Oh, i am very sorry. I completly mixed up discussions and for some reason posted to the complete wrong thread :-( I thought this still was the thread on how to protect a commercial release of a python program .... It was late in the night, i had a sloppy network connection and all that. so please take my excuse, holger From gerhard.haering at gmx.de Sun Sep 1 15:13:56 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 1 Sep 2002 21:13:56 +0200 Subject: Making regex suck less In-Reply-To: <3d725881.345921@news.t-online.de> References: <3d725881.345921@news.t-online.de> Message-ID: <20020901191356.GA3759@lilith.ghaering.test> * Gerson Kurz [2002-09-01 18:31 +0000]: > [...] Anyway, that got me thinking on why do we have to deal with > regular expressions like r"((?:a|b)*)", when in most cases the code > will look something like this: > > r = re.compile("") > ... > r.match(this) or r.find(that) If you only use the RE once, you can use the module-level functions ;-) > which means the real time is not spent in the compile() function, but > in the match or find function. So basically, couldn't one come up with > a *human readable* syntax for re, and compile that instead? That's equally powerful? Most probably not. > Also, I think it would already be an improvement if the syntax > provided for clear and easy-to-understand special cases, like > > re.compile("anything that starts with 'abc'") s.startswith("abc") s.lower().startswith("abc") > and if you cannot find something in the special cases for you, you can > always go back to > > re.compile("") > > After all, *everyone* starting with re thinks the syntax is cryptic > and mind-boggling, and only if you get yourself into the "re mindset", > you understand things like r"\s*\w+\s*=\s*['\"].*?['\"]" instantly. If > we had an easier syntax, more people would be using re ;) > > Is the idea utterly foolish? I don't really know. IMO if you have very simple string-searching, then you can probably get away with the string methods, and if you have very complex stuff, then you'll probably be better of with a parser generator (like SimpleParse, which is very readable, IMO). I don't find regular expressions that unreadably, especially when I consider that I'd have to write many lines of error-prone Python code instead. Stuff like this is just too convenient: # working around zxDateTime limitations: if JYTHON: import re ISO_DATE_RE = re.compile(r"(\d\d\d\d)-(\d\d)-(\d\d)") def DateFrom(s): match = ISO_DATE_RE.match(s) if match is None: raise ValueError return DateTime(*map(int, match.groups())) Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From syver-en+usenet at online.no Tue Sep 10 13:05:18 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 10 Sep 2002 17:05:18 GMT Subject: embedded Python sample References: <2a0f4cc4.0209100520.1d3a723b@posting.google.com> Message-ID: monnetb at yahoo.com (bruno Monnet) writes: > Hi, > > I'm trying to call a python script from my c++ code. All I need is to > invoke the script and check the return status. > > does anyone has a simple example ? All I found until now is very > complex and ugly code :-(( I think something like this will do (untested) void runPythonFile(char* myfile) { FILE* fileptr = fopen(myfile, 'r'); Py_Initialize(); int result = PyRun_SimpleFile(fileptr, myfile); Py_Finalize(); return result; } You should get some ideas by reading the Extending/Embedding section in the python manual, and then read the relevant sections the Python/C api. -- Vennlig hilsen Syver Enstad From gerhard.haering at gmx.de Fri Sep 13 12:11:21 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 13 Sep 2002 16:11:21 GMT Subject: function pointer References: Message-ID: James J. Besemer wrote in comp.lang.python: > Gerhard H?ring wrote: > >>Broken quoting - yuck! Your newsreader is broken. Please repair it (using >>third party software) or make Usenet a better place by throwing away that >>crapware. >> > > I believe this error occured when the line was wrapped by the > python-list mailer, not necessarily the submitter's newsreader or > email program. No, it's one of these Outlook Express bugs that are known for years at Microsoft, but never got fixed. It happens when text of the referenced message gets quoted and Outlook Express does its wrapping of text to the set width later. It's most annoying to those who have to read that broken quoting style. There are other bugs that are known equally long, but at least they don't annoy anyone besides those that deserve it, like: begin loveletterforyou.vbs hahaha end No matter where OE or Outlook find this in a message, they interpret it as an attachment, ignoring the rest of the message. This has also been known for years, but instead of just fixing their email parsing, they wrote a laughable MSDN article that recommends to not use "begin " in messages. >>If we want to keep the terminology right, Python doesn't have variables. It >>has names and values. > > The fact that The Tutorial and other Python doc uses the term "variable" > makes it confusing for newcomers. Sorry, I probably was too harsh about this. It's just that using the terms 'name' and 'value' instead of variable made it a lot simpler for me to understand the concepts of the Python data model. In fact, I think I got them from the Python Language Reference, which explains the Python data model using the terms: - objects, values and types - identifiers (names) http://www.python.org/doc/current/ref/objects.html http://www.python.org/doc/current/ref/atom-identifiers.html The reason why I objected to the term variable was that (at least for me) it has the connotation of strong typing, where a variable can only hold values or references to objects of (subclasses of) the declard type. Dismissing the use of 'variable' to describe Python behaviour was premature, though. It certainly has its uses, it's just that it is IMO less accurate than the terms from the Python Language Reference. -- Gerhard From christophe.delord at free.fr Mon Sep 9 13:35:42 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Mon, 9 Sep 2002 19:35:42 +0200 Subject: random.shuffle question References: <3k4f9.7500$yt3.3831288@newssrv26.news.prodigy.com> Message-ID: <20020909193542.08c6937a.christophe.delord@free.fr> It works but not as you may expect. l[4:8] is another list made with l[4] to l[7] and changing l[4:8] does not change l. For example : >>> l = [1,2,3,4,5,6,7,8,9] >>> l2 = l[4:8] >>> l2[2] = 99 >>> l2 [5, 6, 99, 8] >>> l [1, 2, 3, 4, 5, 6, 7, 8, 9] So when you shuffle l[4:8] you shuffle a copy of a sublist of l. In the previous example you can consider that l2 is the argument given to shuffle. One solution is to shuffle the sublist and copy the sublist in the list: >>> l = [1,2,3,4,5,6,7,8,9] >>> l2 = l[4:8] >>> random.shuffle(l2) >>> l[4:8] = l2 >>> l [1, 2, 3, 4, 6, 7, 8, 5, 9] But this may be inefficient on larger lists. Christophe. On Mon, 09 Sep 2002 16:51:11 GMT "dsavitsk" wrote: > why does this not work to shuffle part of a list? > > >>> l = [1,2,3,4,5,6,7,8,9] > >>> random.shuffle(l[4:8]) > >>> print l > [1, 2, 3, 4, 5, 6, 7, 8, 9] > > and more importantly, is there a better way to do this? > > -d > > -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From mertz at gnosis.cx Mon Sep 16 09:52:54 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 16 Sep 2002 09:52:54 -0400 Subject: Source code References: Message-ID: <2Ieh9kKkXMhU092yn@gnosis.cx> "dsavitsk" wrote previously: |If your code is that valuable, run it on your server remote from end |users as a trade secret, or force them to agree to a license and protect |it w/ copyright. I would reformulate the issue slightly: If you BELIEVE your code is that valuable, seek psychiatric help. Yours, Lulu... -- mertz@ _/_/_/_/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY:_/_/_/_/ v i gnosis _/_/ Postmodern Enterprises _/_/ s r .cx _/_/ MAKERS OF CHAOS.... _/_/ i u _/_/_/_/_/ LOOK FOR IT IN A NEIGHBORHOOD NEAR YOU_/_/_/_/_/ g s From wesc at deirdre.org Thu Sep 5 14:40:07 2002 From: wesc at deirdre.org (Wesley J. Chun) Date: 5 Sep 2002 11:40:07 -0700 Subject: ANN: BayPIGgies mtg Wed 9/11 7:30pm Message-ID: BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group Agenda: Using a New MVC Architecture to Create a Pythonic XML-based Web Application Framework When: September 11, 2002 @ 7:30pm Where: Stanford University, Palo Alto, CA Speakers: Paul McGavin, Donovan Preston, Sam Penrose from InterSight We will discuss how we are applying a new Python-based MVC architecture to create an efficient, Pythonic web application framework that separates presentation templates from the Python source code with DOMTemplate. The framework componentizes behavior into reusable objects with DOMWidgets and DOMHandlers. After creating web applications in three separate Python frameworks -- Webware for Python, Zope and Apache/Python cgi -- InterSight decided to create its own MVC framework, based on some of the ideas from IBM and Lutris Enhydra's Barracuda project, to power their automated publishing applications. Their applications enable scalable content: the ability to produce, from a single set of managed data and images, many different marketing communication pieces: press- ready Adobe InDesign and QuarkXPress files, web pages, order sheets, sample stickers, price tags and more. We are actively seeking speakers for BayPIGgies, esp. October 9th! If you would like to give a talk at one of our meetings (any Python- related topic), please contact us! more info including directions: http://www.baypiggies.net hope to see some of you on Wednesday! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, ? 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://www.baypiggies.net wesley.j.chun :: wesc at deirdre.org cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://roadkill.com/~wesc/cyberweb/ From duncan at NOSPAMrcp.co.uk Mon Sep 2 11:19:44 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 2 Sep 2002 15:19:44 +0000 (UTC) Subject: Newbie's unsurmountable pb with IO stream trick References: Message-ID: spendius at muchomail.com (Spendius) wrote in news:aba30b75.0209020633.26ba4c70 at posting.google.com: > So I have a challenge for you guys who are enough acquainted > with Python: how could I perform the same with this language ? What operating system are you running on? I believe there are ways to do this on unix or on windows, but they are totally different. Do you really need to access your database through this frontend program? Your life might be much easier if you connected to the database directly. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From noah at noah.org Mon Sep 9 16:08:00 2002 From: noah at noah.org (Noah) Date: 9 Sep 2002 13:08:00 -0700 Subject: Integer overflow in fcntl on some Linux platforms. What's going on? Message-ID: Hello, Can anyone help me figure out what the problem is here? On some Linux platforms when I try to execute the following code: s = struct.pack("HHHH", 24, 80, 0, 0) x = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCSWINSZ, s) I get this exception: 'signed integer is greater than maximum' It seems that Linux does not like the integer from sys.stdout.fileno(), but this has worked fine on all the BSD machines and one Linux 2.2.20 machine I tested it on. So far only RedHat 7.1 has this problem. Or maybe it does not like the constant termios.TIOCSWINSZ (set win size), yet it has no problem with the similar constant termios.TIOCGWINSZ (get win size). The following is a test script that demonstrates this problem. It logs all steps to a file called LOG. It crashes after STEP 5 inside getwinsize() at STEP getwinsize() 2. This line is the ioctl() call. This is the results I get in my LOG file: STEP 1: pid: 274968 STEP 2: stdout.fileno(): 1 STEP 3: stdout.fileno() hex: 1 STEP 4: termios.TIOCSWINSZ: 2148037735 STEP getwinsize() 1. STEP getwinsize() 2. STEP getwinsize() 3. STEP 5: getwinsize() #1: (54, 80, 0, 0) STEP setwinsize() 1. STEP setwinsize() 2. EXCEPTION: signed integer is greater than maximum Any help would be appreciated. Yours, Noah #!/usr/bin/env python import os, sys, termios, fcntl import struct def setwinsize(): # Assume ws_xpixel and ws_ypixel are zero. log ('STEP setwinsize() 1.') s = struct.pack("HHHH", 24, 80, 0, 0) log ('STEP setwinsize() 2.') x = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCSWINSZ, s) log ('STEP setwinsize() 3.') def getwinsize(): log ('STEP getwinsize() 1.') s = struct.pack("HHHH", 0, 0, 0, 0) log ('STEP getwinsize() 2.') x = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, s) log ('STEP getwinsize() 3.') return struct.unpack("HHHH", x) def log (s): fout = open ('LOG','a+') fout.write(s) fout.write('\n') fout.close() pid = os.getpid() log ('STEP 1: pid: ' + str (pid) ) log ('STEP 2: stdout.fileno(): ' + str(sys.stdout.fileno()) ) log ('STEP 3: stdout.fileno() hex: %x' % sys.stdout.fileno() ) log ('STEP 4: termios.TIOCSWINSZ: ' + str(termios.TIOCSWINSZ) ) try: log ('STEP 5: getwinsize() #1: ' + str (getwinsize())) setwinsize() log ('STEP 6: getwinsize() #2: ' + str (getwinsize())) except Exception, e: log ('EXCEPTION: ' + str(e)) sys.exit(0) print print 'Log file written. It is called "LOG".' print print open('LOG').read() From loewis at informatik.hu-berlin.de Fri Sep 27 07:46:10 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 27 Sep 2002 13:46:10 +0200 Subject: py2exe Error creating NT Service References: Message-ID: "Harald Schneider" writes: > exec compile(open(self.script).read(), self.script, "exec") in > mod.__dict__ > File "", line 101 > > SyntaxError: invalid syntax [...] > Any ideas? I would print self.script, and look at line 101 of the file named by self.script. Regards, Martin From joconnor at cybermesa.com Thu Sep 26 02:09:41 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Thu, 26 Sep 2002 13:09:41 +0700 Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> <3D934C5C.4000603@mxm.dk> Message-ID: <20020926.130938.1789366143.1524@cybermesa.com> In article <3D934C5C.4000603 at mxm.dk>, "Max M" wrote: > Pat Notz wrote: >> @ = "at" >> ! = "bang" >> . = "dot" >> * = "star" >> >> Is there a short (one or two syllable) pronounciation for "__" (double >> underscore). "Underscore underscore" and "double underscore" are kind >> of long. Somthing like "splat"? Anyone? > > _ = 'under' > > __ = 'under-under' How about "underder"?? -- Jay O'Connor joconnor at cybermesa.com http://www.r4h.org/r4hsoftware From marklists at mceahern.com Thu Sep 26 09:25:35 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 26 Sep 2002 08:25:35 -0500 Subject: Is there a way to find the name of the method currently being executed? In-Reply-To: <3D9278D0.9060307@arielpartners.com> Message-ID: import sys def func1(): print "my name is %s" % myname() def myname(): steps_back = 1 return sys._getframe(steps_back).f_code.co_name func1() From jeff at sasmor.com Sun Sep 8 16:58:48 2002 From: jeff at sasmor.com (Jeff Sasmor) Date: Sun, 08 Sep 2002 20:58:48 GMT Subject: Zope Status? References: Message-ID: Speaking from what I understand about this subject, it's not simple for the Zope Corp to merely plug-in a new version of Python and make a release. Disregarding any issues about changes they might want to make that would take advantage of new features of Python 2.2 (and up), the underlying instrumentality of Zope, the ZODB (Zope Object DataBase) as it exists in Zope 2.5 and so on, will not run under Python versions > 2.1 due to incompatibilities of the C extension classes with the changes made (in Python 2.2) regarding type-class unification. Obviously, there's already a version of ZODB for Python 2.2, but I think it's not something that one cannot just 'drop in' to a current version of Zope. That's just one thing. Also, Zope 3 is a clean-slate redesign; that is, it is being rearchitected with no initial regard for existing Zope applications. I suppose opinions go either way on this, but overall it is probably a Good Thing. I recall reading that there will eventually be backwards compatibility, perhaps with some interface layer, but I suspect that the initial releases will be for very advanced developers. BTW, I don't speak as a member of the Zope team, just someone who's been lurking on all the dev lists for Zope 3 and the ZODB as I am developing an app based on the ZODB and need to track what these folks are doing. Apologies in advance to Zope Corp for any inaccuracies. jms -- #-------------------------------- Jeff Sasmor jeff at sasmor.com "Bo" wrote in message news:Xns9281221A07167bosahvnetscapenet at 66.185.95.104... > I apologise if this isn't the proper forum to do this in. > > 1) Can anyone tell me roughly if\when Zope is moving to python 2.2? > > 2) Also any idea when they might release Zope 3? > > 3) Anyone close to the Zope team who is willing to shed some light on the > near future for things Zope? > > > Great thanks in advance. > > Bo From see_reply_address at something.invalid Sun Sep 22 21:44:42 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 23 Sep 2002 13:44:42 +1200 Subject: Python about file I/O References: <3d8da3df@nntp.server.uni-frankfurt.de> Message-ID: <3D8E720A.90501@something.invalid> Michael Janssen wrote: > existence-check is: > os.access(file,os.F_OK) But it's generally considered preferable to just go ahead and try to open the file, and catch the exception if it fails. Some reasons for preferring this approach include: * It will catch all possible reasons for failing to open the file, not just lack of existence or permissions. * It's not prone to something happening in between testing and opening which causes the file to no longer be openable. * It's more efficient -- only one file system operation instead of two. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From sholden at holdenweb.com Sat Sep 7 14:33:07 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 7 Sep 2002 14:33:07 -0400 Subject: encryption (passwords) References: <3d75d115$0$221$4d4ebb8e@news.nl.uu.net> Message-ID: "Gerhard H?ring" wrote in ... > Gumuz wrote: > > I am quite a newbie regarding encryption stuff. There are some issues > > boggling my head and I suppose these come from the fact that I have no > > clue how to apply encryption in a real-life situation. > > > > I am using network-sockets to communicate between two(or more) python > > applications. I want to encrypt these messages, or at least a part of it > > e.g. password and such. > > Ok. I'd recommend to use SSL instead of inventing your own crypo layer. I'd > probably go with PyOpenSSL. > I'd agree that implementing your own encryption technique is unlikely to be secure. Use the work that's already been done. > > My limited understanding of encryption tells me that I need a 'key' to > > decrypt stuff. > > There are two kinds of encryption: > - symmetric encryption > - assymemtric encryption > > Symmetric works by both ends having the same key. The sender encrypts the > message with the key, the receiver decrypts it using the same key. The > problem is that you have to distribute the keys first, and have a secure > way of distributing the keys. > In other words, a second (secure) channel is required to comunicate the key to be used on the first channel. Fortunately teh second secure channel can be the same channel but using public-key (asymmetric) encryption. > Asymmetric encryption works by splitting the key up into a private and a > public key. The private key can only be used for decrypting, the public key > only for encrypting messages. > Not strictly true, it depends on the requirements. Aysmmetric encryption can be used to provide three different features: 1. Privacy. In this case the sender encrypts the message with the recipient's public key. Since it can now only be decrypted by the holder of the corresponding private key, the assumption is that only the intended recipient will be able to decrypt it. This is the case Gerhard describes. 2. Authentication. Here the sender encrypts the message with their own private key. Anyone with access to the sender's public key can decrypt it, and since the decryption process gave a legible message it is reasonable to assume that it really was encrypted by the holder of the corresponding private key. 3. Integrity. Here the sender generates a message digest (some function computed from the content of the message, ideaaly using a recognized cryptographic hashing function). The digest is of fixed length, and with a "good" hashing function it won't be possible to generate arbitrary message digests with a particular digest value. The sender then encrypts the digest value with their private key, producing what is normally calles a "digital signature". The recipient decrypts the digest with the sender's public key, and independently verifies (by generating another message digest locally) that the message they received has the same digest value as that inserted by the sender. If this is not the case then either the content or the digest has been tampered with, and the message content should not be trusted. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From eric.brunel at pragmadev.com Thu Sep 5 04:17:31 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 5 Sep 2002 10:17:31 +0200 Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> Message-ID: Naveed Iqbal wrote: > I have to print to a standard printer. I take the data from the > keyboard and print it using the printer. Please help me....my job > depends on this!!!! Things are quite different on Unix and Windows. Just a sample (untested) program to print "Hello world!" to the default printer on both platforms: ----Unix---------------------- import os p = os.popen('lpr', 'w') p.write("Hello world!\n") p.close() ------------------------------ ----Windows------------------- import win32ui dc = win32ui.CreateDC() dc.CreatePrinterDC() dc.SetMapMode(4) # This is UI_MM_LOENGLISH ## With this map mode, 12 points is 12*100/72 units = 16 font = win32ui.CreateFont({'name' : 'Arial', 'height' : 16}) dc.SelectObject(font) dc.StartDoc("HelloWorld") dc.StartPage() dc.TextOut(40, 40, "Hello world!") dc.EndPage() dc.EndDoc() ------------------------------ And now you wish you were on Unix ;-)! For more information on the Windows version, see the documenattion for win32ui @ http://aspn.activestate.com//ASPN/Python/Reference/Products/ActivePython/PythonWin/modules.html and Micro$oft MFC documenation @ http://msdn.microsoft.com/library/default.asp Good luck! PS: I'm actually a little biased towards Unix... In fact, if you have the printer directly connected to your PC, opening LPT1: and just writing the text to it should work. But if it's a network printer, the only solution is the code above... We also can make things a little more complicated on Unix by using PostScript. But it's still shorter: import os p = os.popen('lpr', 'w') p.write('%!PS\n') p.write('/Helvetica findfont 12 scalefont setfont\n') p.write('/cm { 72 mul 2.54 div } def\n') p.write('1 cm 28 cm moveto\n') p.write('(Hello world!) show\n') p.write('showpage\n') p.close() -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From sholden at holdenweb.com Wed Sep 18 12:25:22 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 18 Sep 2002 12:25:22 -0400 Subject: Loading modules from several directories References: <33803989.0209172247.2e6afc1f@posting.google.com> Message-ID: <6Q1i9.1149$bh1.989@fe03> "Eugene Pervago" wrote ... [...] > If I put the project_a path first, it loads its modules but can't > import the /onedir/foo modules. It seems package can only be in one > place, once Python finds it, it just stops looking elsewhere. > What would you rather have it do? Load them both? Find every possible package and load the oine with the most recent modification date/time? Load the longest one? Load the one whose checksum is closest to your birthdate? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From whisper at oz.net Mon Sep 9 19:28:09 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 9 Sep 2002 16:28:09 -0700 Subject: a re question In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Rajarshi Guha > Sent: Monday, September 09, 2002 13:11 > To: python-list at python.org > Subject: a re question > > > Hi, > I have a file with lines of the format: > > 001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23 > 001 Xya FGh 143557789 7 100 09/05/2002 20:23:23 > > I am trying to extract the 9 digit field and the single digit field > immediatley after that. > > When I use Visual Regexp to try out the regexp > > (\d{9,} {3,}\d) > > it highlights the 2 fields exactly. > > But when I use the following Python code I get None: > > >> s='001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23' > >> p = re.compile(r'(\d{9,} {3,}\d)') > >> print p.match(s) > >> None > > Could anybody point out where I'm going wrong? > > Thanks, Yes - match always starts looking for a match at the beginning of the line - try p.search instead. See python22/doc/lib/matching-searching.html I would also suggest using \s{3, } instead of what you have for clarity in skipping the spaces between the 9 digit number and the single digit number. You might find that putting parens around each element you want to extract a convenient shortcut; then if you do elts = p.search(s), elts.group(1) will be the 9 digit number and elts.group(2) will be the single digit. The pattern would then look like: r'(\d{9, })\s{3, }(\d)' you could also do num9, num1 = elts.group(1,2) if you're in a hurry ;) HTH, Dave LeBlanc Seattle, WA USA From josh_py at sautez.com Tue Sep 17 13:15:19 2002 From: josh_py at sautez.com (josh_py at sautez.com) Date: Tue, 17 Sep 2002 10:15:19 -0700 Subject: using python as cgi on apache unix References: Message-ID: "Dennis Reinhardt" wrote in message news:orHh9.167$UJ1.17889587 at newssvr14.news.prodigy.com... > > ... want to move this to my unix server. Unfortunately, no matter what I > > do I can not get apache on my linux box to execute any python scripts. I > > get the following errors in apache: > > Premature end of script headers: /var/www/html/cgi-bin/test.py > > What do you get when you type "test.py" at the shell prompt when logged into > the cgi directory on the RH box at the command line? Do you get: > --- > --- > Content-Type: text/html > --- > hello > > where "---" is taken as a blank line? I agree with Gerhard that the initial > print "\n\n" is wrong. But your comment trying the cgi.test suggests that > something else is going on. The above test may sniff out that something > else. > > > Dennis Reinhardt > > http://www.dair.com > > I do get the correct results. I also removed the blank lines and it still didnt' work. I have now moved the script to yet another machine and now it works. I must have Apache configured in such a way on the one machine that it is confused. It knows the .py are executible and such but does not execute them correctly. There is a problem with how apache is seeing the file and executing the program. I will have to review the httpd.conf file in both cases to try to figure it out. Thanks for the suggestion and pointing out my errors with the print statements. Josh From muk_pr at yahoo.com Wed Sep 11 18:50:24 2002 From: muk_pr at yahoo.com (vb) Date: 11 Sep 2002 15:50:24 -0700 Subject: Destructor never called ??? Message-ID: <76710511.0209111450.40999dd8@posting.google.com> Hi, I have the following code my problem is when I call any methods of TCVector_Object the destructor never executes. I mean v = module.CreateTCVector() del v; //destructor runs. message shown .OK but in v = module.CreateTCVector() v.Append(123); del v;//or closing python interpreter destructor never gets called. Any ideas? BTW are there any extending&embedding docs (except ASPN & Python docs) I realy have hard times in that ref. counting stuff and is my way the official way of adding methods to a new type ? Thanks. headers............. staticforward PyTypeObject TCVector_Type; staticforward PyMethodDef TCVector_methods[]; struct TCVector_Object{ PyObject_HEAD vector List; }; static PyObject* new_TCVector(PyObject* self, PyObject* args) { TCVector_Object *obj; if (!PyArg_ParseTuple(args,"")) return NULL; obj = PyObject_New(TCVector_Object, &TCVector_Type); return (PyObject*)obj; } static void delete_TCVector(PyObject* obj) { ShowMessage("Deallocating"); PyObject_Del(obj); } static PyObject * TCVector_getattr(PyObject *obj, char *name) { //Methods will be looked here. AnsiString attrname = name; if (attrname == "Count") { return Py_BuildValue("i",((TCVector_Object*)obj).size()); } else return Py_FindMethod(TCVector_methods, obj, name); } static PyObject * TCVector_Append(PyObject* self, PyObject* args) { int i; if (!PyArg_ParseTuple(args,"i",&i)) { return NULL; } ((TCVector_Object*)self).push_back(i); Py_INCREF(Py_None); return Py_None; } static PyObject * TCVector_Clear(PyObject* self, PyObject* args) { ((TCVector_Object*)self).clear(); Py_INCREF(Py_None); return Py_None; } static PyTypeObject TCVector_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, "TCVector", sizeof(TCVector_Object), 0, delete_TCVector, /*tp_dealloc*/ 0, /*tp_print*/ TCVector_getattr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ }; static PyMethodDef TCVector_methods[] = { {"Append", (PyCFunction)TCVector_Append, METH_VARARGS,""}, {"Clear", (PyCFunction)TCVector_Clear, METH_VARARGS,""}, {NULL, NULL, 0, NULL} /* sentinel */ }; static PyMethodDef samplemodule_methods[] = { {"CreateTCVector", new_TCVector, METH_VARARGS, "Create a new TCVector object."}, {NULL, NULL, 0, NULL} }; void __export __stdcall initsamplemodule() { Py_InitModule("samplemodule", borland_tools_methods); } From agenkin at cdf.toronto.edu Fri Sep 13 15:37:40 2002 From: agenkin at cdf.toronto.edu (Arcady Genkin) Date: Fri, 13 Sep 2002 19:37:40 GMT Subject: Generating Win95 (lanman) password hashes with Python Message-ID: I need to generate Win95 password hashes from a Python script. The PyCrypto module (http://www.amk.ca/python/writing/pycrypt/) provides DES class: http://www.amk.ca/python/writing/pycrypt/pycrypt.html#SECTION000400000000000000000 that might be able to do what I need. The hash that I need is the following: LAN Manager Password Hash This is a 32-bit hexadecimal sequence that represents the password Windows 95 and 98 clients will use. It is derived by encrypting the string KGS!@#$% with a 56-bit DES algorithm using the user's password (forced to 14 bytes and converted to capital letters) twice repeated as the key. If there is currently no password for this user, the first 11 characters of the hash will consist of the sequence NO PASSWORD followed by X characters for the remainder. Anyone can access the share with no password. On the other hand, if the password has been disabled, it will consist of 32 X characters. Samba will not grant access to a user without a password unless the null passwords option has been set. My first problem is that I don't understand how to get two 8-byte strings from the 14-character password. I'm guessing that the password is padded with something. The second problem is the "mode" parameter that I need to pass to the DES.new() function. Any idea what I might need? The dir() on DES gives the following available modes: 'MODE_CBC', 'MODE_CFB', 'MODE_CTR', 'MODE_ECB', 'MODE_OFB', 'MODE_PGP' Any help would be appreciated. -- Arcady Genkin : CDF sysadmin : http://cdf.toronto.edu/~agenkin/contact.html guilt is the cause of more disauders than history's most obscene marorders (E.E. Cummings) From pecora at anvil.nrl.navy.mil Sun Sep 29 09:05:02 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Sun, 29 Sep 2002 09:05:02 -0400 Subject: [Mac] Editor on Macintosh? References: <1fj7za2.1erbqps1uvzpj8N%news@agapow.net> Message-ID: <290920020905027300%pecora@anvil.nrl.navy.mil> >From the looks of it this is OS X only, right? -- Lou In article , Jonathan Hogg wrote: > I'm quite happy with BBEdit. > > > > One feature I'm growing particularly fond of is the new worksheet windows. > These are like MPW worksheets if you're familiar with MPW (Ah! thems were > the days). Basically you get an editor window that has a live shell > underneath it. By hitting the ENTER key instead of return, the last line > typed (or currently selected text) is executed and the stdout inserted at > the cursor point in the window. > > This isn't so useful for very interactive stuff and I wouldn't use it as a > substitute for a terminal window, but for recording and monitoring the > output of programs it's fantastic. Basically I open a new worksheet window > and type something like this at the top: > > cd /to/project/directory > ./start-program --non-interactive --with-lots-of-debugging-output > > Then I just select the lines, hit ENTER, and watch the output fill the > window. Then I can scroll up and down and use BBEdit's grep searching > facilities on the output as it's running. > > Yes, I'm sure Emacs can do all of this, but I don't want a terminal-based > editor pretending to be a GUI application. > > Oh, another thing. BBEdit has a command-line tool now for firing up the > editor allowing you to type: > > % bbedit foo.py bar.py > > and have them open up in BBEdit. > > Jonathan (no stock options, just a happy user) From claird at starbase.neosoft.com Thu Sep 5 14:49:49 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 5 Sep 2002 13:49:49 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 4) References: <448A0F008E0AFE11.19B9EF86BEE2B191.107D5020B234F743@lp.airnews.net> Message-ID: In article , Fernando =?ISO-8859-1?Q?P=E9rez?= wrote: >Fernando P?rez wrote: > >> James Kew wrote: >> >>> I can't persuade Google to find this message-id; any chance of a link? >> >> google_groups('comp.lang.python anansispaceworks.com')[0] > >Oops. Make that > >google_groups('comp.lang.python anansispaceworks.com scientific')[0] . . . Short form: look for Hancock at . And accept my apology for failing to resolve all the references properly before sending out the "Python-URL!". -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From Maric.MICHAUD at cirec.com Tue Sep 17 08:56:57 2002 From: Maric.MICHAUD at cirec.com (Maric MICHAUD) Date: Tue, 17 Sep 2002 14:56:57 +0200 Subject: PyQT License Message-ID: <27E327AB8201B54495D54105FBBBB1485D205A@SRVMSG.GERLAND2.local> I did not really understand terms of Qt and PyQt license. Is it GPL for both Win32/UNIX platforms ? From marklists at mceahern.com Fri Sep 27 18:17:18 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 27 Sep 2002 17:17:18 -0500 Subject: watching mutables? In-Reply-To: Message-ID: [I apologize for not providing context, but I've already deleted my copy of the specific message I'm replying to.] The reason a metaclass solution is not possible without modifying the original code has to do with how the metaclass is determined: http://www.python.org/2.2.1/descrintro.html#metaclasses 1. First, Python looks for '__metaclass__' within the class' dict. 2. Python uses the metaclass of any base class. 3. Python looks for a global __metaclass__. 4. Python uses the classic metaclass types.ClassType. With builtin lists and dicts, Python never gets past step 2, so you have to intervene forcefully with step 1 if you want to override the metaclass of a builtin class, which means you have to first subclass it: class WatchedDict(dict): __metaclass__ = Watched // m From claird at starbase.neosoft.com Wed Sep 18 08:34:38 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 18 Sep 2002 07:34:38 -0500 Subject: Facilities for accounting arithmetic (was: Python GUI app to impress the boss?) References: Message-ID: In article , terry wrote: > >>>?I'm willing to bet, though, that Python will be around for longer >>> than VBScript. > >Cameron, > >I don't like to disagree with an icon, but I think that you are missing >a deficiency in Python that will ultimatly limit it's usefullness in >the vast majority of the software that is written in the world. > >As long as Python refuses to admit that money is the focus of most of >the world's software, Python will be relagated to the same status as >FORTRAN, BASIC, and etc - except COBOL and VB. > >Is there any way to get the Python world to allow for the processing of >monetary applications without some hokey 60's constructs that involve >in-line conversions or anticipations of calculation characteristics? . . . If it helps, I have a soft spot for OS/400. I spent the early '80s writing BCD arithmetic packages in various assemblers. Terry, who needs disagreement more urgently than an icon? You and others have raised this point before. I haven't taken it as seriously as I should, just because I know that Microsoft and Sun (among others) are utterly unsympa- thetic to it. I need to ponder that ... anomaly (?) more. Thanks for making an issue of it. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From stephen.boulet at motorola.com Fri Sep 27 17:47:09 2002 From: stephen.boulet at motorola.com (Stephen Boulet) Date: Fri, 27 Sep 2002 16:47:09 -0500 Subject: Better terminal for windows? References: <3D94B037.2020202@motorola.com> Message-ID: <3D94D1DD.40407@motorola.com> Gerhard H?ring wrote: > * Stephen Boulet [2002-09-27 14:23 -0500]: > >>I'm using python 2.2.1 on winnt. >> >>If I want to run python interactively (and perhaps using ipython), is >>there something better than the "cmd" terminal? > > > Well, you could install MSYS from the mingw project, which is sort of a > Cygwin-lite :-) Thanks. I'll have a look at it. >>I'm used to bash on linux at home, but I'd like to avoid installing >>cigwin for now. Thanks. > > > cmd.exe isn't *that* bad once you activate tab completion in the > registry. Have you done that? Nope. How do you do that? I couldn't figure it out just looking through regedit. > > 4NT is also great, but it's shareware. > > -- Gerhard > I've come to the conclustion that the python shell in idle really isn't all that bad. Maybe I'll just stick with that. -- Stephen From jepler at unpythonic.net Wed Sep 11 22:40:13 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Wed, 11 Sep 2002 21:40:13 -0500 Subject: iterators and generators, is this the Python Way??? In-Reply-To: <3D7FF921.2040305@one.net> References: <3D7FF921.2040305@one.net> Message-ID: <20020911214013.A1795@unpythonic.net> On Wed, Sep 11, 2002 at 10:17:05PM -0400, Michael Schneider wrote: > Hello All. > > I just updated my python to 2.2 and noticed that generators, and > iterators were in there. > > I often parse through many files (one at a time), and wanted the speed > of read, and > the convience of for x in myGen: If this beats 'for line in open("myfile"): ...' by much, there's a problem .. can you post some benchmark numbers? Anyway, I don't think this can outperform the simpler for x in file.readlines(): ... since yours adds another layer of Python code in the middle... I think that files can be iterated over in 2.2, I only have 2.3 on hand: $ python2.3 -c 'import sys; print list(sys.stdin)' < /etc/resolv.conf ['search unpythonic.net\n', 'search localnet\n', 'nameserver 206.222.212.218\n'] f.xreadlines() or iter(f) should both operate in the same way, by using readlines with a size hint, then returning successive lines from the returned list, refilling the list as necessary. At the time, this benchmarked "just as fast as" slurping the whole file with a single readlines(), but with a reasonable memory footprint even for gigabyte files. (At least when none of the lines are insanely long) For benchmarks made at the time, start near http://mail.python.org/pipermail/python-dev/2001-January/011269.html Tim Peters quoted Neel Krishnaswami: | Quick performance summary of the current solutions: | | Slowest: for line in fileinput.input('foo'): # Time 100 | : while 1: line = file.readline() # Time 75 | : for line in LinesOf(open('foo')): # Time 25 | Fastest: for line in file.readlines(): # Time 10 | while 1: lines = file.readlines(hint) # Time 10 | for line in xreadlines(file): # Time 10 | | The difference in speed between the slowest and fastest is about | a factor of 10. Jeff From trash at terastat.com Tue Sep 17 13:23:57 2002 From: trash at terastat.com (bap) Date: Tue, 17 Sep 2002 17:23:57 GMT Subject: PIL v.1.1.3 and grabscreen Message-ID: I'd like to use the grabscreen function from Lundh's site (http://effbot.org/downloads) however it won't install or run (I use Python 2.2, it may be compiled for 2.1). The function is now included (according to the documentation) in PIL 1.1.3 -- but the PIL site only has binary versions of 1.1.2, for v1.1.3 the site refers to Lundh's site -- where again the installation routine doesn't work (asks for a directory but will accept no input). So -- does anyone know of any working sources of either grabscreen or a binary distributable for windows/activestate python 2.2 of PIL 1.1.3? From gerhard.haering at gmx.de Wed Sep 4 17:45:22 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 4 Sep 2002 21:45:22 GMT Subject: Database BSD on Mac? References: <3144be3c280c062e5e71a98ab191f664.98737@mygate.mailgate.org> <_7vd9.57894$ub2.928923@news1.tin.it> Message-ID: Max wrote in comp.lang.python: >> > I was looking on BSD but I'm not sure it is ported to all platforms. >> > Wich db should I utilize? >> >> Do you really need one? Or do either pickle or shelve suffice? > > I read shelve can be used for small amount of data... will it work with 5mb? Certainly. And probably for _lots_ of more data, if your problem fits an on-disk hashtable like shelve. -- Gerhard From peter at engcorp.com Thu Sep 19 19:40:37 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 19 Sep 2002 19:40:37 -0400 Subject: Minimal debug/rep functionality References: <3d894106@news.sentex.net> Message-ID: <3d8a606a@news.sentex.net> Mark wrote: > Peter Hansen wrote: > >>Sorry, I couldn't find a solution that was larger than six lines: >> >> >>> def trace(frame, event, arg): >>... if event == 'line': >>... print '%s: %s' % (frame.f_code.co_filename, frame.f_lineno) >>... return trace >>... >> >>> import sys >> >>> sys.settrace(trace) >> > > This is exactly what I needed. Now, can you explain to me how I hook in a > "local" trace function to take over once I execute the function I'm > interested in tracing? I'd like to use the "event" argument to take note > of calls that are 1 level deep (ie in my foo function, any calls made) and > turn off tracing of these until they return back to the level of foo. I guess you'd need a global to track the level, or implement the trace "method" as an object with a __call__ method so you can track state as well as receive the tracing calls. As for local tracing... the above function actually does that already. As the docs note, the global function (installed by sys.settrace) returns a reference to a local trace function when event is "call". I'm just using the same function for both purposes as a cheat. :) > I presume I could implement this with a "if event == 'call':" condition, but > I can't seem to get a global trace function to hook up to a local trace > function ... it does one or two things right, then goes crazy. Post sample code if you're having trouble... but I recommend playing a lot at the interactive prompt before doing so. You learn lots more that way. -Peter From jpm at papercut.org Mon Sep 30 15:04:24 2002 From: jpm at papercut.org (Joao Prado Maia) Date: Mon, 30 Sep 2002 15:04:24 -0400 (EDT) Subject: Question about __getattribute__/__getattr__ In-Reply-To: Message-ID: On Mon, 30 Sep 2002, Mark McEahern wrote: > > if cached_value == None: > > This is an aside, but comparison to None should be via identity rather than > equality; e.g., > > if x is None: > > or: > > if x is not None: > Yeah, I always forget that when switching from PHP to Python. Anyway, my main question was how to get the list of arguments passed to a method/function. Any ideas ? :) Cheers, Joao From jason at tishler.net Mon Sep 16 12:42:59 2002 From: jason at tishler.net (Jason Tishler) Date: Mon, 16 Sep 2002 12:42:59 -0400 Subject: Accessing Windows Registry under cygwin In-Reply-To: References: Message-ID: <20020916164259.GG424@tishler.net> Henry, Sorry for the sluggish response time, but I just returned from vacation...] On Mon, Sep 09, 2002 at 09:59:41PM +0100, Henry S. Thompson wrote: > On 11 September 2001 Norman Vine said "I have managed to get the > '_winreg' module working with Cygwin < _winreg = Python access to the > Windows Registry >" [1]. Assiduous searching does not reveal that > this work ever surfaced -- where might I find it? See the following: http://sourceforge.net/tracker/?group_id=5470&atid=305470&func=detail&aid=554807 Are you willing to help? Thanks, Jason From peter at engcorp.com Mon Sep 2 02:27:31 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Sep 2002 02:27:31 -0400 Subject: curses: AttributeError: initscr References: Message-ID: <3D7304D3.28D48684@engcorp.com> Gerhard H?ring wrote: > > * Cesar [2002-09-01 22:22 -0400]: > > in the same directory where my script live, there was an old file named > > curses.py. Then the instruction : "import curses" imported the bad one... > > You're not the first one to have this kind of problem. Too true. :) > A way to debug such problems is to start Python with the option "-v" or > even "-vv", which helps you track down where modules are really loaded > from. The first thing I generally do, since I'm inevitably testing something like this out at the interactive prompt, is to as for "module.__file__" and see where the file I'm importing is really coming from. I've been surprised on more than one occasion. -Peter From jpm at papercut.org Mon Sep 30 11:30:55 2002 From: jpm at papercut.org (Joao Prado Maia) Date: Mon, 30 Sep 2002 11:30:55 -0400 (EDT) Subject: Question about __getattribute__/__getattr__ Message-ID: Hi, I'm trying to do the following: class Real_Class: def real_method(self, name): return name class Cache: r = None def __init__(self): self.r = Real_Class() def __getattr__(self, attr): cached_value = self.get_cache(attr) if cached_value == None: # need to eventually save the returned value in the cache return getattr(self.r, attr) else: return cached_value def get_cache(self, attr): return None if __name__ == '__main__': t = Cache() print t.real_method('spam') Now, the code works correctly - it calls the appropriate method name with the argument 'name'. However, I would like to cache the return value of the method call for a specific match of method name / method arguments. That is, I would cache: t.real_method('spam') And: t.real_method('eggs') in two different cache files. It all comes down to the question: how do I know the full list of arguments passed to a function/method ? This way I'll be able to md5() the full string and have a different cache file for each method call. Any ideas ? Cheers, Joao From loewis at informatik.hu-berlin.de Wed Sep 4 05:03:10 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 04 Sep 2002 11:03:10 +0200 Subject: Why Python? References: Message-ID: Benjamin writes: > is it worth to go deeper into python? That depends on what you are trying to do. Python can help in doing lots of things, since it has good libraries for many application areas. If you want to discuss further, please tell us what kinds of things you want to do. You might just start using it, as well - take a small problem of yours that you always want to get solved, and see how easy it is to solve in Python. Don't hesitate to ask here if you have specific questions. Regards, Martin From DeepBleu at DeepBleu.org Sat Sep 21 10:48:56 2002 From: DeepBleu at DeepBleu.org (DeepBleu) Date: Sat, 21 Sep 2002 14:48:56 GMT Subject: pyrhon and oracle References: <5b8834c2.0209201412.50e77861@posting.google.com> Message-ID: "Lee Gray" wrote in message news:B__i9.505088$q53.17034835 at twister.austin.rr.com... > Satheesh Babu wrote: > > > cx_Oracle might be the *easiest* to use. I use DCOracle while working > > with Zope, but for standalone development, cx_Oracle is tops. > > > > Download the driver from > > http://www.computronix.com/utilities.shtml > > > > go to Python DB-API specs > > http://www.python.org/topics/database/DatabaseAPI-2.0.html > > > > Here's an example using DB-API > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 > > > > vsb > > http://vsbabu.org/ > > > > I'm just looking into Python, so these articles don't mean much to me yet... > Does all this mean that Python doesn't talk to an Oracle DB "out of the > box"? For Windows, can Python use ADO? > In all programming languages you have to add components/packages to do certain things. In the case of Python you have to add a package that allows you to use a database. There are many packages made for Python for this purpose. Also, Python can use ADO in Windows. Please search for Python and ADO in Google. There are articles that describe how to do that. From chris.gonnerman at newcenturycomputers.net Mon Sep 30 01:13:33 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 30 Sep 2002 00:13:33 -0500 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: <006701c26840$20e0e340$ba01010a@local> ----- Original Message ----- From: "Dennis Lee Bieber" > Chris Gonnerman fed this fish to the penguins on Sunday 29 September > 2002 03:33 pm: > > > > You ask how it is a different problem. Simple. A human, > > training in decimal math in grade school, knows that > > > > 1/3 = 0.3333333... > > > > and would *expect* it to round to 0.33 (still in two > > decimal > > So, in 2 decimal place arithmetic > > a = 1.00 / 3.00 > b = a * 3.00 > > gives > b = 0.99 > > which is NOT equal to 1... But this is okay because it's done > is "decimal arithmetic"? It's not "OK"... it's EXPECTED. > The telling phrase is "training in DECIMAL math"... > Most computers don't work in decimal math, so the > user /should/ be ready to learn the ins&outs of binary > floating point... Incorrect. The *user* expects the dang computer to produce the same results as for a manual calculation. In other words, truly serious businesspeople expect to be able to hand-check the numbers. The occasional (but far too common) binary float anomalies are unacceptable in that environment. > > For every example of "what is wrong with binary > floating point" someone else can find a similar case when > using decimal math. True, but the decimal anomalies are *expected* and the binary anomalies are *surprising*... I've been a programmer for a long time, working in everything from a scientific lab to a retail store. I still don't understand the ins and outs, as you put it, of binary floating point. > Even VB's "currency" type (which looks to be a scaled 64-bit > integer) carries 4 decimal places -- which allows for > "proper" results when displaying final results in two decimal > places with rounding. > > 1/3 => 0.3333 internally > 3*0.3333 => 0.9999 > 1.00 for display after rounding. I hate to give anything to Microsoft, but they seem to have a good, workable, not-often-surprising idea here. I still prefer the FixedPoint.py module's programmer-controlled scaling. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From python473 at yahoo.com Fri Sep 27 11:10:11 2002 From: python473 at yahoo.com (John Howard) Date: 27 Sep 2002 08:10:11 -0700 Subject: file open verification Message-ID: <9eabe547.0209270710.17ca112d@posting.google.com> Two questions - somewhat related: Situation - I have several files on an apache server that are being accessed by python programs that are receiving data from html forms. q1: How can the status of a file be checked? If two forms have been submitted and the data is being added to a common file, how do I know that data from both forms are being written correctly to the common file? q2: Related to above - really more of a cgi question - does the apache server keep all these file accesses separate some way? From sismex01 at hebmex.com Fri Sep 20 09:25:44 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 20 Sep 2002 08:25:44 -0500 Subject: strong/weak - dynamic/static [Was: Getting started] Message-ID: > > >So, you see, in C (a strong, static typed language) I obtained > >a char from a floating-point number; not the string representation, > >just the first byte. > > C is a statically typed language, but to call it "strongly" typed > is a bit of a stretch. C is at best, middle of the road in type > strength. > > C// > You are of course right; I ommited some (intended) quotes around the "strong" in "(a strong, static typed language), so it would reflect my true intention. :-) -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From never at mind.info Wed Sep 4 19:09:50 2002 From: never at mind.info (G. Willoughby) Date: Thu, 5 Sep 2002 00:09:50 +0100 Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> Message-ID: I would really like to know how to do this too, basically i want to print to a standard bubblejet print (non postscript) from a Tkinter Text widget, any ideas? --G. Willoughby From shalehperry at attbi.com Wed Sep 11 18:05:38 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 11 Sep 2002 15:05:38 -0700 Subject: problem with lists In-Reply-To: <20020911215423.GA30455@habana.easygolucky.de> References: <20020911215423.GA30455@habana.easygolucky.de> Message-ID: <200209111505.38492.shalehperry@attbi.com> On Wednesday 11 September 2002 14:54, Manuel Hendel wrote: > for line in lines: > line = string.strip(line)[1:-1] > fields = string.split(line, "|") > > domains = [] > > if not domains.index(fields[3:4]): > domains.append(fields[3:4]) > > print domains > > This brings the following error message: > :!./pop3create.py pop3data > > [No write since last change] > Traceback (most recent call last): > File "./pop3create.py", line 22, in ? > if domains.index(fields[3:4]): > ValueError: list.index(x): x not in list > > Can someone explain this to me? > > Thanks, > Manuel You want to use : if fields[3:4] not in domains: domains.append(fields[3:4]) .index() only works if the item is actually in the list. From gerhard.haering at gmx.de Fri Sep 6 03:48:36 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Fri, 6 Sep 2002 09:48:36 +0200 Subject: Timothy Rue In-Reply-To: <898662b7d85d2c966c0bd45d563d5d2d@xganon.com> References: <898662b7d85d2c966c0bd45d563d5d2d@xganon.com> Message-ID: <20020906074835.GB848@lilith.ghaering.test> * xganon [2002-09-06 02:31 -0500]: > Does Timothy Rue still Troll here? If not, how did you get rid of > him? Easy: gerhard at lilith:~/src/conf > grep -B2 threeseas News/score Score: =-9999 Expires: 2/20/2003 From: "Timothy Rue" grep threeseas .muttrc_scoring # "Timothy Rue" score '~f threeseas' =0 Good thing I have my personal config files in CVS, so I have these settings on all the computers/OSes I work on :) > We need him out of our group now, Are _you_ trying to troll now? -- Gerhard From member at dbforums.com Tue Sep 17 08:26:27 2002 From: member at dbforums.com (MPS) Date: Tue, 17 Sep 2002 12:26:27 +0000 Subject: Modify AD key fields programmatically via ADSI or VB Script Message-ID: <1824301.1032265587@dbforums.com> I am new to ADSI and was wondering if anybody knows a way to modify AD key fields (i.e./ DN) programmatically via ADSI or VB Script? Here is the exact scenario: We are attempting to synchronize the population in our new Active Directory deployment to the active individuals identified within our various database systems of record. To accomplish that, we generate the following ldap string describing the DN for every individual daily: TOM SMITH,ou=ACCOUNTING,ou=people,dc=biz,dc=url,dc=com along with values for numerous attributes. As noted above, the DN is comprised of the concatenate of FIRST NAME, MIDDLE NAME, and LAST NAME as well as that individual's PRIMARY DEPARTMENT (in this case ACCOUNTING). All of these are implemented into AD via a LDIF generated by a third party synchronization product (Simplesync). If any of these four elements (FIRST NAME, MIDDLE NAME, LAST NAME, DEPARTMENT) change (as they will from time to time), the result in AD is to add a "new" individual and "delete" to old. This is undesirable. Is there a way to programmatically detect that any of the above data elements are changing prior to executing the bulk synchronization and MODIFY the DN in AD in place or any other solution that will move this person to a different DN without losing the rest of their existing AD information. Thanks a million for any help - MPS -- Posted via http://dbforums.com From mhammond at skippinet.com.au Fri Sep 20 21:19:47 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 21 Sep 2002 01:19:47 GMT Subject: Python COM and variable number of arguments References: Message-ID: Greg Green wrote: > In this case I was using the makepy generated wrapper. I have > M. Hammonds book and used the method of ensuring I was using the > early-bound object. > > So am I out of luck even if I have the wrapper? You could also try passing with pythoncom.Missing or pythoncom.Emtpy in place of the positional arguments. You may need to experiment to see what one works - it depends on the COM object. Mark. From david.abrahams at rcn.com Sun Sep 15 11:20:59 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sun, 15 Sep 2002 11:20:59 -0400 Subject: Extending a C++ App References: <996eade8.0209120912.3a653d7@posting.google.com> <996eade8.0209122352.45721938@posting.google.com> Message-ID: "Gareth McCaughan" wrote in message news:slrnao96ee.52u.Gareth.McCaughan at g.local... > David Abrahams wrote: > > > > "Bwuce_Wee" wrote in message > > news:996eade8.0209122352.45721938 at posting.google.com... > > > > > I'm busy investigating Boost.Python... > > > > In that case, get Boost.Python v2 using the instructions at > > > > http://mail.python.org/pipermail/c++-sig/2002-May/001100.html > > > > It's nearing release, and v1 isn't long for this world. > > If you recommend new users to start with v2 rather than v1, > then it's already time for a (pre-)release, no? Almost. We're just working out the final administrative issues which will allow us to do that. -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From a-steinhoff at web.de Thu Sep 5 05:39:48 2002 From: a-steinhoff at web.de (Armin Steinhoff) Date: 5 Sep 2002 02:39:48 -0700 Subject: Installing Python 2.2.1 on WinNT References: Message-ID: "Phil Rittenhouse" wrote in message news:... > Hi all, > > I've run into a (actually two) problem installing Python 2.2.1 on Windows NT > 4.0. > At the end of the install, it throws up an error "Could not load the DLL > library $%#%^$. > The specified module could not be found." I have recently installed Python 2.2.1 on a NT 4.0 machine with SP6. The install process worked flawless. Is your dowloaded install file OK ?? - Armin From martin at v.loewis.de Tue Sep 17 02:05:35 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Sep 2002 08:05:35 +0200 Subject: Large file support and stat vs stat64 in extension modules References: Message-ID: Ben Escoto writes: > define_macros=[("_LARGEFILE_SOURCE", 1), ("_FILE_OFFSET_BITS", 64)] > > when declaring the ext_modules does something similar and seems to work. > > Again, this is a bit ad hoc, but seems to work, and I don't know of a > better way. If Python was configured for LFS, then those defines appear in pyconfig.h. So including Python.h before any system headers is the recommend, and better, way. Regards, Martin From DennisR at dair.com Wed Sep 18 13:00:06 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Wed, 18 Sep 2002 17:00:06 GMT Subject: Python comment stripper References: <16Nh9.248$Wc6.17087796@newssvr13.news.prodigy.com> <3d8807b1$1@news.sentex.net> Message-ID: > Makes sense. Let's see, what about a one-(logical)-liner (warning, > untested!): Alex, Thanks for the starter code. This will be a good Python learning program for me. However, I may defer implementing source comment extraction until after first release. > What are you using now for compression? I am using WinRar 3.0 (www.rarlab.com). As an exe inside a zip file, my hello example takes 402 Kb. The user must extract and run the EXE manually. As an EXE inside a self-extracting RAR format EXE, the same example is 361 Kb. The latter is smaller and easier for recipient. (ref: www.dair.com/pyhello.zip and www.dair.com/pyhello.exe). > Module gzip is probably a good idea to help you reduce size, too. At the time extraction is going on, it is impractical for Python to be doing the extraction -- there is the Python DLL (v2.0: 653 Kb and v2.2: 821 Kb) for starters. I am aiming for a small footprint. The 361 Kb download has Python22.dll inside and that DLL is used when the hello program runs. : Thanks, Dennis -- Dennis Reinhardt http://www.dair.com > From tjreedy at udel.edu Thu Sep 12 12:45:17 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 12 Sep 2002 16:45:17 GMT Subject: wrapping yield ? References: Message-ID: "Michael Sparks" wrote in message news:alqehl$9qv$1 at nntp0.reith.bbc.co.uk... > Hi, > > I'd like to be able to wrap "yield" in a function - is that > possible, and if not (my eading of stuff I've seen so far > says not) are there any plans to make it possible? > > Whilst it may seem odd, I'd like to be able to do this: > > def my_generator(arg): > dostuff.... > while(1): > waitForSomethingCheckingPeriodically() > processit You have to put in a yield x *somewhere* in order to yield anything to the caller. Hard to see why this is a problem. Something like x = wait.... yield process(x) TJR You are From amichail at cse.unsw.edu.au Thu Sep 12 02:51:23 2002 From: amichail at cse.unsw.edu.au (Amir Michail) Date: 11 Sep 2002 23:51:23 -0700 Subject: ignoring dtd file in sax parser Message-ID: <1010a26.0209112251.3efd57f4@posting.google.com> Hi, I'm trying to parse XML files that specify a dtd. However, I would like to ignore the dtd, and in fact, the dtd file is not even present. I tried: parser.setFeature(feature_namespaces, 0) parser.setFeature(feature_validation, 0) parser.setContentHandler(ph) try: parser.parse(f) # print "NO PARSE ERRORS" except xml.sax._exceptions.SAXParseException: print "XML parse errors in " + fn However, it still complains about not finding the dtd file. Amir From lbrannma at cablespeed.com Sun Sep 22 20:52:57 2002 From: lbrannma at cablespeed.com (Lance) Date: Sun, 22 Sep 2002 17:52:57 -0700 Subject: sys.ps2 assignment has no effect References: Message-ID: Thanks Alex.. it's with IDLE. That explains things. Lance "Alex Martelli" wrote in message news:FQqj9.149901$pX1.5369568 at news2.tin.it... > Lance wrote: > > > I'm running the latest Python on Windows XP. The default installed > > secondary string appears to be blank spaces rather than an ellipse. The > > following has no effect: > > > > import sys > > sys.ps2 = '... ' > > > > Any suggestions? > > Is this with the text-mode interactive Python (which would > surprise me, as I've run the latest Python on XP w/o such > problems), or with IDLE or other such IDE? IDLE does not > use PS2, afaik (it always uses spaces instead) and other IDEs > might do likewise. > > > Alex > From gerhard.haering at opus-gmbh.net Wed Sep 11 03:57:22 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 11 Sep 2002 07:57:22 GMT Subject: RELEASED email package version 2.3 References: Message-ID: Barry A. Warsaw wrote: > I've just released the (standalone) email package version 2.3. Is there any summary on changes, possible incompatibilities and deprecated features in comparison with the email package in Python 2.2 available? -- Gerhard From cliechti at gmx.net Tue Sep 17 15:15:03 2002 From: cliechti at gmx.net (Chris Liechti) Date: 17 Sep 2002 21:15:03 +0200 Subject: More on Protecting Source Code References: Message-ID: Kerim Borchaev wrote in news:mailman.1032260602.11981.python-list at python.org: > Hello David, > > Tuesday, September 17, 2002, 7:26:06 AM, you wrote: > > DL> I suppose one solution is to modify the Python interpreter with > different DL> op-codes and that ought to make it somewhat painful for > the average hacker. DL> A better solution is to make a .pyc file > approximately as hard as a binary DL> .exe file to decompile - however > that could be done. > > Just a thought. > Keeping your python modules encripted(e.g. with rotor module?) you can > reimplement __import__ builtin to properly handle importing these > modules. that sounds nice at first, but how would you code the custom import? if one has the readable code for that one using it to read the encrypted files is a no-issue. and if you decrypt it the plain text sources are in memory and a simple snapshot of the applications memory reveals the source. a simple way to semi obfuscate is to use the freeze tool which embedds the python bytecodes in a C array. as you also link against a python interpreter there are no version issues and distributing gets easy. if somebody wants to change the opcodes for this python interpreter - go on, that should be easy and the python decompilers won't work out of the box. if somebody believes that there should be better security there might be ways, but i think that you need expert knowledge in encryption, the OS it runs on, attack methods of crackers etc. to achieve a much higher level of security. probably too much effort just to eventualy loose... just distributing bytecode (forzen or not) should be save enough for most commercial purposes. i don't think that java is any more secure than python in this respect. chris -- Chris From anton at vredegoor.doge.nl Mon Sep 30 12:48:03 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Mon, 30 Sep 2002 18:48:03 +0200 Subject: watching mutables? References: Message-ID: On 30 Sep 2002 01:05:17 GMT, bokr at oz.net (Bengt Richter) wrote: I have slightly adjusted your code to result in the code below, this works if imported by Idle like this: Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> from watcher import Watcher >>> w = Watcher('m',locals()) >>> m = 1 "m" is bound to new object: 1 So this seems to be ok. However if the script below is executed itself, nothing happens. Also importing the module in another script and then executing a test script gives no output. The watch function isn't called at all. I guess the tracer has to know more about the other arguments in: def watch(self, frame, event, arg): Could this please be elucidated. Thanks for your insightful remarks and code. Anton. #watcher.py from sys import settrace, modules from marshal import dumps class Watcher: def __init__(self, name, namespace): self.name = name self.ns = namespace obj = namespace.get(name) self.objid = id(obj) self.objs = dumps(obj) settrace(self.watch) def watch(self, frame, event, arg): obj = self.ns.get(self.name) objid = id(obj) if objid != self.objid: self.objid = objid what = 'new' else: what = 'same but mutated' objs = dumps(obj) if self.objs != objs: print '"%s" is bound to %s object: %s' % (self.name, what, `obj`) self.objs = objs elif what == 'new': what = 'new but equivalent' print '"%s" is bound to %s object: %s' % (self.name, what, `obj`) return self.watch def finished(self): settrace(None) def test(): # huh ? w = Watcher('m', locals()) m = 1 if __name__=='__main__': test() From thorsten at thorstenkampe.de Mon Sep 23 17:03:21 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 23 Sep 2002 23:03:21 +0200 Subject: Three dumb questions (ordered by dumbness descending) Message-ID: Okay, here they are: 1. Why is 'zip(zip(x)) != x' (should be the same because it's the transposed) 2. Peter Norvig mentions in "Python for Lisp Programmers" some "don'ts": "[x] + y" and "x[1:]". Are there more things to avoid (especially in a loop)? 3. random.shuffle: the documentation says: "Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated." I translate this to "don't shuffle lists with more than 15 elements if you want a randomly ordered list". Alex Martelli says the same: "For example, Python users who are calling random.shuffle on a sequence of substantial length have a need for an underlying random generator with a *HUGE* period, as a necessary although not sufficient condition towards ensuring that all permutations of the shuffled sequence get generated with equal likelihood. Wichman-Hill has a period of less than 7,000 billions (7e12), insufficient to account even for the permutations of a sequence whose length is just 16 (16! > 2e13)." Otherwise in the "Python Cookbook" (Selecting Random Elements from a List Without Repetition) the shuffle version is called "the winner". So: can I use random.shuffle or do I have to write my own - slower - version to get a random list? Thorsten From sam at localhost.localdomain Wed Sep 11 19:05:22 2002 From: sam at localhost.localdomain (newbie) Date: Thu, 12 Sep 2002 00:05:22 +0100 Subject: I must be an idiot, please pity me! References: <3D801757.1020901@nospam.free.fr> Message-ID: On Thu, 12 Sep 2002 01:25:59 +0100, laotseu wrote: > Creating a db connection in each function for sure not be very > efficient.But what's wrong with passing the database connection to the > functions in mod1, mod2, and modXXX ??? That connection has to be passed to the other functions (where needed of course) in mod1. Say, mod1.functiona may use functions f1, f2 and f3. My gut feeling of having to pass that connection to all of these said "this can't be right". This is what I've done but it sure doesn't feel right! > Anyway, you can make it simpler, like this : Yay, now for the good stuff! > in each module, > - create a global db_connection variable - add an init() function, that > takes a db_connection as argument and assign it to the module's global > db_connection variable - and don't forget to call this function before > any other. Yes, I can follow that. Once I saw that "global" was more "local" I've never really considered using it. > Another, more OO way to do this would be to rewrite your modules as > classes, each getting a db_connection argument in it's __init__(), and > then, in the main script, create the needed objects. So the resulting object would be the same as what I return with now? > HTH > Laotseu Thank you. Sammy From shalehperry at attbi.com Tue Sep 24 11:15:15 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 24 Sep 2002 08:15:15 -0700 Subject: confused with lambda~ In-Reply-To: <20020924084839.30815.qmail@web21307.mail.yahoo.com> References: <20020924084839.30815.qmail@web21307.mail.yahoo.com> Message-ID: <200209240815.15208.shalehperry@attbi.com> On Tuesday 24 September 2002 01:48, black wrote: > that describe in reference documentation is too short, I couldnt even > understand what it trying to say. any explanation please ? > lambda is way to define a function without giving it a name. lambda x,y: x + y defines a function which takes two parameters -- x and y -- and returns their sum. do_sum = lambda x,y: x + y do_sum(2,3) yields 5. As you can see we store the function as do_sum. So let's take this a step further. numbers = range(1,21) # numbers 1 - 20 sum = reduce(lambda x,y: x + y, numbers) sum will be the sum of all numbers 1 - 20. This is equivalent to the following code: sum = 0 for n in numbers: sum = sum + do_sum(sum, n) The idea is lambda let's you write little one off functions when you need them rather than have to define one somewhere and likely only use it once. In a lambda on expressions are valid so no assignment or print calls can happen. If you need that you must define a function. Hope this helps. From gerhard.haering at gmx.de Tue Sep 10 18:33:31 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 10 Sep 2002 22:33:31 GMT Subject: test (ignore) References: <3d7e2957$1_2@nopics.sjc> Message-ID: Adonis wrote in comp.lang.python: > just a test, please ignore. What exactly is wrong with alt.test or one of the other .test groups? -- Gerhard From david.abrahams at rcn.com Fri Sep 27 19:08:20 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Fri, 27 Sep 2002 19:08:20 -0400 Subject: Problem w/ boost_python_debug.dll References: Message-ID: [Boost.Python questions should go to the C++-sig (http://www.python.org/sigs/c++-sig/); I seldom watch this list carefully.] This is a limitation of our build system (sorry, we're working on it). boost_python_pydebug.lib is really built as boost_python.lib, then copied/renamed, a strategy that doesn't work out well. You have several options: 1. rename the debug products back to boost_python.lib/.dll, and link with that. Keep debug and release versions in separate directories. Keep your PATH straight so that the wrong one is never loaded by mistake 2. Use Boost.Build to build your project. It always keeps the debug/release/debug-python versions in separate directories, and automatically points at the right one (which is why this doesn't cause me all kinds of pain every day). 3. Temporarily edit libs/python/build/Jamfile to change the name of the library target from boost_python to boost_python_pydebug. Rebuild everything. There will be a properly-named-and-functioning debug library in the bin/ directory tree. Grab it and away you go. Sorry for the inconvenience. I'm going to try to get distutils going for v2; that should make some of these things easier. HTH, Dave -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com "Richard" wrote in message news:cb95025b.0209142123.82c016e at posting.google.com... > I'm using Boost.Python (v1) to embed & extend a C++ application. I've > downloaded ActiveState's distribution and built the debug python > library and DLL. > > I built the release and python-debug versions of Boost.Python as is > documented. I also define BOOST_DEBUG_PYTHON in my C++ files since I > have the debug python libraries. > > Enough with the background, let's get to the problem. For debug > builds, I link with boost_python_pydebug.lib. But when I run the > program, it still tries to load up boost_python.dll, NOT the debug > version! The only way I know to fix the problem is to rename > boost_python_pydebug.dll so that it is loaded instead. > > Does anyone know a better fix? Any help would be appreciated. > > Thanks. From gua81 at XXXyahoo.com Thu Sep 26 03:48:37 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Thu, 26 Sep 2002 17:48:37 +1000 Subject: Getting last char in string. Message-ID: Hi, im writing a simple method that takes in a string input and check if the last charcter is an '/' then it will do A else do B my Q now is how to get the last char??? Thanks From mnations at airmail.net Thu Sep 12 11:22:07 2002 From: mnations at airmail.net (Marc) Date: 12 Sep 2002 08:22:07 -0700 Subject: Reading all text in telnet connection Message-ID: <4378fa6f.0209120722.227fe930@posting.google.com> Hi: Having a small problem trying to capture all the text in a telnet connection. I've used all the options of eager, lazy, etc., and can't seem to find the right combo. What I'm doing is intermittently writing data and then reading all of the response. Unfortunately, all of the response might not immediately appear. I started off using read_until, but there's nothing really consistent that I can read to. So I need the ability to simply read everything current in the buffer until EOF. What is the best way to accomplish this? Thanks, Marc From gerhard.haering at gmx.de Sat Sep 14 06:30:08 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 14 Sep 2002 10:30:08 GMT Subject: Skipping Parts of a For Loop References: Message-ID: Thomas Guettler wrote in comp.lang.python: > Is there a way to skip some parts in a for loop? > [...] > Is there a way to skip some parts? > > "continue" skips one element. "continue" skips the rest of the for loop. > But how can I skip several? With "continue" :-) -- Gerhard From aleax at aleax.it Tue Sep 24 08:42:47 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 12:42:47 GMT Subject: Dynamic loading of modules References: <87sn00zeke.fsf@pokey.henrik-motakef.de> Message-ID: Johan Fredrik ?hman wrote: > I tried this below. But as you see, even if the Password.py has a "def > init()" it doesn't work. > > Python 2.2 (#1, Mar 26 2002, 15:46:04) > [GCC 2.95.3 20010315 (SuSE)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> z = __import__("plugins.Password") >>>> z.init() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'init' __import__ returns the TOP-LEVEL module in the package even when you import a dotted name. SO, you need: x = __import__('plugins.Password') x = getattr(x, 'Password') and now you should have the effect you want. x = x.Password would be OK too instead of the getattr call, of course, but the latter has the advantage that you can use a variable to hold the attribute (submodule) name:-). Alex From aahz at pythoncraft.com Wed Sep 18 16:29:43 2002 From: aahz at pythoncraft.com (Aahz) Date: 18 Sep 2002 16:29:43 -0400 Subject: Remarks to Python 2.3 References: <20020918222421.328088eb.use-net@schabi.de> Message-ID: Normally, I tell people posting to python-dev that they're in the wrong place and should go to c.l.py. However, this time, I think the reverse suggestion is in order: you should post your questions to python-dev. In article <20020918222421.328088eb.use-net at schabi.de>, Markus Schaber wrote: > >I studied http://python.org/dev/doc/devel/whatsnew/contents.html and was >very impressed - you manage to get python even more fascinating with >every release. > >I especially like enumerate() and Bool. > >But I have some remarks: > >- Mutable sets support some in-place operations - should those, just as >the in place operations on lists, like sort(), return None instead of >the new list to make clear that they are in place operations and for the >sake of consistency? > >- When replacing list elements using the extended slice syntax - e. G. >in a[::2] = range(0, -2, -1) - the left side must have exactly the same >numer of elements as the right side. So, to cite the example, a[::2] = >range(3) is illegal for a=[0, 1, -1, 3]. > >Now I could image that it makes sense to allow one single additional >element to be added to the list in case only the step is specified and >the operation doesn't produce a gap. So the given example above would be >valid, giving a sequence of five elements, whereas with a=[0, 1, 2] it >would stay illegal (as it would produce a gap). a[0:3:2]=range(3) would >stay illegal as it explicitly specifies the length of the range, >a[0:3:5]=range(3) could be allowed. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From greek_bill at yahoo.com Tue Sep 17 16:12:37 2002 From: greek_bill at yahoo.com (Morfeas) Date: Tue, 17 Sep 2002 21:12:37 +0100 Subject: Instantiating and initialising C++ with embedded Python Message-ID: Hello, I'm developing a game in C++ and I've come to a point where I think I need to use a scripting languge (and why not python?!). I have a nice C++ class hierarchy that does all sorts of things. I need to be able to create (i.e. instantiate) and initialise a bunch of objects at run time. For example I need to do the following (in pseudo-code) : if (car jumps over obstacle) { award points to player; } I could hard-code this with C++, but I'd like the flexibility of doing this only for cerain game levels, etc. Since I've only started reading on Python, can you please tell me if the following is right : 1. My main program is in C++, so I need to embed the python interpreter. 2. I need to allow python access to my C++ classes, therefore I need to extend the embedded interpreter. I think I'm ok with doing (1), but not so sure about (2). I've been reading the python documentation, but they seem to focus on C rather than C++. I believe I need to write some python-friendly class definitions, etc. Can someone give me some of the following : a) a brief description of the whole process b) some code examples c) suggestions about useful tools Thanks, Morfeas -- www.freecfm.com/m/morfeas From vze3m6zd at verizon.net Sun Sep 8 13:33:02 2002 From: vze3m6zd at verizon.net (dioscoro) Date: Sun, 08 Sep 2002 17:33:02 GMT Subject: Why Python? References: Message-ID: <3D7B8AC2.2040008@verizon.net> > Also, I started recently to learn PHP. I wouldn't recommend it for a > newbie at programming, unless he/she needs it. you not recommend beacuse php is is more dificult? are you? you must mean it lacks the the power of c++ or python. From fafhrd at datacom.kz Fri Sep 6 01:02:30 2002 From: fafhrd at datacom.kz (Nikolay Kim) Date: 06 Sep 2002 12:02:30 +0700 Subject: tuple problem In-Reply-To: <1031287998.6307.44.camel@fafhrd> References: <1031287998.6307.44.camel@fafhrd> Message-ID: <1031288576.6308.49.camel@fafhrd> sorry! it's my error From mikeb at mitre.org Tue Sep 3 16:00:16 2002 From: mikeb at mitre.org (Mike Brenner) Date: Tue, 03 Sep 2002 16:00:16 -0400 Subject: [Q] win32com/Excel Message-ID: <3D7514D0.902AA220@mitre.org> Hi Robin, That was great, but most importantly, it was FAST! Would it be possible to tell how you did that so quickly? Is there a reference that would tell me that x1LastCell is in constants? or that you put the activeWindow in front of ActiveCell? Do you know of any references as to how to do it in Microsoft Project whose object model seems much less documented than Excel's is? I know how to use Project Explorer in the Visual Basic Editor inside the Microsoft OLE applications like Microsoft Project, and I know how to get the Python list of objects using makepy. However, that does not seem to be enough to figure out many questions in Microsoft Project (and even some questions in Microsoft Excel). What would be really nice is a document that explains what each object in the list is used for. For example, when opening a Microsoft Project file, it asks a bunch of questions like: are macros okay? should I open related files? should I save the changes I think you made to the previous file? I would like to learn how to cancel out those messages when I open a Microsoft Project file from Python. What book or application do you recommend I purchase? Or what file can I download to learn how to do these things? Thanks, Mike >I would like to emulate this Visual Basic statement from Python, using >Com: > > Range(Range("A1"), ActiveCell.SpecialCells(xlLastCell)).Select > >this statement selects the active worksheet (which is, incidentally, >not similar to UsedRange). > >any clues? > >thank you, from win32com.client import Dispatch from win32com.client import constants xl = Dispatch("Excel.Application") AB = xl.ActiveWorkbook AS = AB.ActiveSheet AW = xl.ActiveWindow R = AS.Range('A1',AW.ActiveCell.SpecialCells(constants.xlLastCell)) print AB.Name, AS.Name, R -- Robin Becker From Chris.Barker at noaa.gov Wed Sep 18 13:01:01 2002 From: Chris.Barker at noaa.gov (ChrisBarker) Date: Wed, 18 Sep 2002 10:01:01 -0700 Subject: Python GUI app to impress the boss? References: Message-ID: terry wrote: > Contrast that > with the following VB code: Amount = Qty * UnitPrice > The amount of validation rises exponentially > when the calculations in a program are implementation specific, as > opposed to language intrinsics. Each calculation must be tested at the > limits of each of the variables involved - at each instance. Well, sure. This is obviously a stupid way to go about...That's what object oriented programming is all about. What you need to do is create a currency class that behaves like it should, and then use it everywhere you want currency. Then you can do: Amount = Qty * UnitPrice just like VB. > The quick reply to your observation is: Yes, anything is possible - > but is forcing a language into an environment to which it is not > intrinsicly suited a reasonable approach? This is not an issue of suitability of Python. > I think Python needs to incorporate an intrinsic data type that > monetary Yes, it would be4 very useful to have that data type, but it really doesn't make any difference whether it is intrinsic or not. > and shouldn't be accomplished with overlays on integer or > character variable types. Why not? what do you think VB is doing? All machines that VB runs on use binary integer and floating point arithmetic..so a currency data type HAS to be based on those. It's just a question of whether you write the "overlays" in Python, C, assembly, or whatever. And you are free to extend Python in those languages if you like. The only reason I can see to not writing your class in Python is performance, and unless you are doing a lot of calculations, that is probably a non-issue. If someone writes a nice one, maybe it could even be put intot he standard library. > Python needs this data type, that is not > hardware oriented, to become truly mainstream and be a threat to VB. Python needs the equivalent of the MS marketing machine to be a "threat" to VB. > I say this with all due respect to all the other positive attributes of > Python and it's flexibility to solve a myriad of other non-business > application problems. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From jb at cascade-sys.com Fri Sep 6 21:01:59 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 06 Sep 2002 18:01:59 -0700 Subject: Larry Wall's comment on python... References: Message-ID: <3D795007.5000700@cascade-sys.com> Rod Stephenson wrote: >Larry Wall Wrote: > >"Python is cool to look at small bits of, but I think the "outline" >syntax breaks down with larger chunks of code. I'm with Aristotle on >the structure of discourse--a story should have a beginning, and >middle, and an end. So should blocks" > >Any comments? > Typically, he substitutes a cute particle of rhetoric for a meaningful response. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From tim.one at comcast.net Sun Sep 29 17:56:50 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 29 Sep 2002 17:56:50 -0400 Subject: Python's import: why doesn't it work? In-Reply-To: <3d976fbc$0$23666$91cee783@newsreader02.highway.telekom.at> Message-ID: [ Jurie Horneman] > Actually, I just tried this in a DOS shell under Windows 98: > > python -v script.py >output.txt > > It lists the verbose output straight to the DOS shell, not to > output.txt. The output is useless, I can't scroll back. > > Oddly, > > python -h >output.txt > > correctly sends the output to output.txt. > > Does anybody know if this is a bug, Arguably so, but it's a command.com (the Win9x shell) limitation. Your first example printed to stdout, your second to stderr, and command.com simply doesn't allow redirecting stderr, or setting the DOS box history to a usable value. cmd.exe (the WinNT/2K/XP shell) does both. > and how I can work around it? Programming life under command.com is impossible without tcap: http://www.simtel.net/pub/pd/11141.html It's free, tiny, and works great. It's the only Win9x "console capturing" utility I've tried that actually works, and doesn't cause system instability. From thorsten at thorstenkampe.de Mon Sep 9 20:14:35 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 10 Sep 2002 02:14:35 +0200 Subject: Python primer - comments appreciated! Message-ID: "Python, anyone?"... Yep, this is my first one. Comments on style/readability and technique/flow appreciated! #v+ def quotient_set(seq, func, partition='nonbool'): """ partition into equivalence classes With the 'bool' parameter 'quotient_set' always returns two lists: the first containing the 'true' items and the second containing the false ones. """ if partition == 'bool': # Yes, I know about 'filter', but this returns just the 'true # elements'... # put this in one line? true_class = [] false_class = [] for item in seq: if func(item): true_class.append(item) else: false_class.append(item) return [true_class, false_class] else: # put this in one line? quotient_set = [] representative_class = [] for item in seq: representative = func(item) # "Try: seq.index(item)" is IMO rather ugly in a loop. But # it's even better than "if item in seq: seq.index(item)", # which goes twice through seq try: quotient_set_index = representative_class.index(representative) except ValueError: quotient_set.append([item]) representative_class.append(representative) else: # This somehow "inelegant", because all I want to do is: # "seq[index] = seq[index].append(item)" Suggestions? equivalence_class = quotient_set[quotient_set_index] equivalence_class.append(item) quotient_set[quotient_set_index] = equivalence_class return quotient_set #v- To get a feeling for what 'quotient_set' does, try: >>> f = lambda x: x % 3 >>> quotient_set([1, 2, 3, 4, 5, 6, 7, 8, 9], f) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] >>> quotient_set([1, 2, 3, 4, 5, 6, 7, 8, 9], f, 'bool') [[1, 2, 4, 5, 7, 8], [3, 6, 9]] #v+ def set(seq): """ make a true set by removing duplicates """ # Shortest way to do a 'null function'? 'None' doesn't work... f = lambda x: x # identity function return [item[0] for item in quotient_set(seq, f)] #v- From donn at u.washington.edu Tue Sep 3 12:37:57 2002 From: donn at u.washington.edu (Donn Cave) Date: 3 Sep 2002 16:37:57 GMT Subject: Synchronous capture of stdout and stderr References: Message-ID: Quoth Konrad Wojas : | Neil Hodgson wrote: | > Konrad Wojas wrote: | > | >> I'm working on a build tool that captures the stdout and stderr of an | >> application and mails the output if a compile fails. I'm now using | >> popen2.popen3 and the select module, but I don't receive the two streams | >> in the same order as the application sends them. | > | > A common problem here is that the application buffers the streams | > when writing to a pipe but not when writing to a terminal. Using a pty | > instead may convince the child application to run unbuffered. Is there a | > flag (like Python's -u) to run the application in unbuffered mode? | | No, the applications are make and gcc :) | | I guess I'll have to use popen4 and don't distinguish between stdout and | stderr. Maybe I could try writing a LD_PRELOAD wrapper some time. I wouldn't expect make and gcc to buffer output like that. Personally, a single output stream sounds better to me anyway in this case, because I don't recognize any great semantic distinction between standard and error outputs in a make job. But in answer to your immediate question, I would suggest two things - use the UNIX file descriptor, file.fileno(), and the posix module read and write functions, to avoid unwanted buffering, and secondly, use the select.select() function to find output that's ready to read. Donn Cave, donn at u.washington.edu From jeske at chat.net Sun Sep 15 02:26:08 2002 From: jeske at chat.net (David Jeske) Date: Sat, 14 Sep 2002 23:26:08 -0700 Subject: html template system? In-Reply-To: References: Message-ID: <20020914232608.B20812@mozart.chat.net> There is am extremely fast template system called Clearsilver which has some similarities to Cheetah (Python) or Velocity (Java), except that it's a C-library and very language neutral. A Python binding is available: http://www.clearsilver.net/ On Fri, Sep 13, 2002 at 11:24:55PM +0000, :B nerdy wrote: > what are good templating systems avaliable for python? > > ive been at http://zebra.sourceforge.org and the documentation is kinda sus. > zope DocumentTemplate is included with zope. but i want a smaller footprint > system. > > what are my options? cheers > > > -- > http://mail.python.org/mailman/listinfo/python-list -- David Jeske (N9LCA) + http://www.chat.net/~jeske/ + jeske at chat.net From jb at cascade-sys.com Mon Sep 9 20:38:52 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Mon, 09 Sep 2002 17:38:52 -0700 Subject: a re question References: Message-ID: <3D7D3F1C.8000804@cascade-sys.com> Rajarshi Guha wrote: >Hi, > I have a file with lines of the format: > >001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23 >001 Xya FGh 143557789 7 100 09/05/2002 20:23:23 > >I am trying to extract the 9 digit field and the single digit field >immediatley after that. > Regex is great but on the surface it appears to be overkill for your application. I would like to suggest some alternatives not using regex. (A) IF all the fields are fixed width (up to and including the fields of interest, but not necessarily the ones following) then you can extract sub fields by simple indexing into the string. E.g., assuming a single space or TAB for a separator and that variable 'line' contains one of the above data lines, then something like line[14:23] would extract the larger numeric field. (I may have counted wrong -- you may have to debug that fragment before using it.) (B) If the fields are variable width (as your regex suggests) BUT always separated by spaces or tabs, you can simply split the line into fields: fields = line.split() and then, fields[4] and fields[5] would contain the nonwhite space contents of your desired numeric fields. The split function (in the string module) takes an optional argument to specify separators (e.g., commas) other than whitespace. I expect these alternatives would be faster than regex, though I have not measured to make sure. If I'm mistaken and the fields are all run together, without whitespace separators, then you're stuck with regex. However, then your existing expressions likely need more work to work right in that case. "There's more than one way to do it!" Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From BPettersen at NAREX.com Fri Sep 13 15:29:14 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Fri, 13 Sep 2002 13:29:14 -0600 Subject: Embed extended Python Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192012532DC@admin56.narex.com> > From: Mathieu Tremblay [mailto:mtremblay at golemlabs.com] > > Hello, > I am quite new to Python and I'd like to embed extended python. > The problem is that the documentation I can find on the > internet is always related to C standard types and not to C++ objects. [snip] It isn't clear to me exactly what you're having problems with so I'll just give you the general overview of what you need to do... First you need to initialize Python and your extension modules. In this case I'm using SIP to wrap C++ (hence the call to initlibsip), and my wrapped module is libnrxc.dll). PyInitializer::PyInitializer() { // Initialize Python Py_Initialize(); // initialize SIP (the wrapper generator) library initlibsip(); // initialize the Narex library initlibnrxc(); PyObject* mainmod = PyImport_AddModule("__main__"); m_namespace = PyModule_GetDict(mainmod); Py_INCREF(m_namespace); // make sure the nrx module is loaded try { PyObject* m_result = PyRun_String( "import nrx\n", // has to end in \n Py_file_input, m_namespace, m_namespace); if (m_result == NULL) { // getTraceback() returns the traceback as a std::string. throw new NException(getTraceback().c_str(), N_EX_NULL); } else { Py_DECREF(m_result); } } catch(NException *e) { std::cout << e->getMessageText(); } } After all that you should be able to call into your C++ module: PyObject* res = PyRun_String("nrx.CWheel()", Py_eval_input, m_namespace, m_namespace); res is now your C++ instance wrapped in a PyObject. To get back the C++ object, you'll have to call a function from your wrapping library that will do that for you, e.g. for SIP: int error; CWheel = (CWheel*)sipConvertToCpp(res, sipClass_CWheel, &error); I haven't used swig in a while, so I don't know what the swig call is, but you get the idea... When you want to go the other way (have c++ object, need PyObject), there is a similar call: PyObject* val = sipMapCppToSelf(&myWheel, sipClass_CWheel); hth, -- bjorn From mstenner at phy.duke.edu Thu Sep 26 10:41:28 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Thu, 26 Sep 2002 10:41:28 -0400 Subject: off topic -- spam assassin In-Reply-To: <200209261407.g8QE76Wo028975@ratthing-b246.strakt.com>; from lac@strakt.com on Thu, Sep 26, 2002 at 04:07:06PM +0200 References: <200209261407.g8QE76Wo028975@ratthing-b246.strakt.com> Message-ID: <20020926104128.A12812@phy.duke.edu> On Thu, Sep 26, 2002 at 04:07:06PM +0200, Laura Creighton wrote: > On the advice of several of you here, I installed spam assassin, and > had a pleasant six months of nearly spam free mail. Thank you, each > and every one of you who recommmended it. Alas, the spammers have > got smarter, and I am now getting 25+ pieces of spam that aren't > caught by spam assassin every day again. :-( What's new for our > side of the arms race? Have you upgraded to the most recent version of spamassassin. My observations are similar to yours, but staying on the current version of SA works nicely for me. (although I don't get as much spam as you, and maybe your spammers are smarter than mine) I think the SA heyday is over. Once it left obscurity, I think the spammers started using it to tailor their messages. This is an inevitability and only means that we'll need to stay on top of the most recent version. -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From michaels at one.net Fri Sep 20 08:07:34 2002 From: michaels at one.net (Michael Schneider) Date: Fri, 20 Sep 2002 08:07:34 -0400 Subject: Python sequences reference - problem? References: Message-ID: <3D8B0F86.9000600@one.net> I also like python. When doing pure math I have been using J for prototyping algorithms. J is basically APL without the special symbols . Good paper with many links for APL and J: ftp://watserv1.uwaterloo.ca/languages/apl/software-library/index.html http://www.jsoftware.com/ These are expecially good for heavy linear algerbra, Have fun, Mike Alex Martelli wrote: >Michal Kaukic wrote: > >>Hi, >> >> we like Python - I use it (with Numeric and SciPy modules) >>for teaching of Numerical analysis and my colleague is doing >>some research in discrete optimization in Python. And he often >>surprises me with non-conformal use of language :-) >> >> We are mathematicians, not programmers. I suppose, he believes >>that Python "thinks" like Mathematician. Yesterday, he was struggling >> > >I think the concept of "MODIFYING an object" is pretty far from >most areas of maths I've dabbled in (I'm an engineer, not a >mathematician, but do find maths fascinating). It seems to me >that the only real way to get a language that WILL "think like >a mathematician" is to take your pick among languages that have >no concept of "modifying an object" - which nowadays basically >means, Functional Programming languages. Personally I find >Haskell the most elegant one -- clean syntax (uses whitespace >much like Python), clean semantics (lazy evaluation the default >everywhere). Last I checked, the best Haskell compilers were >able to produce very decent code for many problems -- performance >will in most cases be better than Python's. If you want even >MORE performance, I suspect some less-puritanical but still FP >language (such as O'Caml) can probably deliver it. > >If for some reason you don't want to get into FP, then I think >you can forget everything about "thinking like a mathematician". >If data modification IS allowed, then your chosen language needs >to choose either of two possibilities: > >-- COPY-semantics: an assignment such as > x = y > inherently copies y, so that any future change to y has no > more effect on x > >-- REFERENCE-semantics: an assignment such as > x = y > makes x a synonym of y, so that both refer to the same > object: any future change to that object affects any > synonym for the object equally > >Many languages choose a MIX of these two kinds of behavior, >but that's the worst of both worlds, as it complicates things >a lot. Generally, OLD languages (such as Fortran) relied on >copy semantics (references or synonyms were not considered, >and when they could happen, as in argument-passing, they were >prohibited by the language rules, although those rules were >rarely enforced). Modern languages by and large have moved >to reference semantics, which is generally much cleaner even >though in some cases performance can suffer (optimization is >the main reason some languages complicate things by mixing >reference and copy semantics). "Generally" is important: LISP, >one of the oldest languages around (second-oldest after >Fortran, among those still widely used today), relied on >reference semantics from the start. The resulting elegance >has much to do with Lisp's acceptance in the mathematical >community, IMHO. > >Python uses reference semantics. When you want a copy, you >ask for a copy -- it's as simple as this. If you don't ask >for a copy, you don't get a copy... you get a reference to >the original. There is no complication: it's _always_ this >way. (OK, OK, at the margin there are doubtful cases: in >particular, a SLICE is a copy-request for all built-in types, >but a reference, sharing data with the original array, when >you use the Numeric package... Numeric had to move _away_ >from copy and onto reference in this case to avoid accidental >copies of huge array slices... take this as the exception >that proves the rule, OK?-). > >Python does have some data types that are immutable, which >helps move it a little bit closer to FP -- numbers, strings >and tuples are immutable. (Even Java has strings as >immutables -- SOME of FP's niceties do start to move into >the mainstream, albeit slowly:-). But the main style is still >very much NOT FP, rather relying on modifiable data. > >>with the code shown below (somewhat simplified): >> >> >>L_L=[[1,2,3], [2,3,4], [3,4,5]] >> >>def do_process(LL): >> n=len(LL[0]) >> rec = [0]*n >> Res=[] >> >> for row in LL: >> rec[0] = row[0] >> # further code - modifying rec >> # lots of conditional processing and such... >> # ... >> Res += [rec] >> >> return Res >> >>--------------------------------------------- >> >>After calling do_process(L_L), the "expected" result should be >> >> [[1, 0, 0], [2, 0, 0], [3, 0, 0]] >> >>but the true result is >> >> [[3, 0, 0], [3, 0, 0], [3, 0, 0]]. >> >> >> Yes, this is fully in accordance with how the Python language should >>behave: >> Res += [rec] inserts references to list object rec, >> which are further modified... (he should use copy(rec) instead). >> > >Right in all respects, yes. > > > >> But there is nothing to make this behaviour clearly VISIBLE in code. >> > >*EVERY* assignment in Python uses reference semantics. Every occurrence >of an assignment, therefore, makes reference behavior "clearly VISIBLE". > >Presumably fish don't find water "clearly VISIBLE", being used to that, >much as it is for us and air. When something "is *EVERYWHERE*", how >can it be "clearly VISIBLE" at the same time?-) > > >>If I work with pointers in C/C++ I know and see they are pointers. >> > >That's because C uses copy semantics, and uses pointer to emulate >reference semantics when needed. That's just the reverse of Python, >which uses reference semantics, and explicit calls to copy to >emulate copy semantics when needed. > >C++ lets you define "references" which IMPLY reference semantics >rather than copy semantics -- and you don't SEE what they are at >the point of use (only at the point of definition). Flaming about >that here, one way or another, won't be very useful:-). But there >are LOTS of precedents: Pascal (!!!) lets you declare arguments >to a procedure as either reference or copy -- then you don't see >the difference at the point of use; Visual Basic emulated that, too >(the default has changed in recent releases of VB, but that's >-another- flame:-); languages with sophisticated macro systems, >such as Dylan or relatively-recent LISPs, let you do all that and >worse. > >But C and Python are SIMPLE languages: one semantics is pervasive >(reference for Python, copy for C), you take explicit measures >when you want the OTHER semantics, and those measures are visible >at the point of use (well, _mostly_ -- C does complicate things >a bit by having arrays "decay to" pointers, Python has the >"slice aren't copies in Numeric" issue -- but that's definitely >at the margin). > >>You can say - we also know that rec is list object and so be careful >>with it. Yes, but consider the complex code where the similar constructs >>are very easy to overlook. And debugging of such code can be frustrating. >> > >The issue has nothing to do with rec being a list object, really. >You may see the issue as having to do with the fact that rec is >(any kind of) *MUTABLE* -- indeed, a language without mutable data >DOES shield you from these issues. If you tried to mutate non- >mutable data, as rec[0] = .... does, you'd get an exception at >runtime (if every kind data was immutable, of course, the language >wouldn't even have any CONSTRUCTS to express mutation). > > >> My colleague was in state of despair and made thoughtful remarks >>about FORTRAN and Python similarity. He believes that Python is corrupting >>his (computer) memory... >> > >Fortran (up to F77 -- I lost touch with it afterwards) had reference >semantics in all parameter passing to subprograms (with aliasing forbidden >in rather complex ways -- very few compilers ever enforced that, letting >the hard-to-debug cases for the programmers:-)), copy semantics for all >assignments. I can't see any parallel between that and Python's >behavior, not even in the "anti-parallel" sense of Python // C. > > >> So what is the point? I wrote this message in hope that there are >>more people with similar experience. My question is - how to explain >>to novice non-programmer users (maybe mathematically "infected") >>the quirks of Python sequence objects? Which methodology to use >> > >First of all, somebody with reasonable math bent will prefer a >more general explanation -- so, forget sequence objects, because >that's just one specific cases. ALL object-mutation works the >same way, whether it be of a sequence or non-sequence. > >>in programs so we can clearly see we work with "pointers"? >> > >You're in water. Water is *everywhere*. When you think there >is nothing there, there's water. Just get used to it. Trying >to muddy up the water in an attempt to make it more visibile >would be counter-productive. > >>Or maybe someone can propose the changes to the Language to overcome >>this (psychological) barrier? I feel this as a serious obstacle >>in using Python (my students experienced it too). >> > >It appears, though you never state it, that the behavior you >would consider "natural" would have to do with copy semantics. >I find that weird, absolutely weird -- I've seen it happen to >old died-in-the-wool programmers without solid mathematical >bases, because for 20 or 30 years of their lives they had only >seen copy semantics and could no longer conceive of any other, >but that's exactly the reverse from the "mathematical bent" >you keep mentioning. > >Accepting your mention of "mathematical bent" as relevant, I >repeat my suggestion that you look into functional programming. >FP is seriously cool, IF all the programmers involved have a >solid mathematical outlook on life, the universe and everything. > >If for whatever reason you want to keep using languages based >on the idea of data modification, you won't find a simpler or >more regular one than Python. And it would be absurd to pick >old-enough languages that use copy semantics because some >previous experience (NOT with maths itself, surely?!) makes >you feel that's natural and divergences from it should be >made "very VISIBLE" -- besides Python, you'd be cutting yourself >off from Java, Eiffel, C# ... reference semantics IS the wave >of the last decade-plus, and probably of the next one too >(unless FP comes into its own, but I've sort of stopped holding >my breath for THAT -- there just isn't enough of an audience >with a pervasive-enough mathematical turn of mind:-). > >Just remembed that EVERYTHING works by reference, and what >could possibly be the problem...? > > >Alex > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mstenner at phy.duke.edu Tue Sep 10 08:39:24 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Tue, 10 Sep 2002 08:39:24 -0400 Subject: UNIX processes In-Reply-To: <200209101233.05796.b.maryniuk@forbis.lt>; from b.maryniuk@forbis.lt on Tue, Sep 10, 2002 at 12:33:05PM +0200 References: <200209101233.05796.b.maryniuk@forbis.lt> Message-ID: <20020910083924.A4265@phy.duke.edu> On Tue, Sep 10, 2002 at 12:33:05PM +0200, Bo M. Maryniuck wrote: > Hi, all. > Somebody know how to list all the processes in RIGHT way on Linux/UNIX? > I need to find the zombies, stopped processes etc. The problem is that almost every different UNIX(like) system has a different interface to the kernel/process table. You have a couple of choices: 1) use the program "ps", which does the right thing for any given os/kernel and presents a fairly standardized report, or 2) pick the os(s) that you care about, and write your own code to do it directly. On linux, that can be done pretty nicely through the /proc/ filesystem ("man proc"). -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From djc at object-craft.com.au Mon Sep 23 11:39:35 2002 From: djc at object-craft.com.au (Dave Cole) Date: 24 Sep 2002 01:39:35 +1000 Subject: M$SQL connections from linux References: <1032528860.599940@news.etel.ru> Message-ID: >>>>> "Mark" == Mark Charsley writes: Mark> In article <1032528860.599940 at news.etel.ru>, black at flamingo.ru Mark> (Vasiliy A. Mark> Chernoivan) wrote: >> Hello all Is there some module for python which performs the task? >> Is it possible at allto access data under M$SQL from linux machine? Mark> Not used it myself, but mxODBC should do the job: Mark> http://www.egenix.com/files/python/mxODBC.html Or this: http://object-craft.com.au/projects/sybase/ Compile with the latest FreeTDS from CVS (not 0.53) http://object-craft.com.au/projects/sybase/sybase/node5.html You may have a small problem with 0.35pre1 and FreeTDS in which case you should try this version of Sybase.py until I make a new release (in a week or so): http://object-craft.com.au/pipermail/python-sybase/2002-September/000059.html - Dave -- http://www.object-craft.com.au From jb at yahoo.de Mon Sep 9 16:01:32 2002 From: jb at yahoo.de (JB) Date: Mon, 09 Sep 2002 22:01:32 +0200 Subject: Python 2.3 Message-ID: <3d7cfc19_5@news.newsgroups.com> Will rational numbers be implemented in Python 2.3? And when is the first beta due? TIA, -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From aleax at aleax.it Wed Sep 25 17:57:13 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 21:57:13 GMT Subject: Getting started References: <3D920950.323B25B3@alcyone.com> Message-ID: Erik Max Francis wrote: > "James J. Besemer" wrote: > >> However "lame" or "weak" you may consider this feature to be, it does >> NOT constitute "weak typing" per the formal definition. This is >> simple >> polymorphism, as you seem to acknowledge, same in Perl as in Python. > > The problem here is that there is no official "formal definition." Some > use "weak typing" to mean any type system where the typing can be foiled > by casts; some use it to mean any system where operations, not the > objects themselves, determine the types of the objects. (I favor the > latter definition, since it carries more information about the > language.) This is simply a case of differing terminology. Bingo -- and I think that if one works through all the references I gave one will see Cardelli cover all the major issues, though he does not do so in any single one of them and his exact terminology may differ from mine, yours, James's, "Some authors'" (e.g. Scheme's R4R : """ Scheme has latent as opposed to manifest types. Types are associated with values (also called objects) rather than with variables. (Some authors refer to languages with latent types as weakly typed or dynamically typed languages.) Other languages with latent types are APL, Snobol, and other dialects of Lisp. Languages with manifest types (sometimes referred to as strongly typed or statically typed languages) include Algol 60, Pascal, and C. """ and so on. I don't think it's all that pragmatically useful to have a black/white definition for properties, in real life -- it may be good maths (or at least, much-simpler maths) but "practicality beats purity". In geometry, a 2D shape either is or isn't a circle: there is no "being more circular" or "being less circular" -- it's black and white. In real life, we don't really care in most application for a 1-micron deviation on a shape of 1 meter's diameter -- we can and do consider it "pretty much a circle" for all practical purposes. One whose deviation is 10 microns is going to be "less circular" but still OK for most purposes, etc, etc. It may be important to know the extent and character of the deviation, of course. For example, Java or Eiffel are compile-time type-safe *EXCEPT* for some covariance issues -- in arrays for Java, in procedure parameters for Eiffel. C++ has no covariance issues, but does have explicit casts, unions, etc. Fortran has no covariance nor cast issues, but does give compliant compilers a license to NOT enforce all checks that would be needed to ensure all language rules are complied with -- IF you follow all the language rules you're OK, BUT the fact that your program compiles correctly with a compliant compiler does NOT give you certainty that the rules are indeed followed -- in Fortran IV and Fortran 77, procedure parameters, equivalence statements, and mismatch of common statements for the same common between separately compiled subprograms, are all points to check (some compilers can check _some_ rules -- all are indeed enforceable, at runtime at worst, but Fortran's typical emphasis on speed means they often aren't). On the other side of the fence, it's clearly trivial to design a language which can have no type problems -- just give the language just one type, period. It's even easy for the compiler to ensure that you are indeed using that single type (as it's the only one you have) wherever it's required (i.e., everywhere). It's of no bloody practical use whatsoever, of course. In practice, we want practically useful definitions of things -- "weak typing" is one, but clearly not the only one. Eg., in another post James claimed that standard C has no objects -- something that will no doubt break Kernighan and Ritchie's hearts, since they write: """ An object is a manipulatable region of storage; an lvalue is an expression referring to an object """ and so on. [the issue IS important -- an rvalue *NEED NOT* "refer to an object" in C, while an lvalue *DOES*]. Clearly, James meant "objects as in OO", but that's not what I wrote and to which he was vehemently responding -- no matter, he clearly has his own definition of what "an object" IS, no matter what one of a language's inventor claims an object is *in the language he invented*... Our discipline hijacks many terms of everyday use -- e.g., to describe something that is done, or is to be done, in a generic way, I can't safely call it a process nor a task nor a routine nor a procedure nor a job nor ... all have specific technical meanings in some language and/or operating system, and/or in the literature. It's easier in Italian -- because most such terms are used in the English original, therefore most Italian equivalents are free for their ordinary use. Similarly in the late Roman Republic some Latin scholars apparently claimed that Greek was the only language suited to philosophy -- and didn't note that Latin *with* embedded Greek phrases was in fact much better, because technical terms appeared as such and didn't hijack the everyday, ordinary significance of the word or phrase. Alex From eugene at ulka.com Wed Sep 18 18:38:55 2002 From: eugene at ulka.com (Eugene Pervago) Date: 18 Sep 2002 15:38:55 -0700 Subject: Loading modules from several directories References: <33803989.0209172247.2e6afc1f@posting.google.com> <6Q1i9.1149$bh1.989@fe03> Message-ID: "Steve Holden" wrote in message news:<6Q1i9.1149$bh1.989 at fe03>... > "Eugene Pervago" wrote ... > > [...] > > If I put the project_a path first, it loads its modules but can't > > import the /onedir/foo modules. It seems package can only be in one > > place, once Python finds it, it just stops looking elsewhere. > > > > What would you rather have it do? Load them both? Find every possible > package and load the oine with the most recent modification date/time? Load > the longest one? Load the one whose checksum is closest to your birthdate? They do not intersect. Actually the structure is something like this: /onedir/foo dbutils.py utils.py auth.py /anotherdir/foo - Nothing /anotherdir/foo/projectA User.py Product.py In Unix I would do it using symlinks, not possible on Windows. I can think of two solutions: 1) Copy /onedir/foo/*.py to anotherdir/foo/ for each project (Doesn't seem like a good solution, though easily doable since the common files are under version control) 2) Instead of foo.projectA have a foo_projectA or fprojectA to avoid problems with nested packages. Neither of those two is particularly attractive to me. Any suggestions? Thanks, Eugene Pervago From ajs at ix.netcom.com Tue Sep 17 11:04:49 2002 From: ajs at ix.netcom.com (Arthur) Date: Tue, 17 Sep 2002 11:04:49 -0400 Subject: More on Protecting Source Code Message-ID: <001c01c25e5b$92a4e470$9865fea9@arthur> Janes writes: >It is precisely the promise of commercial reward that makes America the >incredible fount of invention and creativity that it is. You sound like a neo-something - like myself. To me the open source movement has offered the opportunity to maintain a subversive stance in the context of an essentially "conservative" world view. Sort of wholesome subversion. Makes the folks looking to make $ from their on intellectual property work a bit harder - if they are competing with folks willing to throw theirs into the ring for free. No question it has *driven* innovation. That - And there is certainly the opportunity for abuse of processes that are themselves reasonably sound - Enron and friends in some instances, Disney (for example, and in a totally different sense - and in some ways for me, closer to home), I would argue, in some others. The worst thing "we" could do is leave the high ground screaming on these kinds of situations to the folks with an essentially different world view.. Art From sholden at holdenweb.com Fri Sep 13 15:23:51 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 13 Sep 2002 15:23:51 -0400 Subject: Problem with HTTPS request References: Message-ID: "Gerhard H?ring" wrote ... > Christian Reyes wrote in comp.lang.python: [...] > >> "Christian Reyes" wrote in message > > news:... > ^^ > > Broken quoting. > > >> > [...] Note: HTTPS support is only available if the socket module was compiled > > with > ^^ > > Broken quoting again. Please throw away that OE crapware or fix it > using Morver or whatever. > Gerhard: You're showing distinct signs of having too much time on your hands :-) Can't you fix your brain instead so it will let you ignore other people's mailer problems? an-unreconstructed-OE-user-myself-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From gmuller at worldonline.nl Sat Sep 7 06:44:48 2002 From: gmuller at worldonline.nl (GerritM) Date: Sat, 7 Sep 2002 12:44:48 +0200 Subject: Smoothing a discrete set of data References: <3csmdso5.fsf@morpheus.demon.co.uk> Message-ID: "Paul Moore" schreef in bericht news:3csmdso5.fsf at morpheus.demon.co.uk... <..snip...> > I have a set of data, basically a histogram. The data is pretty > variable, and I'd like to "smooth" it to find trends. Actually, this > comes up a *lot* for me - some examples: sampled IO rates on a machine > - I want to look for trends (is IO higher overnight or during the day, > etc) or fuel consumption for my car (do I use less fuel since I had > the service). <..snip...> > Can anyone help me? I can't believe that this problem has never come > up before, but I can't find any literature on it. > Yes, this problem is very common. For instance in Physics it occurs very often. In physics the approach would be to fit "lines", where the line form depends on the particular physics. In your example it sounds as if less theory is available (how about operations research?), which means that you have less a priori knowledge of the signal. Your brain picks out the evident peaks. One approach is to filter out the high frequent noise by simply applying a low pass filter, ie a weighted average of neighboring points. A more complex approach would be to assume some distribution in peaks (for instance Gaussian) and fit a set of these peaks over the data. Depending on your expectation the peaks can be parameterized for width and amplitude for instance. I expect that in the end your interpretation is still required, but the job might be eased by this kind of computer assistance. > Thanks in advance, > Paul Moore. regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From phoebe_1 at att.net Sat Sep 21 10:27:10 2002 From: phoebe_1 at att.net (Holden Caulfield) Date: 21 Sep 2002 07:27:10 -0700 Subject: Solaris 64 bit compilation References: Message-ID: Please see insert. I apoligize for not providing all the info, as I did not have access to the machine. martin at v.loewis.de (Martin v. Loewis) wrote in message news:... > phoebe_1 at att.net (Holden Caulfield) writes: > > > This is my first attempt at compiling Python v2.2.1 in *64bit* mode > > on a Solaris 5.9 system. I am using the Sun Compiler (the latest I do not > > remember the version). I am migrating a few of my apps (all developed on > > 64bit platforms) to Solaris, so I *need* the 64bit mode. > > > I can't follow your conclusion - if you migrate applications which > have been developed on 64-bit platforms, there is no inherent need to > compile them as 64-bit binaries on Solaris 9. > Ok, What I have is Python C-Extensions that I wrote for a third party vendors software. Unfortunately, they have decided to ship *only* 64 bit libraries for Solaris. So, you see I need to build python in that mode. > > But, it is failing miserably. It compiles *fine* in 32bit mode (the default), > > but it does me no good. As some of the extensions library that I have are > > 64bit. Before, I start hacking I thought I would give a query here and see > > if anyone had any success? > > It compiles fine for me, with SunPRO 6U1. What I have is : cc: Sun WorkShop 6 update 1 C 5.2 2000/09/11 Like I said, it compiles fine for the default mode, which is creating 32bit extensions,modules. Like I said before, I *need* to have it in 64-bit objects, modules,extensions etc. > > > > > Here are my preliminary results: > > - Flags used "-xarch=v9 -xcode=pic32". > > The first thing I get is the bail-out in "pyport.h": > > Where the #LONG_BITS != (8 * sizeof(LONG)) fails!!! > > Please try to report failures carefully. It does not say sizeof(LONG), > instead, it says SIZEOF_LONG. Which gives rise to the question: What > value does SIZEOF_LONG have, in pyconfig.h? > cc -c -DNDEBUG -g -Xc xarch=v9 -xcode=pic32 -I. -I./Include -DHAVE_CONFIG_H -o Modules/p ython.o Modules/python.c "./Include/pyport.h", line 480: #error: "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." > > So, I commented it out, first to proceed and see what happens. Most of them > > compiled fine except, I got some serious errors in the: > > fileobject.c file probably related to the LP64 model. > > > > I will try to add more info, when I get around to it. > > More info would be required if you want help. Start with reporting the > error messages as the compiler produces them, instead of interpreting > them, and reporting your interpretation. > So after commenting it out, here is what I get. cc -c -DNDEBUG -g -Xc xarch=v9 -xcode=pic32 -I. -I./Include -DHAVE_CONFIG_H -o Objects/f ileobject.o Objects/fileobject.c "Objects/fileobject.c", line 282: argument #2 is incompatible with prototype: prototype: long : "/usr/include/iso/stdio_iso.h", line 209 argument : union {double _d, array[2] of int _l} "Objects/fileobject.c", line 325: return value type mismatch "Objects/fileobject.c", line 355: assignment type mismatch: union {double _d, array[2] of int _l} "=" long "Objects/fileobject.c", line 393: assignment type mismatch: union {double _d, array[2] of int _l} "=" long "Objects/fileobject.c", line 407: operands have incompatible types: union {double _d, array[2] of int _l} "==" int "Objects/fileobject.c", line 462: operands have incompatible types: union {double _d, array[2] of int _l} "==" int "Objects/fileobject.c", line 468: argument #1 is incompatible with prototype: prototype: long : "./Include/intobject.h", line 37 argument : union {double _d, array[2] of int _l} "Objects/fileobject.c", line 548: argument #2 is incompatible with prototype: prototype: union {double _d, array[2] of int _l} : "/usr/include/unistd.h", line 341 argument : long "Objects/fileobject.c", line 550: operands have incompatible types: union {double _d, array[2] of int _l} ">=" int "Objects/fileobject.c", line 551: assignment type mismatch: union {double _d, array[2] of int _l} "=" long "Objects/fileobject.c", line 553: operands have incompatible types: union {double _d, array[2] of int _l} "<" int "Objects/fileobject.c", line 555: operands have incompatible types: union {double _d, array[2] of int _l} ">" union {double _d, array[2] of int _l } "Objects/fileobject.c", line 555: operands have incompatible types: union {double _d, array[2] of int _l} ">=" int "Objects/fileobject.c", line 556: operands have incompatible types: unsigned int "+" union {double _d, array[2] of int _l} "Objects/fileobject.c", line 556: operands have incompatible types: unsigned int "-" union {double _d, array[2] of int _l} "Objects/fileobject.c", line 1173: cannot recover from previous errors cc: acomp failed for Objects/fileobject.c *** Error code 2 make: Fatal error: Command failed for target `Objects/fileobject.o' > Regards, > Martin From marco at reimeika.ca Sun Sep 22 01:34:36 2002 From: marco at reimeika.ca (marco) Date: 22 Sep 2002 01:34:36 -0400 Subject: "time" module under AIX? References: Message-ID: marco writes: > I've just compiled python 2.2.1 under AIX and all seemed > to go well. However, I'm having some trouble importing > a few modules such as "time" and "math" e.g. OK, it seems it was a permission problem. I compile/install stuff as a non-privileged user and then change ownership. However, it turns out that "make install" doesn't use the "install" command consistently and sometimes just copies stuff (without setting any permissions). In my case the files in lib-dynload ended up being 750 and this was causing problems (there may be others, I have to check carefully)... Cheers, -- marco at reimeika.ca Gunnm: Broken Angel http://reimeika.ca/ From bokr at oz.net Mon Sep 16 13:58:10 2002 From: bokr at oz.net (Bengt Richter) Date: 16 Sep 2002 17:58:10 GMT Subject: Converting Python app to C++ completely References: <3D85D9EB.9020102@thinkware.se> Message-ID: On Mon, 16 Sep 2002 09:56:34 -0400, Roy Smith wrote: >Magnus Lycka wrote: >> A common approach is to factor out the performance critical >> parts (once you have actually measured) and rewrite them in >> C or C++. The profiler is a good tool for this measuring. > >I'm in the process of doing exactly that. I've got an app I wrote in >Python which needed speeding up. Profiling showed that 99% of the CPU >time was spent in one class, which did a lot of low-level character >processing. Mostly what it did was thrash around creating string >objects and tearing them down again in a rather un-pythonic way. > >Seemed like a perfect opportunity to learn C++, so I re-wrote the class >in that language. Somewhat surprisingly, I only got about a 2x speedup. >I think the reason is because now instead of spending all my time >allocating and deallocating Python strings, I'm doing the same with C++ >strings :-) > >I'm going to take a shot at re-writing it again using C-style arrays of >characters. It'll be interesting to see how much speedup I get. I >figure one of two things will happen; either the C version will be much >faster than the C++ version, or it won't. Either way, I figure I will >have learned something about C++, and maybe about Python too :-) Maybe you could post the culprit class and see what alternative _algorithms_ people come up with. It sounds like the badness is in your methods ;-) Regards, Bengt Richter From robie at 1373.net Mon Sep 23 22:30:21 2002 From: robie at 1373.net (robie1373) Date: Mon, 23 Sep 2002 20:30:21 -0600 Subject: confusion about opening files Message-ID: <3d8fcda4$0$198$75868355@news.frii.net> I am trying to open a file, >>> import os >>> file = os.open("e:\\d12", "r") Traceback (most recent call last): File "", line 1, in ? file = os.open("e:\\d12", "r") TypeError: an integer is required I get this error if the mode is r, r+, a+ or whatever. I also get it whether the file exists or not. Can someone explain what I am doing wrong? From dsavitsk at e-coli.net Fri Sep 6 19:34:32 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 06 Sep 2002 23:34:32 GMT Subject: Larry Wall's comment on python... References: Message-ID: "Gillou" wrote in message news:albdk2$2iro$1 at norfair.nerim.net... > "Rod Stephenson" a ?crit dans le message de news: > wkr8g7rn4c.fsf at yahoo.com... > > Slashdot has a list of questions posed to Larry Wall (perl). When > > asked his thoughts on other scripting languages, he makes the > > following observation about python > > > > "Python is cool to look at small bits of, but I think the "outline" > > syntax breaks down with larger chunks of code. I'm with Aristotle on > > the structure of discourse--a story should have a beginning, and > > middle, and an end. So should blocks" > > > > I'm not quite sure what he's trying to get at here - I guess that for > > a long heavily indented chunk of code, you could lose track of the > > overall structure, but I don't write code this way. > > > > Any comments? > > Long heavily indented chunks of code is a really bad programming style > (whatever's the language). > Modern python editors can find blocks, hide/show blocks, auto indent/dedent > blocks, and find start/end of blocks. Further, those of us used to using, say, the treeview in Outlook [Express] to read newsgroups, or other similarly structured interfaces, find the hierarchy of Python indenting quite natural. -d > Tabnanny does a fine job on ugly indenting. > > def longfunction(): > # 300 lines of code below > ... > return > # end longFunction() > > From mhammond at skippinet.com.au Wed Sep 25 18:43:13 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 25 Sep 2002 22:43:13 GMT Subject: PythonWin CVS problem References: Message-ID: <5_qk9.20506$6g7.64886@news-server.bigpond.net.au> David LeBlanc wrote: > I'm using the same repository I've been using for the past 6 months or more: > :pserver:anoncvs at cvs.pythonpros.com:/home/cvsroot > > Just tried it again and got the same: "permission denied". > > David LeBlanc > Seattle, WA USA > > >>-----Original Message----- >>From: python-list-admin at python.org >>[mailto:python-list-admin at python.org]On Behalf Of Dilton McGowan II >>Sent: Tuesday, September 24, 2002 20:30 >>To: python-list at python.org >>Subject: Re: PythonWin CVS problem >> >> >>David LeBlanc wrote: >> >> >>>Second day it's inaccessable with "permission denied" >>> >>>David LeBlanc >>>Seattle, WA USA >> >>Are you using cvs.pythonpros.com? It worked for me yesterday and >>again just >>now. They seem to have the latest source. Just a friendly suggestion. >>-- >>http://mail.python.org/mailman/listinfo/python-list It may be a local permissions problem. Try checking out the tree to a new directory. Mark. From etralex at ua.pt Mon Sep 23 16:23:28 2002 From: etralex at ua.pt (Ricardo B) Date: Mon, 23 Sep 2002 21:23:28 +0100 Subject: Very complex Python/C++ embedding/extension question(s) References: <3d8cfd3c$1@news.swissonline.ch> Message-ID: <1032812577.470847@newsfront3> On Sun, 22 Sep 2002 01:13:23 +0200, Bernhard Glueck wrote: > Hi there > I am developing a new multimedia/game/vr architecture, and at the moment > i am trying to embed python as a scripting language. I have a slew of > questions about the Python/C API.. > > Your architecture could do with some better explanation. Anyway, based on that you can add new Actor/Type classes in run-time, I'll assume that Actor/Type's child classes don't extend their parent's interface and that you have a system where new classes can be dynamically registred. Therefore, you only need a C++ to Python wrapper to the base class, and you can use that wrapper for instances of child classes. The same holds true for Python to C++ wrappers. You should provide an interface for the childclasses written in Python to register themselves and to see what classes are avaliable, the sameway you do with the C++ classes. About the third question: Why don't you just use actor.Call("DoSomething", ...) in Python code, as you do in C++? You're just begging for increased confusion. -- Ricardo From andrewm at object-craft.com.au Tue Sep 17 23:24:36 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Wed, 18 Sep 2002 13:24:36 +1000 Subject: How to make a C extension module backwards compatible? Message-ID: <20020918032436.0DC653C21B@coffee.object-craft.com.au> Is there any community wisdom on how to make a C extension module that implements a new-style class (type?) backwards compatible (albeit, at the cost of some functionality)? Put another way, how *should* I make a class implemented in C behave like a new-style class when installed with python 2.2 and above, and like an old style class when installed with older pythons? Should I just riddle the code with #ifdef's, or is there a more elegant way? -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From spoermeg at voldelig.com Tue Sep 17 19:33:37 2002 From: spoermeg at voldelig.com (Terje Johan Abrahamsen) Date: Tue, 17 Sep 2002 18:33:37 -0500 Subject: Source code References: Message-ID: "Martin v. Loewis" wrote in message news:m3admizdzq.fsf at mira.informatik.hu-berlin.de... > Gerhard H?ring writes: > > > You should perhaps reconsider if and why you need to hide your source > > code. > > You should also recognize that, if your computer can execute and > perform a certain algorithm, users can always observe simulate the > computer operations, thus breaking any protection scheme. > > You'll have to give your customers a sealed computer and no permission > to install additional software, or communicate with the internet, if > you want to reliably prevent them from analysing your program. I guess that will be a little overkill. I am not writing military software or software that has uniqe algoritms. I just want to make sure that if someone is going to steal my program to sell it themselves, that they have to actually write the code. Not only get mine, remove the copyrights, fill in what they want and sell it away. If Py2Exe stores the source in pretty much open for reading, I need to use another way of protecting it. But, the programs will be availiable for download, and will be possibly to copy. I just want to make it a little harder. From martin at v.loewis.de Sat Sep 21 19:28:22 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 22 Sep 2002 01:28:22 +0200 Subject: Python 2.2.1 compatible with Tcl/Tk 8.4? References: Message-ID: Paul Moore writes: > Hmm, experimenting, it looks like it doesn't. So I must have to tell > Python to use the installed TCL 8.4. How? You need to recompile _tkinter.pyd. Regards, Martin From marklists at mceahern.com Mon Sep 23 19:06:34 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 23 Sep 2002 18:06:34 -0500 Subject: list problem In-Reply-To: <-29615135.1032818024099.JavaMail.nobody@webmail2.brturbo.com> Message-ID: [jubafre at brturbo.com] > i have: > x=[['0020', '0000x9'], ['0030', '0000xa'], ['00B4', '0000x8'], > ['0030', '0000xb'], ['00F0'], ['0001'], ['0003'], ['0005']] > > and i want: > y=['0020', '0000x9', '0030', '0000xa', '00B4', '0000x8', '0030', > '0000xb','00F0', '0001', > '0003', '0005'] > > how to do this? You want to flatten a sequence. Here's a recipe that does that: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/118845 I'll leave it as an exercise for you to deal with the string type appropriately. I think the recipe will try to flatten the string (although I have not tested to confirm that) and that's probably not what you want. // m - From brueckd at tbye.com Thu Sep 26 11:22:00 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Thu, 26 Sep 2002 08:22:00 -0700 (PDT) Subject: Python threading? In-Reply-To: Message-ID: On Thu, 26 Sep 2002, Thomas Weholt wrote: > This might be just a stupid question, but I'm trying to implement a > filesharing-app, based on the BaseHTTPServer in the standard python-distro. > This will of course be heavy IO-processing involved. Will threading still be > a bad idea? The project is aimed at small user-groups ( I do not think one > person will have more than say 5-10 concurrent connections at a time, most > of them downloading files 1MB + in size), At those low load levels, threads will be fine. > as if threading is a very bad idea no matter what, still it's used almost > everywhere ( I got no statistics to back up that statement ;-) ). You have to factor in the issue of complexity too though. The threading approach is almost always much simpler and many applications don't need to be high performance, so threading is acceptable. That said, the asynch approach _is_ useful to know and understand - if for no other reason than it makes you understand the problem from a very different angle. And after awhile it really starts to "click" in your head and make sense. State machines are nifty. :) > NB! It would be nice to be able to limit the number of threads, actually the > number of concurrent connections, on the server too, so if anybody has any > comments on some way of doing that and still handle request gracefully Is the client side a web browser or a custom app? Your request handler could return a nice "server is busy" (e.g. HTTP 503) message to a browser, but if you want to explicitly cap the number of threads you'll need to subclass the server. It's been awhile since I've looked at SocketServer, but I think it has a check_request or verify_request or something method that you could override to send back an HTTP 503 if the server is overloaded (already has N threads running) and then return false (as in, "don't process this request any further). -Dave From phncontact.libero.it at Wed Sep 4 03:59:23 2002 From: phncontact.libero.it at (Benjamin) Date: Wed, 04 Sep 2002 07:59:23 GMT Subject: Servizi Internet References: Message-ID: by the way, how many people understand italian in this nesgroup? ^_^ From danb_83 at yahoo.com Sun Sep 22 00:36:04 2002 From: danb_83 at yahoo.com (Dan Bishop) Date: 21 Sep 2002 21:36:04 -0700 Subject: Math optimization References: <6T5j9.145247$pX1.5195840@news2.tin.it> Message-ID: jepler at unpythonic.net wrote in message news:... > Did you bother benchmarking? I'd be surprised to see a huge difference, > since the overhead of the bytecode loop should be much much greater than > the cost of a single division operation. There is a very slight difference. On my PC, a / 2.0 takes 824 ns a * 0.5 takes 784 ns From mhammond at skippinet.com.au Tue Sep 17 07:14:57 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 17 Sep 2002 11:14:57 GMT Subject: win32security.LogonUser not working References: Message-ID: <3D870F4B.7000904@skippinet.com.au> {posted and mailed] dsavitsk wrote: > I have gone so far as to assign every possible right in dir(ntsecuritycon), > but i am still getting the same error. I have also assigned nearly everyone > and every thing on my network the right to act as the os. any ideas? > > -d > > > "dsavitsk" wrote in message > news:L9Pg9.8440$yt3.4474038 at newssrv26.news.prodigy.com... > >>should have mentioned >>python: 2.1.3 >>win32all: 145 >>win2k: sp2 >> >> >>"dsavitsk" wrote in message >>news:x6Pg9.8439$yt3.4473830 at newssrv26.news.prodigy.com... >> >>>I am trying to run code as another user. I copied the code below from >> >>ASPN, >> >>>so it would seem that someone has gotten this to work. I keep getting >> > the > >>>error >>> >>>pywintypes.api_error (1314, 'LogonUser', 'A required privilege is not >> > held This is a *privilege* issue, not a *permissions* issue. This same issue happens when trying to reboot a server - from the RebootServer.py script I posted recently: import win32security import win32api import sys import time from ntsecuritycon import * def AdjustPrivilege(priv, enable = 1): # Get the process token. flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags) # Get the ID for the system shutdown privilege. id = win32security.LookupPrivilegeValue(None, priv) # Now obtain the privilege for this process. # Create a list of the privileges to be added. if enable: newPrivileges = [(id, SE_PRIVILEGE_ENABLED)] else: newPrivileges = [(id, 0)] # and make the adjustment. win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges) Look for C/C++ samples using the LogonUser function in the way you are trying to, and I am confident you will find similar calls to the above in that sample code. Let us know if you sort it out - or better still, send me a sample .py file that uses it which I can include in win32all :) Mark. From hst at empolis.co.uk Tue Sep 17 05:53:23 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 17 Sep 2002 10:53:23 +0100 Subject: Regular expression help needed Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F41A@hendrix.empolisuk.com> Torkil Grindstein wrote: > Sent: 17 September 2002 10:04 > To: python-list at python.org > Subject: Regular expression help needed > > > Hi. > > It's been a while since I played around with regexps, and I > realize that I really need some help here. > > Mission: I have a string containing a whole WML document. I want > to extract data from following occurences: > > > > That is, I want to extract the content of any occurences of > the meta "michael" key. There may be several occurences in one > document. > > > will give me the results "owen" and "jackson". > > Of course, it is possible that the document has written the > tags in uppercase (META Name, META NAME, etc), but I could > lowercase the whole document string prior to searching. (The > content is case insensitive for my purposes.) > > I would really be glad if someone out there took this challenge..:) > > Cheers, > Torkil > -- Superficially, this is easy: >>> s='' >>> r=re.compile('>> r.findall(s) ['owen', 'jackson'] but I can't really recommend it as it contains too many implicit assumptions: 1) There are no comments or processing instructions that could contain similar data 2) The attributes always come in the order specified i.e. name first, content second, any others following 3) The attributes are always double quoted and there are no spaces surrounding the = All of these can be got round by using REs, but as the data is in (presumably well-formed) XML an easier solution would be to parse the XML using SAX and simply examine the attributes of each element named "meta" or "META". Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From tjabo.kloppenburg at unix-ag.org Wed Sep 18 22:41:52 2002 From: tjabo.kloppenburg at unix-ag.org (Tjabo Kloppenburg) Date: Thu, 19 Sep 2002 04:41:52 +0200 Subject: Regex question In-Reply-To: References: Message-ID: <20020919044152.50f6bab2.tjabo.kloppenburg@unix-ag.org> hi, "Eric Arnold" wrote: > The string I'm capturing is as follows: > Name:AAA,BBB,CCC why regexp? just do: splitted1 = s.split(":",2) # --> splitted[0] == Name events = splitted1.split(",") # = list of events it is not that cool, but it runs without brainsucking experiments... :) tk. -- Tjabo Kloppenburg --=- In 95.82 Tagen ist Weihnachten! -=-- -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From megabytemonster at hotmail.com Tue Sep 3 16:29:23 2002 From: megabytemonster at hotmail.com (Stuart) Date: 3 Sep 2002 13:29:23 -0700 Subject: winsound.Beep() frequencies Message-ID: <3ab719f7.0209031229.33667461@posting.google.com> While looking at the python documentation, I noticed that there are no frequency/pitch tables for using with the winsound module. Does anyone know whether this documentation exists, and/or what the corresponding frequencies to pitches are? Thanks, Stuart From neel at mediapulse.com Thu Sep 12 18:37:20 2002 From: neel at mediapulse.com (Michael C. Neel) Date: Thu, 12 Sep 2002 18:37:20 -0400 Subject: [mod_python] ANNOUNCE: Mod_Python donated to ASF Message-ID: Let me be the first to say, in the fashion that the Internet has taught us to celebrate a great victory or other action.... Woot. Mike -- Michael C. Neel There are only 10 types of people in the world; those who understand binary and those who don't. -----Original Message----- From: Gregory (Grisha) Trubetskoy [mailto:grisha at modpython.org] Sent: Thursday, September 12, 2002 6:26 PM To: mod_python at modpython.org; python-list at python.org; announce at apache.org; dev at httpd.apache.org Cc: jim at apache.org Subject: [mod_python] ANNOUNCE: Mod_Python donated to ASF It is my pleasure to announce that Mod_Python has been donated to the Apache Software Foundation, and is now a subproject of the httpd server project (see http://httpd.apache.org/). I am grateful to ASF for accepting this donation and committing resources to further the support of Mod_Python. I believe that this action will advance the development of Mod_Python, resulting in an ultimately better and more popular tool for Python developers. I also believe it will serve to better position Python as a language of choice for web development, a need that has been expressed by many. There are no implications to the current Mod_Python users - the license is the same with the sole difference in that the copyright belongs to ASF now. As a consequense of the donation, the CVS repository is now hosted on cvs.apache.org. Do not use the SourceForge repository anymore, it will soon be removed. There will also be website and mailing changes, but the details are still being finalized and will be announced when ready. Regards, Grisha Trubetskoy _______________________________________________ Mod_python mailing list Mod_python at modpython.org http://www.modpython.org/mailman/listinfo/mod_python From tchur at optushome.com.au Thu Sep 12 17:04:22 2002 From: tchur at optushome.com.au (Tim Churches) Date: Fri, 13 Sep 2002 07:04:22 +1000 Subject: Detecting Russian and Ukrainian character sets Message-ID: <3D810156.67A62B78@optushome.com.au> Here are two questions for Russian and Ukrainian Python users: 1) I understand that a common problem when processing text data collected from various sources in Russia and the Ukraine is the mixture of character sets which are used - MS-DOS, Windows, Linux, Unix and mac machines may all use one (or more) of a number of character sets to encode strings, and when such data are supplied in text files, there is usually no indication of which character set was used. Is this correct? http://czyborra.com/charsets/cyrillic.html has a listing of known Cyrillic character sets. 2) Are there any Python routines available for automatically deducing which character set was used to encode a particular text file (or a particular string)? There is a module for Perl called Lingua:RU:Charset which seems to address this problem (see http://www.freebsd.org/cgi/url.cgi?ports/russian/p5-Lingua-RU-Charset/pkg-descr ) at least for Russian encodings. Tim C From roy at panix.com Sun Sep 22 21:08:23 2002 From: roy at panix.com (Roy Smith) Date: Sun, 22 Sep 2002 21:08:23 -0400 Subject: more on weak typing.. References: Message-ID: "Lance" wrote: > So Python is both dynamically typed (because it doesn't use explicit > datatype declarations) and strongly typed (because once a variable has a > datatype, it actually matters). A favorite interview question of mine is to ask the applicant to classify a whole bunch of attributes as more likely to belong to a compiled language, an interpreted language, or neither. I'm not so much interested in the actual answers as I am to see that the applicant knows what I'm talking about. One of those attributes is "strongly typed". I once had somebody tell me that compiled languages are strongly typed because they support longer variable names (i.e. it takes more keystrokes to type in the program). From sholden at holdenweb.com Tue Sep 10 18:57:14 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 10 Sep 2002 18:57:14 -0400 Subject: Pickle problem References: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D10@hendrix.empolisuk.com> Message-ID: "Michael Chermside" wrote ... [good advice on getting pickled] > PS: If what you are trying to do is save in the pickle the exact way > that the "match" method works because you are afraid that the > maintainers of Python may come out with a new version of Python in which > match works differently and is no longer backward compatible, and you > want your code to still work the same way in this hypothetical new > version of Python, then you really *DO* need to store (2). > Unfortunately, it's still not possible (AFAIK). Fortunately, the > maintainers Python wouldn't do that to you. > Not if you make a contribution to the PSU, about which I recently heard From mfranklin1 at gatwick.westerngeco.slb.com Mon Sep 16 12:06:58 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 16 Sep 2002 16:06:58 +0000 Subject: getting username from uid In-Reply-To: References: Message-ID: <200209161606.58840.mfranklin1@gatwick.westerngeco.slb.com> On Monday 16 Sep 2002 2:05 pm, Rajarshi Guha wrote: > Hi, > when I do a stat on a file I can get the UID of the owner. IS there > anyway to get from UID to username (or directly to username for that > matter)? On *nix look at the pwd standard module... $ pydoc pwd Python Library Documentation: module pwd NAME pwd FILE /usr/local/lib/python2.2/lib-dynload/pwd.so DESCRIPTION This module provides access to the Unix password database. It is available on all Unix versions. Password database entries are reported as 7-tuples containing the following items from the password database (see `'), in order: pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell. The uid and gid items are integers, all others are strings. An exception is raised if the entry asked for cannot be found. FUNCTIONS getpwall(...) getpwall() -> list_of_entries Return a list of all available password database entries, in arbitrary order. See pwd.__doc__ for more on password database entries. getpwnam(...) getpwnam(name) -> entry Return the password database entry for the given user name. See pwd.__doc__ for more on password database entries. getpwuid(...) getpwuid(uid) -> entry Return the password database entry for the given numeric user ID. See pwd.__doc__ for more on password database entries. DATA __file__ = '/usr/local/lib/python2.2/lib-dynload/pwd.so' __name__ = 'pwd' HTH Martin -- ### Python Powered Signature I started writting this email on Mon Sep 16 16:05:22 2002 From martin at v.loewis.de Mon Sep 30 15:39:00 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Sep 2002 21:39:00 +0200 Subject: About data structure References: <3d98a5d8$0$496$7a628cd7@news.club-internet.fr> Message-ID: malan writes: > I need to build a data structure like this : > > size 4 bytes ( example 0x0000000A ) > flag 1 byte ( example 0x87 ) > trans 8 bytes ( example 'URTVMI1' ) > F5 3 bytes ( example 0x00125C ) > > How can I define that structure, format it and send it via a socket ? Your specification is incomplete, as you don't give the byte order. Assuming it has to be big-endian, that would be >>> import struct >>> struct.pack(">IB8s3b", 0xA, 0x87, "URTVMI1", 0x0, 0x12, 0x5c) '\x00\x00\x00\n\x87URTVMI1\x00\x00\x12\\' For details, help(struct). HTH, Martin From claird at starbase.neosoft.com Thu Sep 19 08:57:40 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 19 Sep 2002 07:57:40 -0500 Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> Message-ID: <108666F172046BF0.AFF78CED7027291C.080DCC403BC7489C@lp.airnews.net> In article , Steve Holden wrote: >"Nenad Propadovic" wrote ... . [much thoroughly sensible advice] . . >> The GUI has a part I consider complex: I have to present some statistics >in >> form of charts or graphs. > >The Python Image Library (PIL) is very good for creating graphics. You can >create them "on the fly" in your web server and then serve back HTML >documents with references to the created graphics. . . . It strikes me that Mr. Propadovic is tackling several new techniques and technologies at once. Given that, I have an alternative to suggest for "some statistics in form of charts or graphs". There's a trick for making making simple bar charts which requires no extra modules or pro- gramming. It's so simple, in fact, that it makes barcharting easy in shell or assembler or C. Apparently I've only documented it in Tcl (see references there, though, for Python hints). If you need a sample dilation in Python, just say so here. Also, Mr. Propadovic: take Steve's advice to heart. Even the CGI about which he writes need not be as challenging as your comments suggest you fear it to be. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From jslowery at hotmail.com Fri Sep 20 02:24:14 2002 From: jslowery at hotmail.com (Jeremy Lowery) Date: Fri, 20 Sep 2002 01:24:14 -0500 Subject: Suggesting a filename on a HTTP-request by sending someting in the header of the reply References: Message-ID: > I got a simple webserver serving files, but the files are found using > lookup based on ids ( like http://localhost/dl?id=10, where 10 is a key in a > dictionary pointing to a file ), not their filename so when I send > content-type = 'application/octet-stream' in the headers to the client I get > the proper "Save as ..."-dialog, but the filename is all screwed up. It seem > to be the "dl"-part of the url above. I've tried to read the RFC > 2616-document and sent "Content-Disposition"-headers etc. but with no luck. > > What headers do I need to send for it to get the proper filename in the > "Save as ..."-dialog? Say for instance that the filename I wanted the client > to save the file as was "test.zip". The Content-Type (along with the file extension in Internet Explorer) dictate what the browser will do when it recieves the file. Internet Explorer also completely ingnores content-types, and it tries to guess what the content-type of the document is. Depending on the MIME type configuration of the client, it may prompt to download, automatically open the file, etc. The easiest (and most common way) to to include this functionality is to put "right click and save target as" near the link. the Content-Disposition will give a source of the file (a filename; very useful when using CGI to dynamically send files), but it has nothing to do with the content-type and how the browser reaacts to it. Content-Disposition: file; filename=%(filename)s is the proper way to use the http header to show the "filename" of what is being downloaded. J Lowery From cbbrowne at acm.org Fri Sep 20 23:39:48 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 21 Sep 2002 03:39:48 GMT Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> <7xn0qcfafp.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Christopher Browne writes: >> The COBOL (or PL/I, or anyone else accustomed to BCD data types) guy >> will justifiably look at the bizarro FP rounding as being, well, >> bizarre. >> >> There's _no_ good reason for subtracting two perfectly good decimal >> values from one another to result in having weird artifacts appear in >> some 17th decimal place, aside from having a willingness to admit >> fairly deranged arithmetic. > > Um, put $1000.00 in an imagined bank account and have it collect 5% > annual interest, compounded daily for 25 years. How much money is in > the account at the end? > > The "true" answer is (1+(.05/365))**(365*25) dollars, assuming 365 day > years. > > The IEEE double precision answer will be extremely close to that > amount. > > What happens if you do that calculation in BCD? How would you even > specify how to do it? I don't think you will get nearly as much > accuracy. REALITY CHECK for a moment. What do you think A Real Live bank uses to compute interest? Financial transactions are most certainly /not/ computed based on the quasi-infinite precision that you are imagining. Were you expecting IEEE double precision arithmetic, applied over the period of 25 years? Or perhaps, instead, might they use BCD arithmetic, applied on each date that interest is to be accrued? If I put $1000 in a /real/ bank account, earning 5% interest, compounded daily, paid monthly, it is more than just /slightly/ likely that the bank in question would, using code likely written in PL/I or COBOL, put money into the account every month, with amounts rounded based on BCD arithmetic. The "true answer" will most certainly be the BCD-based answer; that's the amount of money you'd have in the account 25 years later. If you protest that the "true" answer is supposed to be (1+(.05/365))**(365*25) dollars, and that the bank is short-changing you by 7 cents, the bank will quite glibly tell you to look at the interest policy, which /won't/ be based on waiting 25 years to apply the interest. -- (reverse (concatenate 'string "gro.mca@" "enworbbc")) http://cbbrowne.com/info/oses.html One man's constant is another man's variable. -- Alan Perlis From BPettersen at NAREX.com Mon Sep 9 14:58:48 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 9 Sep 2002 12:58:48 -0600 Subject: Embedded Python implementation Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019201253160@admin56.narex.com> > From: Evan [mailto:tagith1394 at hotmail.com] [snip] > I have inserted a small amount of C to print the contents of > com_list, > right before the PyRun_String, here is the complete output (*** marks > beginning and end of the script) > > *** > 112 (p) 114 (r) 105 (i) 110 (n) 116 (t) 32 ( ) 34 (") 104 (h) 101 (e) > 108 (l) 108 (l) 111 (o) 34 (") 10 ( > ) *** > File "", line 2 > > ^ > SyntaxError: invalid syntax I can't tell from your output, but there are a couple of gotcha's: - the line terminator needs to be the same as for your Python installation. - The last character(s) in the string needs to be a line terminator. hth, -- bjorn From steve at ferg.org Fri Sep 13 08:32:04 2002 From: steve at ferg.org (Stephen Ferg) Date: 13 Sep 2002 05:32:04 -0700 Subject: ANN: Thinking in Tkinter References: <1a3a9ffa.0209120856.1de06f57@posting.google.com> Message-ID: > I can't really say WHY using a class structure is desirable. It is coming back to me now. As I was working on easygui.py (http://www.ferg.org/easygui/), I noticed two things. (1) I was using global variables a lot. (2) I had several GUI "chunks" in one Python program, and when they were all at the same level, the code was really unstructured. Very hard to understand. Granted, a lot of my confusion was simply newbie confusion. But I thought that the next Tkinter development I did, I would see if structuring the GUI component into classes would help with these problems. Even in the limited development I've been doing for "Thinking in Tkinter", it seems to me that: (1) being able to refer to "self." variables removes the need to make so many variables global. (2) Grouping the GUI material into classes really helps bring some structure to the program that it didn't have before. I suspect that the importance of this (which may not be that obvious in small programs) will become overwhelmingly obvious in larger and more elaborate GUIs. One of my "to do" items is to test this hypothesis by re-writing easygui.py using a class structure. So right now, my hypothesis is that -- although Tkinter technology does not *require* you to structure your GUI as class -- doing so is probably desirable simply from the standpoint of making a large program more manageable. From edwardam at interlix.com Sun Sep 22 02:00:46 2002 From: edwardam at interlix.com (Edward Muller) Date: 21 Sep 2002 23:00:46 -0700 Subject: Python HTTPSConnection/HTTPResponse Problem Message-ID: <9abedeb.0209212200.5c669a50@posting.google.com> I am trying to use HTTPSConnection and HTTPResponse objects to process payments with Authorize.net. I've search (using google) the net and couldn't find any solid examples, so I'm not sure if I'm doing this right. I *know* that I am creating and sending the request correctly because Authorize.net sends me an email with the data in as verification. The problem is that calling conn.getresponse() (actually calling con.sock.makefile('rb',0) also does this) ends up hanging until the connection times out. Authorize.net AFAIK sends only one thing back in response to the HTTPS POST, and that is a comma seperated list of values that include the condition of the transaction (as you can interact with the customer). My though was that perhaps the things get really messed up because the data passed back isn't a normal HTTP response ... so I tried playing with the behind the scenes stuff (peeking into httplib.py) .. . and like I said above ... calling conn.sock.makefile('rb',0) ... which looks like what I need to do to get a file object hangs as well ... So I dunno... Oh and PS conn is a HTTPSConnection instance ... Any help would be very appreciated! From martin at v.loewis.de Tue Sep 17 01:33:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Sep 2002 07:33:43 +0200 Subject: Pickling slotted instances References: Message-ID: Andrew McNamara writes: > I'd agree with this. The __slots__ notation is a bit of a wart, but then > again, it's consistent with several other tricks. Depending on which tricks you mean, I think they all deserve proper syntax (static and methods, properties, super, ...), e.g. class Foo: def m1(kl)[classmethod]: pass def m2()[staticmethod]: pass def m3()[get('x')]: return -1 > I see your point, but it seems like most of the machinery is already > there. It's a shame that slotted classes aren't more "complete", > because they are the perfect answer to people who use tuples instead > of classes for performance reasons (they are only slightly slower > than a tuple). A shame for whom? As I said - unless somebody contributes a solution, there is none. Regards, Martin From DennisR at dair.com Mon Sep 16 20:07:03 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Tue, 17 Sep 2002 00:07:03 GMT Subject: Windows AutoRunning Python Hello -- feedback requested Message-ID: For Windows platforms (only, sorry), I have packaged enough Python to import the os.py library and its dependencies for distribution as an EXE to systems not having Python installed. Python is running as a CGI program on top of a web server I wrote so that the interface is HTML, supporting IE 4+, Netscape 4.7+, and Opera (4+?). The demo is at http://www.dair.com/hellopy.zip When decompressed and run, the EXE displays "hello" in a browser window and shows its running directory as evidence that os.py is functioning. Compressed ZIP size is 401 Kb, expanded is 922 Kb. 1) Is this the right group to discuss/get feedback? 2) Is this functionality useful enough to others to pursue? 3) Other comments? Thanks, Dennis -- Dennis Reinhardt http://www.dair.com From barry at zope.com Fri Sep 13 11:45:16 2002 From: barry at zope.com (Barry A. Warsaw) Date: 13 Sep 2002 11:45:16 -0400 Subject: RELEASED email package version 2.3 References: Message-ID: >>>>> "GH" == Gerhard H?ring writes: GH> Barry A. Warsaw wrote: >> I've just released the (standalone) email package version 2.3. GH> Is there any summary on changes, possible incompatibilities GH> and deprecated features in comparison with the email package GH> in Python 2.2 available? Yes, there's a detailed NEWS file in the package, which describes all the changes in the history of the package. There's lots of new stuff and a few deprecated APIs, so it would be worthwhile reading the NEWS file over (I'm not posting it here due to size). The documentation is still lagging, but I intend to update that during the Python 2.3 alpha cycle. -Barry From bowman at montana.com Fri Sep 27 23:58:27 2002 From: bowman at montana.com (bowman) Date: Fri, 27 Sep 2002 21:58:27 -0600 Subject: Better terminal for windows? References: <3D94B037.2020202@motorola.com> Message-ID: <7I9l9.12791$V64.3332431@newsfeed.slurp.net> Stephen Boulet wrote: > > If I want to run python interactively (and perhaps using ipython), is > there something better than the "cmd" terminal? There is a standalone tcsh that works rather nicely. From never at mind.info Wed Sep 18 07:38:36 2002 From: never at mind.info (G. Willoughby) Date: Wed, 18 Sep 2002 12:38:36 +0100 Subject: Could someone please try and py2exe this? Message-ID: I've had lots of trouble trying to 'py2exe' this app. i keep getting import errors, can someone else please try it and see if you have any luck? If so could you please upload it somewhere where i could get it or send me it via email? Its a Win32 app BTW: http://www.thecalm.fsnet.co.uk/MapperGUI/files/MapperGUI%20v1.6%20Win32.zip Thanks, --G. Willoughby email: sab(at)freeuk(dot)com From chris.gonnerman at newcenturycomputers.net Sun Sep 29 23:42:52 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sun, 29 Sep 2002 22:42:52 -0500 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xelbcgo56.fsf@ruckus.brouhaha.com> Message-ID: <003501c26833$75827560$ba01010a@local> ----- Original Message ----- From: "Paul Rubin" > "Chris Gonnerman" writes: > > > >>> (.70 * .05) + .000000001 > > > > > > rounds to the right thing. > > > > Cool. Now PROVE that's right in all cases. > > What do you mean by "right"? What do you mean by "all > cases"? The original subject is *business* arithmetic. There is no choice but to use decimal arithmetic if you want your math results to match good-old-fashioned pen and paper math. That defines "right." "All cases" refers to all numeric domains common to *business* math. The exact number of decimal places and the rounding rule (0.5 up/0.4 down vs. "banker's rounding" which is rounding 0.5 to an even number) will vary from nation to nation and sometimes from industry to industry, but the expectation of reliable rounding results is still the same. Sorry not to have defined the terms; if you are following the discussion I would expect you to know this. If we were talking about tracking satellites or computing the mass of the electron I'd defer to the experts (those who work in those fields) regarding the best sort of computer math to use. When it comes to business, though, I have experience. As another poster noted, it really doesn't matter if *we* think that results such as the above are "good enough," as our bosses/customers/legislators/users control the definition of "good enough." Most of them can't stand to mislay a penny. I've never worked for a boss who wasn't human (although I have wondered sometimes if I was working for a weasel in human clothing). Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From sholden at holdenweb.com Wed Sep 11 20:23:38 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 11 Sep 2002 20:23:38 -0400 Subject: [FEEDBACK] Is this script efficient...is there a better way? References: Message-ID: "Bob X" wrote ... > I am a newbie at this and this is a script I have come up with. I am > looking for pointers on any "newbie" gotchas or ways to do it better. > > I use this to parse a log file (30MB+) for keywords and write the lines > that are found into another file. > > Any thoughts would be appreciated... :-) > > Bob > > #!/usr/local/bin/python -w > > # import the needed libs > import sys, string > > # make sure the command line arguments are there > if len(sys.argv) < 3: > print "usage: fread.py [log file] [hit file]" > sys.exit(1) > Unless the return is important, you'll find sys.exit("usage: fread.py [log file] [hit file]") more convenient. > # open the files with some error checking > try: > inFile = open(sys.argv[1],"r") > except IOError: > print "Cannot open log file!\n" > sys.exit(1) > > try: > outFile = open(sys.argv[2],"w") > except IOError: > print "Cannot open hits file!\n" > sys.exit(1) > Your error checking is exemplary. Normally I'm happy to have a Python exception explain the error condition, but of course your explicit messages are great. > # build list of keywords > kw = [ "some", "words" ] > > # loop through the list and print the lines to a file > for line in inFile.readlines(): > for badword in kw: > if line.find(badword) > -1: > result = '%s %s' % (badword, line) > print result # Print the result > outFile.write(result) # Write the result > If you only wanted to know the lines that match at least one of the words you could follow the write() with a "break", since there's no need to continue the loop then. Also, the "print" looks like a debugging statement. > # close the files > inFile.close() > outFile.close() > > # let me know when it's done > print "Finished processing file..." > Highly commendable. Another approach would be to build a regular expression from the keywords list and search for the r.e. in each line. The following code is untested... kw = ["some", "words"] kwpat = "|".join(kw) pat = re.compile(kwpat) for line in inFile.readlines(): if pat.search(line): outFile.write(line) for example. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From oren-py-l at hishome.net Thu Sep 12 06:06:15 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Thu, 12 Sep 2002 06:06:15 -0400 Subject: [xml.dom.minidom] why cant it parse '&' In-Reply-To: <9zZf9.24873$_l1.66951@news-server.bigpond.net.au> References: <9zZf9.24873$_l1.66951@news-server.bigpond.net.au> Message-ID: <20020912100615.GB41211@hishome.net> On Thu, Sep 12, 2002 at 09:58:29AM +0000, :B nerdy wrote: > im using the minidom.parseString() to parse the following text > > > Congo Mombo - Guitar Gable & The Musical Kings > Various > blues > 12 > Westwood > 2002-03-11 > > > when it comes to the '&' it throws an exception. is there any way around > this problem?? It's not specific to Python or minidom. & and <> are reserved characters in SGML/HTML/XML. & => & < => < > => > Oren From thoa0025 at mail.usyd.edu.au Sun Sep 15 05:56:38 2002 From: thoa0025 at mail.usyd.edu.au (:B nerdy) Date: Sun, 15 Sep 2002 09:56:38 GMT Subject: regular expression help [port] Message-ID: Greetings, this is a regular expression for an email address "^[a-z0-9_]+@[a-z0-9\-]{2,}\.[a-z0-9\-\.]{2,}$" i wish to valid a variable against this string. would someone be so kind to supply a few lines of code to do this? cheers From richie at entrian.com Fri Sep 13 03:49:41 2002 From: richie at entrian.com (Richie Hindle) Date: 13 Sep 2002 00:49:41 -0700 Subject: Smoothing a discrete set of data References: Message-ID: <8a6ba1da.0209122349.454a4991@posting.google.com> [ Explanation of moving averages and running medians ] > So, I hope this will help answer your question. Whether or not it answers Paul's question, it was an interesting and well-written explanation - many thanks for taking the time to post it! -- Richie Hindle richie at entrian.com From tjreedy at udel.edu Sun Sep 15 18:59:36 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Sep 2002 22:59:36 GMT Subject: representing a literal single slash References: <3D84E9F9.8090101@linux.ie> <3D84FEE6.90600@linux.ie> Message-ID: "Padraig Brady" wrote in message news:3D84FEE6.90600 at linux.ie... > > mystr = mystr.replace(r'\\', r'\') > > Emm this actually doesn't work. Why can't you: > s=r'\' > Is it a bug? Ref Manual 4.1: When an `r' or `R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase `n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation. Terry J. Reedy From sismex01 at hebmex.com Tue Sep 24 18:12:33 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Tue, 24 Sep 2002 17:12:33 -0500 Subject: List/Tuple bug or feature? Message-ID: It's one of python's features :-) For when you wanna write a long string, SQL for example: Query = "SELECT what, when, where, why " "FROM t1, t2, t2 " "WHERE t1.id = t2.id_t1 and t3.id_t2 = t2.id and t1.id_t2 = t3.id " "AND t1.answer = 'OK'" Kinda neat. -gus > -----Original Message----- > From: Mahesh Padmanabhan [mailto:news at nospam.eml.cc] > Sent: Tuesday, September 24, 2002 5:06 PM > To: python-list at python.org > Subject: List/Tuple bug or feature? > > > > Hi, > > I spent a lot of frustrating hours tracking this down and I am > confused as to why I see this behavior. > > >>> x = ('a' 'b') > >>> x > 'ab' > > >>> x = ['a' 'b'] > >>> x > ['ab'] > > As you might have guessed, I missed a comma between two elements in > a fairly large list. > > If this is a concatenation feature, how can I prevent something like > this happening in the future ? > > This is with Python 2.1.3 on Debian Linux. > > Python 2.1.3 (#1, Sep 7 2002, 15:29:56) > [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 > Type "copyright", "credits" or "license" for more information. > > TIA, > > -- > Mahesh Padmanabhan > > ------- > > Replace nospam with prana to email me. > -- > http://mail.python.org/mailman/listinfo/python-list > Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From michaels at one.net Wed Sep 18 07:51:31 2002 From: michaels at one.net (Michael Schneider) Date: Wed, 18 Sep 2002 07:51:31 -0400 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D881B66.1080200@something.invalid> Message-ID: <3D8868C3.9090005@one.net> Martin v. L?wis wrote: >Greg Ewing writes: > >>Last I heard, Christian was moving pieces of the C >>stack while there could be pointers to it in use. >> > >Yes, that's how stackless works, and that cannot change. > >>That's definitely dangerous, as he discovered when >>it broke Tk. >> > >What is the danger? A program crashes? It is dangerous to cross a >street at rush hour; sitting in front of a computer is rarely >dangerous. > >Stackless adds a few limitations as to what C extensions can do. If >those restrictions are followed, it won't crash. > >>I'd be very nervous about using Stackless until >>it stops doing that. >> > >Why is that? Those crashes can only happen if you use the stackless >modules (and only if you use them with a stackless-unsafe extension). >If you don't import stackless, no stack is copied. > This is an important point that I missed. I thought that a stackless python was always stackless, and that I would need to have two version of python around. 1) python.exe - normal python ( for TK) 2) pythonsl.exe - stackless python. Please correct me if I misintrepreted your statement above, but this is what I got out of it : "stackless python behaves the same as 'normal' python, until you import the stackless module. At that point, it becomes stackless python. This allows you to run 'stackless unsafe' modules with the same interpretor as stackless modules, in a predictable manner (as long as you don't import stackless, and an unsafe module)" Is this the correct understanding???? If so, this is really good news!!!!!!!!!! Thank you very much, Mike > ... good stuff cut > >Regards, >Martin > From owen at nospam.invalid Mon Sep 16 18:25:26 2002 From: owen at nospam.invalid (Russell E. Owen) Date: Mon, 16 Sep 2002 15:25:26 -0700 Subject: Python on MacOS X 10.2: a warning and instructions Message-ID: MacOS X 10.2 (Jaguar) breaks the fink installation of Python (due to moving the ncurses package). MacOS X 10.2 does include Python (at least if you install the Developer's CD, not sure otherwise) but it has no readlines support (i.e. no command recall) and no Tkinter support. I upgraded before I realized this, and needed python too much to wait for the fink binary, so I spent a day and a half figuring out how to do the installation (with help from the MacPython list). Instructions are at if you are unfortunate enough to need them. These instructions install a version that uses xfree86 (an X server) to display windows. However, a release version of the native aqua version of tcl/tk now exists (version 8.4.0) but so far the only binary installer is for 8.4a4, an older version. The source installer comes with no instructions and what I tried failed. If anybody gets Python with Tkinter to worth with the aqua version of tcl/tk 8.4.0 under MacOS 10.2, I would love instructions. -- Russell From klausman-un250602 at tuts.net Mon Sep 9 13:06:50 2002 From: klausman-un250602 at tuts.net (Tobias Klausmann) Date: 9 Sep 2002 17:06:50 GMT Subject: Python plugins References: <3D7C13B3.2070606@nospam.free.fr> Message-ID: Christian Tismer wrote: > If you executed a proper __import__, all modules and funcs should > be accessible in the normal way. > There is no need to exec. This is what I overlooked: the lowlevel interface to __import__ Thanks a lot for your help (to laotseu, too). Greets, Tobias From tim.one at comcast.net Fri Sep 6 23:29:52 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 06 Sep 2002 23:29:52 -0400 Subject: Larry Wall's comment on python... In-Reply-To: <3d796a95$1@news.sentex.net> Message-ID: [Peter Hansen] > Anyone know how long is the largest chunk of code Larry Wall has > actually written in Python? It was 23 lines longer than the largest chunk of code Guido has actually written in Perl. The difference is that Larry's code worked, and Guido's still doesn't. I suspect Larry may have taken a wrong lesson from that . > The fact he has to say "I think" about this issue implies he is > guessing. Maybe if he actually tried it he'd conclude differently. It was just a sound bite from an interview, and blocks aren't quite the same thing in Perl (for example, a Perl block can have its own variables, but a Python block can't). I bet that if Guido had designed Perl, it would still have curlies, and I defy anyone to prove that wrong. Heh. leave-rationality-to-the-rationals-this-is-language-design-ly y'rs - tim From anton at vredegoor.doge.nl Sun Sep 15 02:39:01 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 15 Sep 2002 08:39:01 +0200 Subject: How to represent sets References: <1VIg9.16142$5r1.654088@bin5.nnrp.aus1.giganews.com> Message-ID: On Sat, 14 Sep 2002 15:50:21 GMT, "Terry Reedy" wrote: >> I would like to reopen this discussion. > >I don't remember any pronouncement from Guido or anyone else closing >it, except perhaps with regard to what he will personally support. How about: discussion.close() discussion.open() Anton. From mihan at foss.kharkov.ua Wed Sep 4 09:00:55 2002 From: mihan at foss.kharkov.ua (Mykhaylo Sorochan) Date: Wed, 4 Sep 2002 16:00:55 +0300 Subject: forum for zope References: Message-ID: > but does there exist a newsgrup for zope centric items? There exists a forum www.zope-forum.org From mcherm at destiny.com Thu Sep 12 16:08:13 2002 From: mcherm at destiny.com (Michael Chermside) Date: Thu, 12 Sep 2002 16:08:13 -0400 Subject: Coding Style: Quotes References: <20020912144710.GA78280@hishome.net> Message-ID: Oren Tirosh wrote: > On Thu, Sep 12, 2002 at 02:25:11PM +0000, John Waycott wrote: > >>I'm curious if others have adopted any standards for choice of single vs. >>double quotation marks to delimit strings. [...] > > The default repr of a string uses single quotes unless the string > contains a single quote. Most of the time I use the same convention but > I'm not 100% consistent. > > For docstrings I always use triple double-quotes even if the docstring > fits in a single line. > > I use triple single-quotes to comment out blocks of code. This is very > useful since "if 0:" would require re-indentation. > > Oren Encouragingly, I use EXACTLY the same conventions and practices that Oren does, having developed them independently for the same reasons. -- Michael Chermside From cbrown at metservice.com Thu Sep 12 21:14:58 2002 From: cbrown at metservice.com (Colin Brown) Date: Fri, 13 Sep 2002 13:14:58 +1200 Subject: Project idea Message-ID: <3d813c12$1@news.nz.asiaonline.net> On 6/09/2002 I wrote: >>Hi >> >>If you are interested in a Windows platform project for automated testing >>then read on. >> >>There is an excellent freeware package "AutoIt" available from >>http://www.hiddensoft.com/AutoIt/ >>that provides a DLL module that could be readily interfaced to Python. >> >>"AutoIt" is a simple tool that can simulate key presses, mouse movements and >>window commands (maximize, minimize, wait for, etc.) in order to automate >>any windows based task (or even windowed DOS tasks). >> >>Combining these features with say the ability to produce checksums of >>snapshotted screen frames for >>test comparisons would provide the basis for a nice GUI regression test rig. >> >>Unfortunately I do not have the time to follow up on this myself so I thought >>I would pass it on. >> >>Colin Brown >>PyNZ On re-examination, this is even easier because the package already comes with an ActiveX component. Here is an example of how simple it is to use: Python 2.2.1 >>> import win32com.client >>> conn=win32com.client.Dispatch('AutoIt.Control') >>> help(conn) >>> conn.WinGetActiveTitle() u'Python (command line)' >>> conn.WinMinimize('Python (command line)','') & the window minimises! >From here on in even a beginner should be able to have some fun :) Colin From max at alcyone.com Wed Sep 18 22:23:54 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 18 Sep 2002 19:23:54 -0700 Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> Message-ID: <3D89353A.2EC1C052@alcyone.com> "daniel w. moore" wrote: > It's occurred to me after some brainstorming on the subject that the > C/perl construct > > a ? b : c > > can be arranged like this in python: ... > Has anyone put this to good use, i wonder? > Or have I just made a daring and heroic discovery in my own particular > idiom ;) Sorry, but no, this isn't new. A variation is mentioned in the FAQ and these two variants -- using and/or combinations and lambdas -- gets discussed in the group frequently. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ When you love somebody, you're always in trouble. \__/ Col. Sherman Potter Bosskey.net: Quake III Arena / http://www.bosskey.net/q3a/ A personal guide to Quake III Arena. From c6re at sdsumus.sdstate.edu Thu Sep 19 23:33:02 2002 From: c6re at sdsumus.sdstate.edu (Buckshot) Date: 19 Sep 2002 20:33:02 -0700 Subject: e vs exp()? Message-ID: <3a838998.0209191933.1f22e977@posting.google.com> Can anyone here explain why I'm getting different results from e**2 and exp(2)? Which is more accurate? Python 2.2 (#1, Mar 27 2002, 14:56:58) [GCC 2.95.3 20010315 (release)] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> from math import * >>> e**2 7.3890560989306522 >>> exp(2) 7.3890560989306504 From jdhunter at ace.bsd.uchicago.edu Mon Sep 23 11:13:49 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 23 Sep 2002 10:13:49 -0500 Subject: numpy array assignment In-Reply-To: (John Hunter's message of "Mon, 23 Sep 2002 09:58:15 -0500") References: Message-ID: >>>>> "John" == John Hunter writes: John> I have a 2 dimensional array X which is NxM and a 1 John> dimensional array v which is Nx1. I want to assign v to the John> k-th column of X This is what I've come up with so far -- if there is a better/faster way, please let me know.... import Numeric def putcol(k, Z, v): (n,m) = Z.shape Numeric.put(Z, k+m*Numeric.arange(n), v) def putrow(k, Z, v): (n,m) = Z.shape Numeric.put(Z, k*m+Numeric.arange(m), v) Z = Numeric.zeros( (3,5), Numeric.Float ) vc = Numeric.ones( (3,1), Numeric.Float ) vr = Numeric.ones( (1,5), Numeric.Float ) putcol(3, Z, vc) putrow(1, Z, vr) print Z From bruce_deletethis_dawson at cygnus-software.com Mon Sep 23 02:18:09 2002 From: bruce_deletethis_dawson at cygnus-software.com (Bruce Dawson) Date: Mon, 23 Sep 2002 06:18:09 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <%8ci9.138477$5r1.5541622@bin5.nnrp.aus1.giganews.com> Message-ID: <3D8EB212.1000104@cygnus-software.com> thp at cs.ucr.edu wrote: > Terry Reedy wrote: > > + "daniel w. moore" wrote in message > + news:33b491f.0209181820.17b6ea70 at posting.google.com... > +> It's occurred to me after some brainstorming on the subject that the > +> C/perl construct > +> > +> a ? b : c > +> > +> can be arranged like this in python: > +> > +> (a and [b] or [c])[0] > > + If you *know* that b will evaluate as True (perhaps because it is a > + non-null constant, then this can be simplified to 'a and b or c'. I > + first used this several years ago. > > But why use grotesque hacks in the first place? "a ? b : c" is a > well-established syntax for conditional expressions. Why doesn't > Python simply adopt it? > > Tom Payne I assume that there are reasons why it could clutter or make ambiguous the syntax - but I'm not expert. I find the (a and [b] or [c])[0] construct to obscure to be useful - the space it saves is wasted by the comment I have to put in to explain it. It occurs to me that the bool() built in function allows for what is - in my opinion - a cleaner solution. Easier for mortals to comprehend. Basically, construct a two entry list of the two items and then index that with your expression, converted to bool. The bool function is essential since there was previously no generic way of getting the true/false value of an expression. For example: Python 2.2.1 (#34, Sep 14 2002, 09:40:33) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> a = "Hello" >>> b = "Goodbye" >>> myString = "" >>> [a,b][bool(myString)] 'Hello' >>> myString = "Something" >>> [a,b][bool(myString)] 'Goodbye' From lee100 at sport.rr.com Fri Sep 20 08:14:00 2002 From: lee100 at sport.rr.com (Lee Gray) Date: Fri, 20 Sep 2002 12:14:00 GMT Subject: general thoughts References: Message-ID: Benjamin wrote: > the problem, in one word: coding. but now i don't know > what to programm. sounds weird, doesn't it? :) what > should i program?? A friend and I joked for years that we were going to learn C, but just couldn't get into it... because we didn't have a project or problem to solve with it! Although I never learned C, I finally did learn to program, and have often found myself in a short slump simply because I didn't have a project at the time. You need a problem to solve, or as the saying goes, "an itch to scratch". If you have that, and you enjoy using the language, you will find that fun again. Lee From max at alcyone.com Mon Sep 9 14:23:15 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 09 Sep 2002 11:23:15 -0700 Subject: random.shuffle question References: <3k4f9.7500$yt3.3831288@newssrv26.news.prodigy.com> Message-ID: <3D7CE713.93BC9FAF@alcyone.com> dsavitsk wrote: > why does this not work to shuffle part of a list? > > >>> l = [1,2,3,4,5,6,7,8,9] > >>> random.shuffle(l[4:8]) > >>> print l > [1, 2, 3, 4, 5, 6, 7, 8, 9] > > and more importantly, is there a better way to do this? random.shuffle shuffles the list you hand it, and when you create a slice of a list, that sublist is separate from the original list. So you're creating a new sublist, shuffling it, and then tossing it away. You could simply chop up the list, shuffle the part that you want, and then reassemble it: >>> import random >>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> lBegin = l[:4] >>> lMiddle = l[4:8] >>> lEnd = l[8:] >>> random.shuffle(lMiddle) >>> l2 = lBegin + lMiddle + lEnd >>> l2 [1, 2, 3, 4, 6, 5, 8, 7, 9] -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ The perfection of innocence, indeed, is madness. \__/ Arthur Miller Max Pandaemonium / http://www.maxpandaemonium.com/ A sampling of Max Pandameonium's music. From gustav at morpheus.demon.co.uk Tue Sep 10 15:35:43 2002 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: 10 Sep 2002 20:35:43 +0100 Subject: Smoothing a discrete set of data References: <3csmdso5.fsf@morpheus.demon.co.uk> Message-ID: <8z2963jk.fsf@morpheus.demon.co.uk> "Terry Reedy" writes: > "Paul Moore" wrote in message > news:3csmdso5.fsf at morpheus.demon.co.uk... > > I have a set of data, basically a histogram. > > Actually, the two examples you give are *not* histograms. A histogram > is a discrete frequency graph: how many numbers fit in each bit. Note > that binning numbers like this them tosses away any order and other > covariate info. Unimodal histograms are usually smoothed by moment > matching: mean, standard deviation, and possibly more. Thanks for the clarification. As became increasingly obvious to me as I read the various replies, I am not being adequately clear in my own mind what I'm trying to do. Part of this is a result of not thinking in the right terms (for some reason, I didn't see the question in terms of stats, even though I was thinking of things like averaging and regression...), and part is simply a matter of oversimplifying and losing the key details of what I'm trying to do. Given that this is basically statistics, it's ironic that I did maths as my university degree, and while I didn't do a lot of stats in my course, it was an area I had had a strong "amateur" interest in prior to doing the degree course. > > sampled IO rates on a machine > > - I want to look for trends (is IO higher overnight or during the > > day, > > If you take measurements (samples) every hour, for instance, you have > a time series. There are many books on this subject alone. Interesting - I'd heard of time series, but had never got far enough into the subject to get a proper feel for what they covered... > > etc) or fuel consumption for my car (do I use less fuel since I had > > the service). > > This is a standard question with standard methods. If you ignore > order and other covariates and group measurements as before and after, > a t-test or signed rank test would be appropriate. When you put it like that, it's so obvious!! I think I was so fixated on making the picture look like the point I was trying to make (too much time working with business graphics, where the graph is there to make a point, rather than to explain the facts :-() > > Normally, what I do with things like this is draw a graph, and try > > to spot the trends "by eyeball". But it feels to me like I should > > be able to write something which smooths the data out. I just > > don't see how > > As a statistician, I am a fan of eyeballing raw data (with appropriate > caveats about testing what you think you see) in addition to numerical > analysis. However, each statistical procedure is aimed as answering a > question (and many are based on some assumption about the data). So > you need to better formulate what you want to know. You're right. I think that applying some of the suggestions other posters made (low-pass filtering the graph, for example) would help to display some of the grosser trends better (I think that was another aspect of what I was looking for, but I see now that it *is* a separate aspect). Once I have that "feel", I need to get more analytical about specifics. Thanks for your suggestions, and for all the other posters' comments as well. This has reawakened an old interest for me, and I look forward to dusting off some of my old books and learning more... Paul. From joconnor at cybermesa.com Wed Sep 11 16:20:48 2002 From: joconnor at cybermesa.com (Fearless Freep) Date: 11 Sep 2002 13:20:48 -0700 Subject: need Python and Zope experienced programers References: <3d647529.27575997@news.earthlink.net> <15717.3618.449268.769068@gargle.gargle.HOWL> Message-ID: <7d3dc526.0209111220.35007fff@posting.google.com> Michael Chermside wrote in message news:... > Skip Montanaro wrote: > > You might want to post to the Python Jobs board: > > > > http://www.python.org/Jobs.html > > > > Unfortunately, it's for posting job LISTINGS only, not job REQUESTS. But > it seems I've found something anyhow (though without Python :-( ). For what it's worth, I'm an experienced Python programmer looking for work (part or full time, contract or permanant) Take care, Jay O'Connor joconnor at cybermesa.com From oren-py-l at hishome.net Wed Sep 4 07:38:26 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 4 Sep 2002 07:38:26 -0400 Subject: encryption (passwords) In-Reply-To: <3d75d115$0$221$4d4ebb8e@news.nl.uu.net> References: <3d75d115$0$221$4d4ebb8e@news.nl.uu.net> Message-ID: <20020904113826.GA71214@hishome.net> On Wed, Sep 04, 2002 at 11:29:15AM +0200, Gumuz wrote: > I am using network-sockets to communicate between two(or more) python > applications. I want to encrypt these messages, or at least a part of it > e.g. password and such. > > My limited understanding of encryption tells me that I need a 'key' to > decrypt stuff. So I figure that this key will bey written(hard-coded?) > somewhere in my Python-script and it needs to be known at both sides in > order to encrypt and decrypt. Somehow, I can't believe this is true. I can't > get over the idea that if my application becomes open-source anyone could > see the key and decrypt my messages. You can get secret communication without any prior agreement between the parties. The Diffie-Hellman key exchange protocol lets two parties communicating over an insecure channel create a shared secret and a passive listener will not be able to find it. Take a look at http://magaf.org/dh.py There is a catch, though: this gives you secrecy but not authentication. If you encrypt the data stream using this shared secret as a key you will be communicating in perfect secrecy with someone who may or may not be who you meant to communicate with. It could be someone pretending to be the other party (a man-in-the-middle attack) So secrecy has a technical solution, but it only moves the problem elsewhere. Authentication has *no* simple technical solution because it's more of a meatspace problem than a cyberspace problem. Any solution would depdend on lots of tricky assumptions about the users of the system, the potential threats and the environment in which it runs. Oren From rjones at ekit-inc.com Wed Sep 18 20:18:40 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 19 Sep 2002 10:18:40 +1000 Subject: Python equivalent to perldoc? In-Reply-To: References: Message-ID: <200209191018.40935.rjones@ekit-inc.com> On Thu, 19 Sep 2002 12:34 am, Thorsten Kampe wrote: > * Bob X > > > "Thorsten Kampe" wrote in message > > > >>> Shouldn't Python know its own libs? > >> > >> It does: > >> ,--- > >> > >> | Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on > >> | win32 Type "help", "copyright", "credits" or "license" for more > >> | information. > >> | > >> | >>> import pydoc > >> > >> `--- > > > > It doesn't...you are executing from with Python...I am trying to do a ViM > > script that executes it. > > So Vim doesn't doesn't know about Python's libs. No surprise. Actually, vim's been able to import and use python libs for a long, long time. There's no reason why vim shouldn't be able to hook into pydoc. Richard From justnotworking at yahoo.com Thu Sep 12 18:06:51 2002 From: justnotworking at yahoo.com (mowestusa) Date: Thu, 12 Sep 2002 17:06:51 -0500 Subject: Newbie Looking for direction Message-ID: I have never programmed in a language before. I have developed complex databases with Access (Office 95 version) just with the visual tools. I would like to learn a computer language or database as a hobby that I would use to keep track of things in my real job. I have worked through "Non-programmer's Tutorial for Python". I'm reading "Programming Python (First Edition, got cheap)" right now. Most of the programs that I would like to develop would be relatively simple databases. I have Access 95 and Paradox 10 (with runtime). I'm wondering if I'm going down the right path in learning Python or if I would be better served by just learning to use Paradox 10 well. The one problem I have with Paradox or Access is that they seem so slow. Even if you have a simple database it takes a long time to start up and run. I would also like to make things that I could share with colleagues who have no interest in programming, but could use some of the database tools I would develop for our line of work. So far it seems like I'm a long way away from being able to be productive with Python, but that maybe because my end goal is too complex. Any advise would be appreciated. mowestusa From Oschler at earthlink.net Sat Sep 21 16:52:00 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sat, 21 Sep 2002 20:52:00 GMT Subject: Can't suspend a thread? Message-ID: I was hoping to have a master thread that woke up and suspended several other threads dynamically, as needed. From the books I have, that seems to be impossible in Python? Is this true? If so, is there a workaround? thx From sludtke at bcm.tmc.edu Mon Sep 30 13:12:15 2002 From: sludtke at bcm.tmc.edu (Steve Ludtke) Date: Mon, 30 Sep 2002 12:12:15 -0500 Subject: XMLRPC calls don't work in threads, or rather, they don't play well with others ! (help) References: <3D97D190.9030003@bcm.tmc.edu> Message-ID: <3D9885EF.7020703@bcm.tmc.edu> Will Stuyvesant wrote: > [Steve Ludtke] > >>Both of the server.() calls prevent other threads from running > > > Um, do you really think they prevent other *threads* from running? Or > would it be the case that there can be only one server call being > handled at any time at a *specific url:portnumber*. I am currently using only 1 thread to make the XMLRPC calls. It still prevents other threads from running. I'm working on a script to demonstrate the problem. From LogiplexSoftware at earthlink.net Fri Sep 20 09:47:09 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 20 Sep 2002 06:47:09 -0700 Subject: More on Protecting Source Code In-Reply-To: <3d86b4a0$0$23173$afc38c87@news.optusnet.com.au> References: <3d86b4a0$0$23173$afc38c87@news.optusnet.com.au> Message-ID: <1032529629.7312.214.camel@localhost.localdomain> On Mon, 2002-09-16 at 21:50, Steven wrote: > "Security through obscurity is no security against a determined attacker" > > So, someone who is willing to hacka nd hack and hack away at your code, can > get at it, and this is true for things coded in assembler, C, Python or > Befunge. Most people aren't determined attackers, they're simply Joe Average > who needs to get a job done. And even Joe Average is able to download the cracked software from one of the many sites that exist to distribute such software. This is the problem: people think that they can protect their software from the "average" user, and they could except that the "average" user has the resources of the cracker community at his disposal. > An operating system is a complex beast, compiled into machine code its even > more complex, how many people out there are using an unlicensed copy of > Windows or Office? they didn't decompile, that would take skill, they just > copied it bit for bit and posted the registration key. True, but if skill is required and the software is worth it, someone will take the time and they get no greater joy than posting their work for others to see (and download). > Do a very very simple risk analysis. Who is your target audience, what is > the price of your software, will people bother going through your bytecode, > or will they just post the registration key to a website? Will stolen > software lead to a loss in revenue - or will those pirate users be people > who would never have bought it in the first place? (yes, the pirate users > are annoying, and you would feel ripped off, but OTOH you haven't lost > money, and you've gained a bunch of users) Very true. Microsoft benefited greatly from this stance (not worrying too much about unlicensed copies of Windows and other applications). Not enforcing a copyright is a quick way to get something to become a "standard". You can always enforce the copyright later, when everyone is dependent on your software (again, see Microsoft). -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From robin at jessikat.fsnet.co.uk Wed Sep 4 13:10:07 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 4 Sep 2002 18:10:07 +0100 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> Message-ID: In article <3d76366a$1_5 at news.bluewin.ch>, Samuele Pedroni writes >From: Robin Becker >> A colleague has been running tests of reportlab under jython-2.1 several >> of the tests use prodigious amounts of memory (one even failed). We're >> using win2k+j2sdk1.4.0_01 as the jython engine. >> >> Anyone know what sorts of things cause x10 memory usage? I find one >> particular test needs more that 1Gb and then falls over for lack of >> memory. > >That means you are running jyhton through: > >java -mx1024m -cp ...jython.jar org.python.util.jython ... > >and it uses all that memory and would need more? > >regards. > > well actually we're running with the default jython.bat which doesn't seem to specify a memory, 1Gig is probably the default or maybe I ran out of page space. The python process never gets over 90Mb grrrhhhh. -- Robin Becker From klausm0762 at yahoo.de Wed Sep 25 05:13:07 2002 From: klausm0762 at yahoo.de (Klaus Momberger) Date: 25 Sep 2002 02:13:07 -0700 Subject: Python Compiling References: Message-ID: <80a8af7d.0209250113.28ae4c72@posting.google.com> "Terje Johan Abrahamsen" wrote in message news:... ..... > > Is it not possible to write a complete compiler like the C compiler for > Python? Or is it just that nobody has done it? Or must the language be > constructed differently? > Slightly off-topic, but if you are looking for a language which can be run by an interpreter and can be compiled as well, maybe you should take a look at Ocaml: http://www.ocaml.org -klaus From marklists at mceahern.com Thu Sep 26 11:02:17 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 26 Sep 2002 10:02:17 -0500 Subject: revenge of the python puzzle In-Reply-To: Message-ID: [Michal Wallace] > Oh well. :) I think this is just not a good way to make a > python puzzle. > > I guess I could avoid all keywords with something like this: > > open("/dev/stdout","w").write("hello world") > > and then try to make it as convoluted as possible, but then > it's not really cross platform. > > Was it obvious what it did? :) One man's obvious is another man's enigma. I thought it was a fine puzzle. Another way to make it harder would be to scramble all characters. // m From sismex01 at hebmex.com Mon Sep 9 10:50:38 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 9 Sep 2002 09:50:38 -0500 Subject: xml.minidom is stripping out my CRLF's in attrib values!! Message-ID: > > All line breaks must have been normalized on input to #xA > > as described in 2.11 End-of-Line Handling, so the rest of > > this algorithm operates on text normalized in this way. > > > > Begin with a normalized value consisting of the empty string. > > > > For each character, entity reference, or character reference in the > > unnormalized attribute value, beginning with the first and continuing > > to the last, do the following: > > > > For a character reference, append the referenced character to the > > normalized value. > > > > For an entity reference, recursively apply step 3 of this algorithm > > to the replacement text of the entity. > > > > For a white space character (#x20, #xD, #xA, #x9), append a space > > character (#x20) to the normalized value. > > > > For another character, append the character to the normalized value. > > > > If the attribute type is not CDATA, then the XML processor must > > further process the normalized attribute value by discarding any > > leading and trailing space (#x20) characters, and by replacing > > sequences of space (#x20) characters by a single space (#x20) > > character. > > > > Note that if the unnormalized attribute value contains a character > > reference to a white space character other than space (#x20), the > > normalized value contains the referenced character itself > > (#xD, #xA or #x9). This contrasts with the case where the > > unnormalized value contains a white space character (not a > > reference), which is replaced with a space character (#x20) > > in the normalized value and also contrasts with the case where > > the unnormalized value contains an entity reference whose > > replacement text contains a white space character; being > > recursively processed, the white space character is replaced > > with a space character (#x20) in the normalized value. > > > > All attributes for which no declaration has been read should be > > treated by a non-validating processor as if declared CDATA. > > > > So the only way to get a newline into an attribute is to > escape it in using an entity reference. > WOOHOO!! Thanks Duncan, miniXML grows by the minute! -gus pd: For those wondering, "miniXML" is a tiny pure-Python implementation of an XML tokenizer (a generator), a parser (a class which uses the tokenizer) a document-object class (for in-memory access, read-write), an event-processing class (for streaming), an object pickling mixin class, and some other stuff tossed in for good measure. For those times when you don't need the big guns. -gus -- Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From emile at fenx.com Wed Sep 11 10:50:12 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 11 Sep 2002 07:50:12 -0700 Subject: EDI parsing References: <746127ef.0209110128.53665a23@posting.google.com> Message-ID: Onno Ebbinge: > I'm writing an application (in Python) that is part of a bigger > infrastructure for B2B messaging. One communication channel is an EDI > interface to the B2B messaging system. > > I need to parse a (subset) of the UN EDIFACT (aka EDI) standard > (homepage: http://www.unece.org/trade/untdid/welcome.htm). After doing > the initial reading of the standard it looks like it is quite hard to > make a parser for this standard (and 'constructor'). My experience is with the UCC UCS standards, so some of this may be different in the UN standard. Once you have the full specification of the documents you'll be exchanging in a form that python can digest, it's not that hard to build the parser and/or constructor. The full specs are available to members on CD in PDF form. I once wrote an extremely ugly extraction utility that preprocessed using pdf2text and then parsed the resulting mess into something I could then use as something like from edixn import EdiXn for source in sourcemessages: tempIn = EdiXn(source) where sourcemessages is a python list of the individual transactions extracted from the edi envelope. EdiXn knew about 810, 850, 852, 855, 875 and 880 transactions, allowing me to write appropriate handlers for each type. > > My questions: > > 1) Is there a python EDI module? I can't find any :( I didn't then either. > 2) Is there a (python) EDI to XML converter? That wouldn't be hard. If there's already a DTD for edi, that would help a lot. ;-) > 3) Is there anything that I can use to easily interface with EDI? > (preferably in lib and DLL form) Try some of the commercial suppliers. There's big money (both expense and potential) in this, and that's probably why we don't find implementations strewn about the web. > > If the above is not available or fails... > > [You have to know that I've never written a parser in Python before. > The last (big) parser I wrote was in C with a few years back the help > of lex and yacc if memory serves me right.] > > What is the best approach to writing an EDI parser in Python? > To parse the received messages, I've always found it easiest to use and parse the raw ascii coming in. There are commercial packages that allow you to map and export or even map-to-map import, but as most of the customers I've done this for were typically forced into it by demands of the channel, and the commercial offerings rarely seemed as nimble as simply writing a one-to-one utility taking the edi order to the database or the resulting invoice to edi. I have generally used a commercially available transport package, KMart at that time being the notable exception. Outbound messages follow suit. If you are writing this as a part of a portable b2b application then you've got your hands full as you've entered the map-making utility supplier market. You'll need to address the entire specification, which my hardcopy of my deprecated 003050UCS shows to be some ~1000 _dense_ pages. Make sure you've got the funding to do it right, as this is no low-budget add-on. The 'edi specification' always felt akin to the 'rs232 specification' to me, only instead of 25 pins to muck up, they offer 100s. Not-sure-how-this-could-help-ly y'rs, -- Emile van Sebille emile at fenx.com --------- From skip at pobox.com Wed Sep 4 14:37:07 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 4 Sep 2002 13:37:07 -0500 Subject: Why read-only nested scopes? In-Reply-To: References: Message-ID: <15734.21203.49404.785473@12-248-11-90.client.attbi.com> Gon?alo> So why hasn't this been extended when nested scopes were Gon?alo> introduced, e.g. by reusing the global directive or some other Gon?alo> one? Martin> I think the main reason is that nobody could propose an Martin> acceptable syntax. Reusing the global directive does not work. For the gory details, read PEP 227: http://www.python.org/peps/pep-0227.html especially the section entitled "Rebinding names in enclosing scopes". -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From joec at mill.co.uk Mon Sep 2 12:52:00 2002 From: joec at mill.co.uk (Joe Connellan) Date: Mon, 02 Sep 2002 17:52:00 +0100 Subject: compiling extensions on linux References: <3D738D4E.35B6C712@mill.co.uk> Message-ID: <3D739730.DEB80478@mill.co.uk> it does have a initmyextension declared - Here's a simple example of my problem - I've taken all c++ related stuff out so I can use gcc #include "Python.h" #include int converter(void *from, unsigned long *to) { to = (unsigned long*)from; printf("%d %d %d", to[0], to[1], to[2]); return 1; } static PyObject * myextension_printHi(PyObject *self, PyObject *args) { printf("Hi\n"); Py_INCREF(Py_None); return Py_BuildValue(""); } static PyMethodDef myextension_methods[] = { {"printHi", myextension_printHi, 1, "printHi() doc string"}, {NULL, NULL} }; void initmyextension(void) { Py_InitModule("myextension", myextension_methods); } $ gcc -shared -o myextension.so myextension.cpp -I/usr/local/dist/Python-2.2.1/Include/ -I/usr/include/python2.2/ Python 2.2 (#1, Apr 12 2002, 15:29:57) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-109)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import myextension Traceback (most recent call last): File "", line 1, in ? ImportError: dynamic module does not define init function (initmyextension) >>> Thanks for the help Joe "Martin v. L?wis" wrote: > Joe Connellan writes: > > > I'm trying to port an extension of mine from windows to linux and am not > > sure how to include the myExtension.def file in the compile > > You shouldn't have a .def file in the first place - I recommend that > you use distutils instead. > > > eg if I use > > > > g++ -shared -o myextension.so > > > > it compiles fine but I get the following error when importing it into > > python > > > > >>> import myextension > > Traceback (most recent call last): > > File "", line 1, in ? > > ImportError: dynamic module does not define init function > > (initmyextension) > > Nothing to this respect is needed on Linux. Are you sure your module > does define a initmyextension function? > > It might be that it defines initmyextension__Fv instead, since you > compile your extension as a C++ program. > > You should compile it as a C program, unless it really is a C++ > program, in which case you need to define the init function as extern > "C". > > HTH, > Martin From rsrchstr at msn.com Mon Sep 30 18:05:59 2002 From: rsrchstr at msn.com (mike henley) Date: Mon, 30 Sep 2002 23:05:59 +0100 Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> Message-ID: actually, featureprice.com offer a good service; they support perl, php, python, tcl. "Bart Van Hemelen" wrote in message news:ujihpu0gvloetcsadfeg706rcs64o51mjj at 4ax.com... > In the dim and distant past on Mon, 30 Sep 2002 00:40:24 +0100, it was > rumoured that "mike henley" spake thus on the > subject of "Re: idea for a much needed application" in comp.lang.perl: > > >"other than the ones already present on a web-server", exactly! i want to be > >ably to use whatever language, modules or applications i choose, and over > >the year use others, freely. if i choose perl, php, or even python, ruby or > >tcl, then i want to be able to do that. > > Would be sys admin hell. > > Quite frankly, you'd probably be cursing about your hosting service > being crap because this would cause so much hassle to the people who > have to keep the servers running (patches and upgrades to software, > plus scripts by inexperienced users going haywire). > > I know that if I'd was working at a firm offering such things, they'd > have to pay me a lot since it woudl mean I'd have to be extremely good > at a whole lot of things, which in turn would mean expensive > subscriptions for users. > > -- > Bart Van Hemelen > http://pr1nc3.com/BVH/ > -------------------------------------- > Life would be a lot easier if you could take a > look at the source code every once in a while. From paul at boddie.net Wed Sep 4 04:11:51 2002 From: paul at boddie.net (Paul Boddie) Date: 4 Sep 2002 01:11:51 -0700 Subject: https in Python? References: Message-ID: <23891c90.0209040011.7d9e972@posting.google.com> Gerhard H?ring wrote in message news:... > > > s_gherman at yahoo.com (Sorin Gherman) writes: > > > >> Is it possible to handle https using Python's libraries? > > See my page http://www.cs.fhm.edu/~ifw00065/pyssl/index.html for > Windows. See also Robin Dunn's page: http://alldunn.com/python/ I've had some success with the Python 2.1 libraries, and they have the advantage that you don't need to abandon the usual APIs to use https with them; that seems to be the case for M2Crypto, for example. > I wonder why ActiveState doesn't provide SSL support with their Python > distribution. I thought they want to distinguish themselves by adding > value ;-) I can imagine that there's still some paranoia about shipping built-in cryptography, even in jurisdictions which don't prohibit such exports. Also, it's additional workload for those responsible, since there are certain special obligations in providing up-to-date, secure, reliable implementations of crypto packages. Paul From Padraig at Linux.ie Fri Sep 6 08:46:44 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Fri, 06 Sep 2002 12:46:44 GMT Subject: tree data structure References: Message-ID: Duncan Booth wrote: > Padraig Brady wrote in > news:FM0e9.2860$cP3.6165 at news.iol.ie: > > >>Hi, >> >>I've a graph like stucture represented >>by a list of tuples: >> >>[(L0,S2), (S2,S0), (S2,S1), (S1,Q2), (S0,Q1), (S2,S3)] >> >>And would like to convert it to >>a tree structure like: >> >> S0 - Q1 >> / >>L0 - S2 - S3 >> \ >> S1 - Q2 >> >>Any tips appreciated. >> > > Does this help? > > data = [('L0', 'S2'), ('S2', 'S0'), ('S2', 'S1'), ('S1', 'Q2'), ('S0', > 'Q1'), ('S2', 'S3')] > > # Produce a tuple where each node contains its name > # and a list of its child nodes: > # (node, [child1, ...]) > nodes = {} > for parent, child in data: > nodes.setdefault(parent, (parent, > []))[1].append(nodes.setdefault(child, (child, []))) > > result = nodes[data[0][0]] > > assert result==('L0', [('S2', [('S0', [('Q1', [])]), ('S1', [('Q2', [])]), > ('S3', [])])]) > > It certainly does! Just one thing...Why use lists instead of tuples? thanks, P?draig. p.s. I am completely amazed by Python. What is it now.. 4 hours and 43 minutes and I've learnt Python enough (from the web docs) to be able to parse a "graph format" text file and outputting XML (albeit with a little help :-)). Fantastic! From whisper at oz.net Tue Sep 17 15:38:30 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 17 Sep 2002 12:38:30 -0700 Subject: Earing money with Python software (was: More on Protecting Source Code) In-Reply-To: <4jt7ma.fse.ln@lenashee.goebel-consult.de> Message-ID: In my actually having done it experience, utilities and tools are a hard sell. The market is small and developers tend to get along without or build rather then buy unless it's just too good to do without. Developers have a habbit of 'sharing' good tools too - heh. Offering commercial support would be my suggestion. The efbot could probably give you chapter and verse on that! David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Hartmut Goebel > Sent: Tuesday, September 17, 2002 11:51 > To: python-list at python.org > Subject: Earing money with Python software (was: More on Protecting > Source Code) > > > Martin v. Loewis wrote: > > > For software, I think the economical risk is that somebody uses your > > software without giving you the money you want - not that somebody > > sits down and studies your code for days, to write a program that he > > could have written himself from scratch in the same time. > > Which brings me to another (related) topic): How to earn money > distributing Python software? > > I'm currently trying to make up my mind about exactly this problem > area: How can I get some reward back when writing software like > decompyle and bridgekeeper? > > I would be very gald if someone could share his/her experiances on > this topic! > > - Sell it via micro-payment? > - Declare it "Shareware" and hope somebody pays for it? > - Offer commercial support? > - Develop two different versions, a "free" one which is missing some > features and a commercial/registered/supported one offering more > sophisticated functionallity? > > (Any other comments are welcome, too.) > > Regards > +++hartmut > -- > | Hartmut Goebel | h.goebel at crazy-compilers.com | > | crazy-compilers.com | compilers which you thought are impossible | > -- > http://mail.python.org/mailman/listinfo/python-list From loewis at informatik.hu-berlin.de Mon Sep 9 03:48:12 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 09 Sep 2002 09:48:12 +0200 Subject: Difference between static method and a function as a class attribute? References: Message-ID: Gon?alo Rodrigues writes: > Haaaa (a light goes on in an otherwise dark and empty skull) so the > function is implicitely mutated into an unbound method! Wasn't aware of > this, thought that Python did nothing at all and that is why I asked - > Always learning new things. Yes. Guido once phrased this as "functions become methods *on the way out* of the class". This has surprised me at first as well, but I now consider it quite elegant, as it allows C.m = f where f is a function; C.__dict__['m'] will still be the function, but C.m will be a method (whose im_func is f). Regards, Martin From see_reply_address at something.invalid Sun Sep 22 21:28:40 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 23 Sep 2002 13:28:40 +1200 Subject: Avoiding referencing (was: Python sequences reference - problem?) References: Message-ID: <3D8E6E48.5070708@something.invalid> Thorsten Kampe wrote: > 2. "If you don't want referencing, call it with a copy of 'foo' like: > part(foo[:], [2, 3])" > > Yes, but how do I know in advance that 'part' modifies 'foo'? I might > not be the author of 'part'. But it ought to be clear from the documented purpose of 'part' whether it changes the object that you pass to it or not. It's generally expected that a function won't make changes to its arguments unless there's a good reason. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jason at tishler.net Mon Sep 16 14:00:57 2002 From: jason at tishler.net (Jason Tishler) Date: Mon, 16 Sep 2002 14:00:57 -0400 Subject: Accessing Windows Registry under cygwin In-Reply-To: References: <20020916164259.GG424@tishler.net> Message-ID: <20020916180057.GQ424@tishler.net> Henry, On Mon, Sep 16, 2002 at 06:18:19PM +0100, Henry S. Thompson wrote: > Jason Tishler writes: > > Are you willing to help? > > I wish I were competent to help -- I have no experience with > programming to WIN32 APIs. Hmm... You are the one with the itch... > I'll download the package and have a look. Now that's the attitude! > It's not entirely clear from the sourceforge log what's actually > needed next. Why not ask via the SourceForge Patch Manager? I'm sure that Martin or Jerry would appreciate any help. BTW, if you don't care about being portable with Win32 Python, then try using the following workarounds: 1. /proc/registry (but is read-only) 2. regtool (but spawns another process) Jason From dsavitsk at e-coli.net Mon Sep 16 01:22:29 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Mon, 16 Sep 2002 05:22:29 GMT Subject: Source code References: Message-ID: It is also worth repeating the often mentioned point that this is a job for intellectual property law. If your code is that valuable, run it on your server remote from end users as a trade secret, or force them to agree to a license and protect it w/ copyright. -d "Terje Johan Abrahamsen" wrote in message news:am3ms1$2e49b$1 at ID-53055.news.dfncis.de... > If I would like to write some code that would not be possible for others to > read, after I distribute the program, would Python be suitable? I know that > there are a few programs like Py2Exe, that creates .exe files. But, I also > saw this: > > -------------------- > A zip-compatible archive is built, containing all files from this > directory as well as your script, and appended to a custom python > interpreter supplied with py2exe. > -------------------- > > Doesn't sound like it is protected very well. Is there some alternative to > Py2Exe that can do the job, or should I look for a compiled language > instead? > > > From shifflett at nps.navy.mil Thu Sep 12 17:32:39 2002 From: shifflett at nps.navy.mil (David Shifflett) Date: Thu, 12 Sep 2002 14:32:39 -0700 Subject: Signals for GtkEntry widgets Message-ID: <3D8107F7.9090408@nps.navy.mil> I am trying to find which signal is emitted when the user presses Enter while in a GtkEntry widget. I finally found some online docs which listed the various signals for the various widgets at http://developer.gnome.org/doc/API/2.0/gtk/ Unfortunately, these are terse, mainly documenting the API, and not describing uses/functionality/etc IF someone could point me to a reference, or an example, it would be most appreciated Meanwhile I will keep hacking away until I stumble upon something that works Thanks in advance David Shifflett From blackhole at notformail.invalid.de Tue Sep 24 08:25:53 2002 From: blackhole at notformail.invalid.de (Volker Apelt) Date: 24 Sep 2002 14:25:53 +0200 Subject: callback + __call__ + TypeError: unbound method; on non method Message-ID: Hi, I have a problem with a stored function in a callback class object. I try to create a class (Callback) which accepts a function (a callable) as argument, stores it in an object attribute (self._m_func) and uses it in Callback's.__call__ function. The function stored is _not_ a method of of the calling class. I tried several types of calls to self._m_func but I allways end up in TypeError: unbound method call_me() must be called with instance as first argument I tried some other class (XXX) without a .__call__ method, which calls self._m_func and it succeeds. But I can't remove the .__call__ method from my Callback class. The method is essential for Callback, because an instance of it is used by some wrapped C-API function (not shown) to initiate some action on the python side of my code. Do you know what is wrong in the following example? I'm looking for an acceptable workaround or fix. -------------------------- demo code follows #!/usr/bin/python # -*- python -*- # python -v 2.1.1 on linux (Suse 7.3) import time # the called function def call_me(): return time.time # demo: this class works as expected class XXX: def __init__(self): #self.m_func = time.time self.m_func = call_me def callback_currTime(self): return self.m_func()() # becomes self.m_func() with time.time above def direct_currTime(self): return time.time() # defekt: this class doesn't class Callback: """ """ _default_Func = call_me # class wide default callback function def __init__(self): """ """ self._m_func = Callback._default_Func def __call__(self, case=None): """ """ ## do something before calling back ### -- left out ## all attempts end in this type error ## TypeError: unbound method call_me() must be called \ ## with instance as first argument ## find a valid form of calling the function stored ## in _m_func ## fazit: None was found if case is None or case == 1: return self._m_func() elif case == 2: return self.Func()() elif case == 3: C = self.Func()() return C() else: return "ignored" ## def useFunc(self,func=None): """ """ if func is None: self._m_func = Callback._default_Func else: self._m_func = func def Func(self): """ """ return self._m_func # ##### x = XXX() print x.direct_currTime() print x.callback_currTime() x = Callback() # try all cases for c in xrange(5): try: print x(c) except TypeError, e: print "CASE ",c,": ",e ## OUTPUT of this script #1032868956.78 #1032868956.78 #ignored #CASE 1 : unbound method call_me() must be called with instance as first argument #CASE 2 : unbound method call_me() must be called with instance as first argument #CASE 3 : unbound method call_me() must be called with instance as first argument #ignored # Local Variables: # (auto-fill-mode nil) # End: #end of file ---------------------- end of demo code run it to see the problems. thanks Volker -- Volker Apelt From martin at v.loewis.de Mon Sep 16 01:39:12 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Sep 2002 07:39:12 +0200 Subject: [xml] convert funny chars to char entites? References: Message-ID: ":B nerdy" writes: > ive got a string "Il Est N?" and i want to put it into a xml document > > is there a quick and easy way to conver the funny characters to char > entities so i can store them? I recommend you properly declare the encoding of the document, e.g. (assuming the ? is meant to be encoded in Latin-1). XML does not define external entities for non-ASCII characters, so you would have to create a DTD first if you want them. Regards, Martin From nospam at horvath.com Thu Sep 26 02:14:03 2002 From: nospam at horvath.com (Bob Horvath) Date: Thu, 26 Sep 2002 06:14:03 GMT Subject: combining mailbox and email modules References: Message-ID: Matthew Dixon Cowles wrote: > On Wed, 25 Sep 2002 06:36:29 GMT, Bob Horvath > wrote: > > >>I am having trouble figuring out how to get the mailbox and email >>modules to play together so that I can use email module functions on >>every mail in the mailbox. Is there a way to feed a factory from >>the email module to mailbox module? > > > Yes, there is: > > >>>>import mailbox >>>>import email >>>>i=mailbox.Maildir("Mail/testmail",email.message_from_file) >>>>i.next() >>> OK, I tried that. Looks like the email package is being picky about things where I can't see a problem. I keep getting the following error: email.Errors.HeaderParseError: Not a header, not a continuation Which I assume means a line that doesn't start with a space or tab that also does not contain a ':'. The problem is that it looks good to me. I've played around with it, and if I take out the MIME gunk (It actually is a Klez virus), it parses ok. Here is what happens... Python 2.2.1 (#1, Sep 7 2002, 14:34:30) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import email >>> fp = file('large') >>> msg = email.message_from_file(fp) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/email/__init__.py", line 35, in message_from_file return _Parser(_class).parse(fp) File "/usr/lib/python2.2/email/Parser.py", line 41, in parse self._parsebody(root, fp) File "/usr/lib/python2.2/email/Parser.py", line 134, in _parsebody msgobj = self.parsestr(part) File "/usr/lib/python2.2/email/Parser.py", line 45, in parsestr return self.parse(StringIO(text)) File "/usr/lib/python2.2/email/Parser.py", line 40, in parse self._parseheaders(root, fp) File "/usr/lib/python2.2/email/Parser.py", line 81, in _parseheaders raise Errors.HeaderParseError( email.Errors.HeaderParseError: Not a header, not a continuation >>> ... and here it the message... From mickey at verizon.net Tue Aug 20 10:03:52 2002 Return-Path: Delivered-To: bob at horvath.com Received: from localhost (bert [127.0.0.1]) by horvath.com (Postfix) with ESMTP id 9FE612A21D for ; Tue, 20 Aug 2002 10:03:51 -0500 (CDT) Delivered-To: horvath at enteract.com Received: from imap.enteract.com by localhost with IMAP (fetchmail-5.9.11) for bob at horvath.com (multi-drop); Tue, 20 Aug 2002 10:03:51 -0500 (CDT) Received: (qmail 40801 invoked by alias); 20 Aug 2002 14:58:55 -0000 Delivered-To: alias-horvath_com-bob at horvath.com Received: (qmail 40787 invoked by uid 0); 20 Aug 2002 14:58:53 -0000 Received: from out007pub.verizon.net (HELO out007.verizon.net) (206.46.170.107) by pop3-1.enteract.com with SMTP; 20 Aug 2002 14:58:53 -0000 Received: from Urn ([160.39.139.46]) by out007.verizon.net (InterMail vM.5.01.05.09 201-253-122-126-109-20020611) with SMTP id <20020820145852.GWSH1953.out007.verizon.net at Urn> for ; Tue, 20 Aug 2002 09:58:52 -0500 From: mickey To: bob at horvath.com Subject: Document.cookie MIME-Version: 1.0 Content-Type: multipart/alternative; boundary=B969j3A4oe4I6mIO538a14886om5n Message-Id: <20020820145852.GWSH1953.out007.verizon.net at Urn> Date: Tue, 20 Aug 2002 09:58:53 -0500 Status: RO X-Status: X-Keywords: X-UID: 52 --B969j3A4oe4I6mIO538a14886om5n Content-Type: text/html; Content-Transfer-Encoding: quoted-printable --B969j3A4oe4I6mIO538a14886om5n Content-Type: audio/x-wav; name=Wsr.exe Content-Transfer-Encoding: base64 Content-ID: TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAA=9 --B969j3A4oe4I6mIO538a14886om5n --B969j3A4oe4I6mIO538a14886om5n Content-Type: application/octet-stream; name=visa_nfl_espn_freq_JS[1].htm Content-Transfer-Encoding: base64 Content-ID: PGh0bWw+DQo8Ym9keT4NCjxzY3JpcHQgbGFuZ3VhZ2U9ImphdmFzY3JpcHQiPg0KIHZhciBC Cj== --B969j3A4oe4I6mIO538a14886om5n-- bert% From thorsten at thorstenkampe.de Fri Sep 13 13:17:49 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 13 Sep 2002 19:17:49 +0200 Subject: [ANN] PySQLite 0.3.0 released References: Message-ID: * sismex01 at hebmex.com >> From: Bob X [mailto:bobx at linuxmail.org] >> [Merciless Fullquote] > > Yeesh! You had to quote the whole message just to > add two words? That's nothing. Lately I've seen someone on the tutor list /quoting the whole message digest/ while replying to /a single message/. Now isn't that sweet? Thorsten From jstavnitzky at atsautomation.com Fri Sep 20 23:28:40 2002 From: jstavnitzky at atsautomation.com (Jay) Date: 20 Sep 2002 20:28:40 -0700 Subject: Porting woes References: <3a4b2539.0209200809.407d50d5@posting.google.com> Message-ID: <3a4b2539.0209201928.10c577b9@posting.google.com> > It checks whether the cls argument to classic_mro really is a classic > class. It is surprising that it calls into classic_mro. Can you tell > which line in Py_ReadyTypes comes from? (type, list, string, ...?) It occurs in the initialization of the type.. > It would be good to study the value of type, and tp_bases, at this > point. It might be that some initialization of global objects has > failed to happen, or has happened incorrectly. Thanks for the suggestion!! It appears as though this particular problem goes away if I extend the static initialization of the PyTypeObject PyBaseObject_Type to explicitly set the tp_bases value (and the other six values that are not explicitly assigned at the end of the structure to NULL). If I don't explicitly zero these values, they pick up whatever happens to be left over in those memory locations, is it possible that this is a compiler bug?? I assume that this code compiles correctly on most other compilers, or is zeroing out memory locations before use an operating system function?? I hope that there aren't other places in Python where structures are not fully initialized (and I may see a bug of this type again). Thanks, Jay loewis at informatik.hu-berlin.de (Martin v. L?wis wrote in message news:... > jstavnitzky at atsautomation.com (Jay) writes: > > > This failure is occuring during the function classic_mro(). The > > stack at that point is > > classic_mro(),mro_implementation(),mro_internal(),PyType_Ready(), > > PyTypeReady(),Py_ReadyTypes(),Py_Initialize(),Py_Main(). > > > > Help!! What is happening at this point, and what could be causing this > > assertion to fail? > > It checks whether the cls argument to classic_mro really is a classic > class. It is surprising that it calls into classic_mro. Can you tell > which line in Py_ReadyTypes comes from? (type, list, string, ...?) > > None of these are classic classes, so this code should not have been > executed. It appears that this was executed because of the test in > > if (PyType_Check(base)) > parentMRO = PySequence_List( > ((PyTypeObject*)base)->tp_mro); > else > parentMRO = classic_mro(base); > > i.e. base appears not to be a type. This, again, should not happen: > base is > > PyObject *base = PyTuple_GET_ITEM(bases, i); > > which in turn comes from > > bases = type->tp_bases; > > All base types of the types initialized in Py_ReadyTypes have only > types as bases, so it is surprising that one of them has a base which > is not a type. > > It would be good to study the value of type, and tp_bases, at this > point. It might be that some initialization of global objects has > failed to happen, or has happened incorrectly. > > Regards, > Martin From benji_75 at hotmail.com Fri Sep 13 05:46:14 2002 From: benji_75 at hotmail.com (Ben Gerblich) Date: Fri, 13 Sep 2002 19:16:14 +0930 Subject: no RHL 7.1 RPMs for python2.1 Message-ID: Why now does the RPMs for Python2 not appear on python.org? I am having trouble with my application core dumping. I have downloaded and installed the following on July2002: python2-2.1-5.i386.rpm python2-devel-2.1-5.i386.rpm python2-tkinter-2.1-5.i386.rpm python2-tools-2.1-5.i386.rpm wxPython-2.3.2.1-1-Py21.i386.rpm wxGTK-2.3.2-1.i386.rpm wxGTK-devel-2.3.2-1.i386.rpm using Red Hat Linux 7.1 Is there a known problem? BenG. _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From fgranger at alussinan.org Fri Sep 20 14:20:15 2002 From: fgranger at alussinan.org (=?ISO-8859-1?Q?Fran=E7ois_Granger?=) Date: Fri, 20 Sep 2002 20:20:15 +0200 Subject: python on the mac. References: Message-ID: <1fitsez.1wgbphvp6l8kmN%fgranger@alussinan.org> Guy wrote: > I have a script which I created on a win32 machine, I now want to port > it to a mac sys9x, python version 2.2.1. These pages will teach you all you need.... http://python.org/doc/current/mac/using.html -- YB> Phase 1: m?diter sur la question "Qu'est qu'une mauvaise herbe" ? JLV> surtout un jugement de valeur pl?onastiquement jud?o-chr?tien > et plus largement religieux YB> Monsanto est leur Dieu et Roundup est son proph?te ? From arturs at iidea.pl Wed Sep 11 13:41:34 2002 From: arturs at iidea.pl (Artur Skura) Date: Wed, 11 Sep 2002 17:41:34 +0000 (UTC) Subject: New text-mode ui library Message-ID: If you looked at (c)tinter and did not like it, you may check ntinter, a new text-mode UI library based on Python bindings for ncurses by Bartosz Lambach. It's available from http://iidea.pl/~arturs/ntinter-0.1.tar.gz (sample screenshoot: http://arturs.iidea.pl/b.png) -- only basic objects are implemented (Dialogs, Labels, Text Entries, Buttons), but it's quite useful. Regards, Artur -- http://www.amnesty.org.pl From bloke at ii.net Sun Sep 8 07:27:52 2002 From: bloke at ii.net (Rob Hall) Date: Sun, 8 Sep 2002 19:27:52 +0800 Subject: python program to watch a file - example. References: Message-ID: <3d7b3437$0$12727@echo-01.iinet.net.au> Get a fucking life Bengt!!! Bengt Richter wrote in message news:ales54$2un$0 at 216.39.172.122... > On Sun, 8 Sep 2002 01:47:12 -0400, "Wayne R" wrote: > > >This is a multi-part message in MIME format. > Why? > > > >------=_NextPart_000_0039_01C256D9.B8CB5320 > >Content-Type: text/plain; > > charset="us-ascii" > >Content-Transfer-Encoding: 7bit > > > > > >I am trying to write a python program that will run as a deamon and > >watch a file for data to arrive and then wake up and perform duties on > >that data. I found ways to make a python program run as a deamon but I > >am at a loss to find anything related to watching a file for data so > >that it can then process the data. I didn't really want to do a sleep > >loop or something like, I am sure there is a better way. > > > >Any ideas or links to more info? > > > Don't annoy people you want help from, for starters. > What system are you targeting? (Outlook in the headers says you're on windows > generating this abominable mix of actual message and useless cruft). > > >------=_NextPart_000_0039_01C256D9.B8CB5320 > >Content-Type: text/html; > WHY?!! > > Regards, > Bengt Richter From gerhard.haering at gmx.de Sat Sep 28 22:27:27 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 29 Sep 2002 02:27:27 GMT Subject: Fast-track to installing/implementing a SWIP module? References: Message-ID: Robert Oschler wrote in comp.lang.python: > I am a Python newbie so bear with me here. I just downloaded the PyProlog > package, which allows Python to access SWI-Prolog through a C-code SWIP > module. I just need the basics such as, proper directory to install files > and instructions for making sure the SWIP module can find SWI-Prolog, and > for making sure the package will run properly in Python. Is there a URL or > doc that can get me started? I would assume that I have to compile the 'C' > source for the SWIP module, and the resultant object file (.so?) in a proper > directory? These the kinds of questions I need to get answered. I read the > 3 README's in the PyProlog package but nothing seemed to suffice. If I understand correcly, you only have to have SWI-Prolog in your PATH, then the following: python setup.py build will build everything and python setup.py install will install your modules. Explanation: This function: def get_atom(atom): query = "pl -f none -g 'current_prolog_flag(%s, V), write(V), nl.' -t 'halt'" f = os.popen(query % atom) ... in setup.py should do the magic of finding the include and library paths to link against SWI Prolog. -- Gerhard From aleax at aleax.it Thu Sep 19 02:49:43 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 06:49:43 GMT Subject: monetary applications (et al) References: Message-ID: terry wrote: > >>>> Michael wrote: > for how to emulate numeric types. >>>> > > Right, I have looked at that. As near as I can tell there is a vast > difference between 'emulation' and 'intrinsic' - and the burden of that > difference falls on the programmer/customer in your assessment. The I don't understand what you mean. Where's the "vast difference", and what burden falls on the "programmer/customer"? If a type is not built-in (e.g.: cStringIO.StringIO, array.array, mmap.mmap, to mention a few non-intrinsic types distributed with core Python), then you need an "import something" statement. That's not deeply different from, e.g., needing an "import math" before you can compute trig functions (then you call math.sin, of course, not just sin). Is *THIS* what you consider "a vast difference"??? I can't think of anything else. Python users who need to compute trig functions have never squealed out load about the intolerable burden of having to "import math" to do so. On the contrary, people with such needs have developed a large, now widespread package called Numeric, which supplies a zillion facilities for such computations, and is used as a base by a large number of other, mode specialized computational modules. This substantial minority of Python users start almost all of their Python programs with "import Numeric" or "from Numeric import". Doesn't seem to have done any damage to Python's standing in the field of scientific computation -- on the contrary, decoupling the computational parts from Python's core allows the two parts to evolve and get released independently, thus benefiting both those who need such advanced maths, and those who couldn't care less. So what distinguishes the set of people who'd like a "currency" type from those who wanted advanced numerical maths -- except maybe that one set is more inclined to whining, the other, to doing something about it...? Alex From martin at v.loewis.de Wed Sep 18 00:45:30 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Sep 2002 06:45:30 +0200 Subject: Source code References: Message-ID: "Terje Johan Abrahamsen" writes: > If Py2Exe stores the source in pretty much open for reading, I need > to use another way of protecting it. Py2Exe does not store source code. Regards, Martin From robie at 1373.net Mon Sep 23 22:49:17 2002 From: robie at 1373.net (robie1373) Date: Mon, 23 Sep 2002 20:49:17 -0600 Subject: confusion about opening files References: <3d8fcda4$0$198$75868355@news.frii.net> <3D8FCFF3.FD52AFE5@alcyone.com> Message-ID: <3d8fd215$0$192$75868355@news.frii.net> O. K. Now I am confused. I thought that when I imported the os module, i would have to call its functions like this: os.open() Why am I just using the function name? "Erik Max Francis" wrote in message news:3D8FCFF3.FD52AFE5 at alcyone.com... > robie1373 wrote: > > ... > > file = os.open("e:\\d12", "r") > > TypeError: an integer is required > > > > I get this error if the mode is r, r+, a+ or whatever. I also get it > > whether the file exists or not. Can someone explain what I am doing > > wrong? > > You meant open, not os.open. > > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ > __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE > / \ Insight -- the titillating knack for hurting! > \__/ Colette > Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/ > A highly categorized list of Web links. From dreed at capital.edu Thu Sep 19 17:04:41 2002 From: dreed at capital.edu (Dave Reed) Date: Thu, 19 Sep 2002 17:04:41 -0400 Subject: monetary applications (et al) In-Reply-To: <3D8A161E.8060906@swbell.net> (message from Greg Goodman on Thu, 19 Sep 2002 18:06:57 GMT) References: <3D8A161E.8060906@swbell.net> Message-ID: <200209192104.g8JL4f816159@localhost.localdomain> > From: Greg Goodman > Date: Thu, 19 Sep 2002 18:06:57 GMT > On the other hand, cents aren't really indivisible in the American > marketplace, where stock prices often change by fractions of a dollar, > as in "General Motors down 2 and 1/8". I didn't realize the stock market was so bad that nobody looks at it anymore. :-) US stock exchanges have all been using dollars and cents for a while now. Dave From ark at research.att.com Fri Sep 27 19:28:49 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 27 Sep 2002 23:28:49 GMT Subject: What does Python fix? References: Message-ID: Adam> I'm curious to read a bit more about why Tim Peters (and presumably Adam> others) think that Lisp-inspired languages (even non-prefix ones) are Adam> doomed to eternal obscurity. Would anyone care to comment and/or give Adam> me some pointers to commentary on the subject? You might start here: http://www.ai.mit.edu/docs/articles/good-news/good-news.html -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From nospam at here Thu Sep 5 13:59:48 2002 From: nospam at here (Ricardo) Date: Thu, 5 Sep 2002 18:59:48 +0100 Subject: How to get os.popen subprocess PID? References: <3D775167.6060307@pp.htv.fi> Message-ID: <1031248567.61579.0@doris.uk.clara.net> > I have a subprocess opened with os.popen, producing undefined length of > data. I want to read maybe some of this data and then get rid of the > subprocess, not waiting until the end of data. I have thought of > os.kill-ing the process. So far I haven't been able to determine how to > get the pid of the subprocess, required by os.kill .. Any pointers? > Instead of using os.popen() you could import the popen2 module and use the Popen3 or Popen4 classes. Objects of these classes contain a 'pid' attribute. From wham10 at mad.scientist.com Mon Sep 16 06:57:28 2002 From: wham10 at mad.scientist.com (Srijak Rijal) Date: Mon, 16 Sep 2002 05:57:28 -0500 Subject: (no subject) Message-ID: <20020916105728.66744.qmail@mail.com> Hi all I just migrated from perl to python and was wondering if python socket can be read line by line too? How can I get only one line of input from the server without losing info? Thanxs in advance -- __________________________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup From marklists at mceahern.com Thu Sep 19 10:25:16 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 19 Sep 2002 09:25:16 -0500 Subject: strong/weak - dynamic/static [Was: Getting started] In-Reply-To: Message-ID: [sismex01 at hebmex.com] > Python is definitely NOT weakly typed, it's dynamicly-strong > typed. A variable, being only a "reference to *any* object" > may refer to any object, but that object (see the difference?) > may not change it's functionality or type during runtime. Whatchoo talkin' bout Willis? I don't have any practical use for the following, but it seems to demonstrate that what you said is not true... $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> class foo: ... def fooize(self): ... print self.__class__.__name__ ... >>> class bar: ... def barize(self): ... print self.__class__.__name__ ... >>> f = foo() >>> f.fooize() foo >>> f.__class__ = bar >>> f.fooize() Traceback (most recent call last): File "", line 1, in ? AttributeError: bar instance has no attribute 'fooize' >>> f.barize() bar // m - From grabiller at 3dvf.net Sun Sep 29 19:49:22 2002 From: grabiller at 3dvf.net (Guy Rabiller) Date: Mon, 30 Sep 2002 01:49:22 +0200 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <874rc8d9c9.fsf@nospam.eml.cc> <3d976fbc$0$23666$91cee783@newsreader02.highway.telekom.at> <8428na.7vj.ln@ix.netcom.com> Message-ID: <3d979184$0$20332$79c14f64@nan-newsreader-03.noos.net> [Dennis Lee Bieber wrote:] > Don't know if MS-DOS supports redirecting stderr. > On linux you'd use > > python -v script.py 2>output.txt yes it works on MS-DOS too. -- guy rabiller 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net Dennis Lee Bieber wrote: > Jurie Horneman fed this fish to the penguins on Sunday 29 September > 2002 02:26 pm: > >> Actually, I just tried this in a DOS shell under Windows 98: >> >> python -v script.py >output.txt >> >> It lists the verbose output straight to the DOS shell, not to >> output.txt. The output is useless, I can't scroll back. >> > I suspect -v output uses stderr, not stdout. > > >output.txt redirects stdout > > Don't know if MS-DOS supports redirecting stderr. On linux > you'd use > > python -v script.py 2>output.txt > > > However, for this situation -- ie, trying to debug your import > statement -- don't specify the full script on the command line. Do it > interactively with the output going to the screen. > > Oh, BTW... you NEED TWO "v"... python -vv > > >>>> import tmp.some #does not exist > # trying tmp.so > # trying tmpmodule.so > # trying tmp.py > # trying tmp.pyc > # trying /usr/lib/python2.2/tmp.so > # trying /usr/lib/python2.2/tmpmodule.so > # trying /usr/lib/python2.2/tmp.py > # trying /usr/lib/python2.2/tmp.pyc > # trying /usr/lib/python2.2/plat-linux-i386/tmp.so > # trying /usr/lib/python2.2/plat-linux-i386/tmpmodule.so > # trying /usr/lib/python2.2/plat-linux-i386/tmp.py > # trying /usr/lib/python2.2/plat-linux-i386/tmp.pyc > # trying /usr/lib/python2.2/lib-tk/tmp.so > # trying /usr/lib/python2.2/lib-tk/tmpmodule.so > # trying /usr/lib/python2.2/lib-tk/tmp.py > # trying /usr/lib/python2.2/lib-tk/tmp.pyc > # trying /usr/lib/python2.2/lib-dynload/tmp.so > # trying /usr/lib/python2.2/lib-dynload/tmpmodule.so > # trying /usr/lib/python2.2/lib-dynload/tmp.py > # trying /usr/lib/python2.2/lib-dynload/tmp.pyc > # trying /usr/lib/python2.2/site-packages/tmp.so > # trying /usr/lib/python2.2/site-packages/tmpmodule.so > # trying /usr/lib/python2.2/site-packages/tmp.py > # trying /usr/lib/python2.2/site-packages/tmp.pyc > # trying /usr/lib/python2.2/site-packages/Numeric/tmp.so > # trying /usr/lib/python2.2/site-packages/Numeric/tmpmodule.so > # trying /usr/lib/python2.2/site-packages/Numeric/tmp.py > # trying /usr/lib/python2.2/site-packages/Numeric/tmp.pyc > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named tmp.some > -- From sadams123 at optushome.com.au Thu Sep 12 12:25:08 2002 From: sadams123 at optushome.com.au (Steven) Date: Fri, 13 Sep 2002 02:25:08 +1000 Subject: win ce install References: Message-ID: <3d80bfe4$0$23171$afc38c87@news.optusnet.com.au> "Ell" wrote in message news:newscache$bonb2h$5w2$1 at lnews.actcom.co.il... > wince install > 1. > how I install python on wince ? Assuming you have the zip file with all the components copy python.exe to \Windows\Start Menu -this file might be called 'pocket pc python.exe' or something else, either way, it'll be the only executable file in there. You can copy python.exe to other locations in the Start menu e.g. Programs - don't use a shortcut to it, it won't work. Create a directory "\Program Files\Python" and copy the 'Lib' directory (And files) there - this directory is like the Lib directory on a normal python distribution, it holds all the modules. Copy the .pyd files win32event, win32api to the "\Program Files\Python" directory - I guess they could go in the Lib directory, but this is just my setup. Lastly, copy the dlls to \WIndows - this is PyWinTypes.dll and PYTHON22.dll I also have a copy of Python.exe in \Windows - I use that as the target for the python file associations I created in the registry. Having it in \Windows as well gives me a non-moving target, just in case I change where in the menu structure i keep python. I also went through and removed all the CVS related files to save space, other than a few modules, I only keep the compiled versions ('.pyc') in Lib, since it saves on space. > 2. > has somebody experience , python on wince ? > are all objects work as on win32 ? Which version of PythonCE are you using? 1.5.2 - Brian Loyds (?) port 1.5.2 - Mark Hammonds port 2.2/2.3 Brad Clements port Different versions had different parts working.Since i have an iPAQ there was no choice, version 2.2 for me - it does pretty much everything I want - except 'select'. Don't expect any easy to use GUI toolkits like wxPython or Tkinter, the only thing available at the moment is the win32 gui stuff - nowhere near as nice to use. > how is the performance ? depends, its much slower than normal Python on a desktop, but I've found Python slower on a lot of machines - whether that is the machines fault, or more work being down on Python on the x86, who knows. For comparison: AthlonXP 1800, 256MB, XP Pro - 21375.1 pystones/second Intel P133, 84 MB, Win98SE - 566.959 pystones/second iPAQ H3870, PocketPC 2002 - 100 pystones/second Benchmarks only tell so much, basically, yes, its slower, but its more than fast enough for using on the PocketPC. Try what you want to do, thats the only way to really find out if it can do what you want. hope tha helps Steven From cliechti at gmx.net Tue Sep 17 17:20:11 2002 From: cliechti at gmx.net (Chris Liechti) Date: 17 Sep 2002 23:20:11 +0200 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: lpgray at uop.com (Lee Gray) wrote in news:96904b50.0209171305.6d65f574 at posting.google.com: > My boss is pretty open-minded, but also needs to see something working > to be convinced Python is even a viable platform (he had never heard > of it). Otherwise, .Net is a given, whether it's any good or not, > since corporate is MS all the way. with python you have to choice of diffrent GUI libs. if you consider wxWindows you can play around with the wxPython demo application that comes with the download. on the other hand when you support win32 only the win32all package has support for all the windows APIs and it has some samples that get installed. chris -- Chris From tonyl at pillarsoftware.com Sun Sep 8 00:43:08 2002 From: tonyl at pillarsoftware.com (Tony Leotta) Date: Sun, 8 Sep 2002 00:43:08 -0400 Subject: C++ and Python Message-ID: <001401c256f2$3ab5e9f0$f46ede3f@THOTH> Does any one know of any examples written in C++ that use Python as a scripting language? I have been looking at VBA.but I don't know all that COM interfacing gets me down. :( I want to be able to export variables from C++ to the space that all the scripts will run.and have many different python scripts running inside different threads access/modify that data. so I will need locking mechanisms as each thread modifies the global data. I have been written extremely fast C++ servers have expanding pools of worker threads.and in each thread I'd like to be able to run scripts.I guess almost how Apache or IIS call PHP or VB Script. The difference is that I want each Python "script" to be able to communicate to other threads.something that Apache and IIS do not do. These will not be short lived threads.some be run for days. Thanks Tony Leotta http://www.pillarsoftware.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From loewis at informatik.hu-berlin.de Wed Sep 18 05:49:57 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 18 Sep 2002 11:49:57 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> Message-ID: Oren Tirosh writes: > They may be dangerous in some circumstances. IIRC, if a C extension > calls the Python interpreter recursively with pointers to things on > its stack it can cause memory corruption. Depends on your notion of "danger"; I usually associate it with fear and uncertainty :-) If you know it can crash when you do certain things, and you document that limitation, there is no danger. There are already ways to crash Python, the dlmodule being an example in the core distribution. Also, readers should notice that your example requires Stackless to be used: if no stackless module is imported, then accessing variables on the stack won't cause memory corruption. Regards, Martin From aleax at aleax.it Tue Sep 17 02:40:09 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Sep 2002 06:40:09 GMT Subject: threads or queue for this task References: Message-ID: James J. Besemer wrote: ... >>>Generally, Queues never get "full" and you generally don't care if >>>they're empty. >> >>You can define Queues that can hold a maximum number of items; [...] And I proceed to give a very detailed and rather realistic example. How come you don't address it at all? >>Setting size is just an optional embellishment, though >>sometimes it does pay dividends. > > Setting size has it's place but otherwise introduces unnecessary > complications. If it's not necessary (or at least helpful) it's unnecessary. Monsieur de La Palice would be proud of you. > Among other things, it forces the queue writer to deal > with the situation of what to do if the queue is full. Signal error > back to its client? Sleep and try again later? Silently discard the > request? Abort? Almost invariably, just as I said (and you snipped) and in the example I have, the reason you set a Queue to hold a maximum number of items is to have threads that post to it implicitly wait if it's full when they try to post. The situation is strongly parallel to dealing with an _empty_ queue -- normally, you just get items, and implicitly wait if it's empty when you try to get. > "Generally," NOT having a limit is by far the more elegant solution. I dispute the generality you assert, and, again, I gave a specific example: where the time to produce work-requests (posted to a queue) is always far less than the time to consume/process a work-request taken from the queue. This is hardly a RARE situation: on the contrary, it's quite a normal state of affairs that processing a work-request is much more time-consuming than producing it. Therefore, I consider your assertion "Generally, Queues never get *full*" a dangerous over-simplification: they get full if you specifically define them to have a maximum size (and post more items than you peel off), and it's not a rare case to want that ("an optional embellishment", as I said, but one that does happen quite normally in general cases). > Even in the general case, the queue may eventually grow to consume all > available memory if one doesn't have the CPU power to keep up with > requests. But, like most Python errors, this eventually will raise a > specific exception. If the number of work requests is not unbounded, you may be thrashing your computer into disgraceful performance rather than having your program fail with an exception -- wasting unbounded amounts of memory on an unbounded queue, where a single, simple call to make it bounded would solve it all like magic. It's not a matter how how much CPU power you have: strictly a ratio between how much time it takes to produce a work-request, and how much time it takes to process it. If that ratio, which may not depend on CPU power at all, is low enough (it was 1:10 in my example, certainly anything but an extreme case), using a queue of unbounded size will degrade performance horrendously (thrashing can slow your whole machine down almost unlimitedly, if you have virtual memory larger enough than physical memory) if there are enough work-requests. > Anyway, I felt the "general" case was more applicable to this novice's > line of questioning. He/she already was confounded by some > non-essential details. We disagree on didactics. I think over-simplification is a bad way to teach: everything must be kept as simple as possible, *but no simpler than that*. The parallels between a queue becoming empty, and one becoming full (when set to have a max size), are very strong, and may indeed HELP a bright novice grasp things better than if one tried to sweep half of the issue under the carpet. Alex From loewis at informatik.hu-berlin.de Mon Sep 23 05:45:38 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 23 Sep 2002 11:45:38 +0200 Subject: PyXML Building on OS X? References: Message-ID: Jarrett Wold writes: > If you want some sample output of the build I can certainly rerun > it and post it. Please do. No need to report the entire output, though - just the error messages and a little context is needed, such as the compiler line that caused the error message. Regards, Martin From mak at trisoft.com.pl Thu Sep 12 07:47:24 2002 From: mak at trisoft.com.pl (Grzegorz Makarewicz) Date: Thu, 12 Sep 2002 13:47:24 +0200 Subject: win ce install References: Message-ID: <3D807ECC.9000009@trisoft.com.pl> Ell wrote: > wince install > 1. > how I install python on wince ? Just unpack downloaded file with subdirectories and You will see where they cam from. > 2. > has somebody experience , python on wince ? > are all objects work as on win32 ? Python win has some troubles with unicode and not all win32* modules are ported to wince esp. gui,api. Depending on device type You may get problems with SH api - wince is not pocketpc, Jornada is not Symbol ,... Better get sources and compile for Your platform. > how is the performance ? :) ~ 20-80 % of C speed mak From fafhrd at datacom.kz Fri Sep 6 00:53:14 2002 From: fafhrd at datacom.kz (Nikolay Kim) Date: 06 Sep 2002 11:53:14 +0700 Subject: tuple problem Message-ID: <1031287998.6307.44.camel@fafhrd> hi. i have some problem. simple code >>> t = '\xba\xd0\xd7\xd0\xe5' >>> t '\xba\xd0\xd7\xd0\xe5' >>> print t ????? >>> print "%s" % t ????? >>> t is string in utf-8 encoding but after print it iso-8859-5 it's ok or error in python? From joel.quinet at be.unisys.com Thu Sep 26 04:06:16 2002 From: joel.quinet at be.unisys.com (Quinet, Joel) Date: Thu, 26 Sep 2002 03:06:16 -0500 Subject: Getting last char in string. Message-ID: <8D7B1A876CBBD2119E6A00105AC57EF005A38E72@BE-BRU-EXCH-1> Here under an example: s = 'abcd' print s[-1] d print s[-2] c Joel -----Original Message----- From: CheapSkate [mailto:gua81 at XXXyahoo.com] Sent: jeudi 26 septembre 2002 9:49 To: python-list at python.org Subject: Getting last char in string. Hi, im writing a simple method that takes in a string input and check if the last charcter is an '/' then it will do A else do B my Q now is how to get the last char??? Thanks -- http://mail.python.org/mailman/listinfo/python-list From tdelaney at avaya.com Tue Sep 3 20:33:34 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 4 Sep 2002 10:33:34 +1000 Subject: Pyrex 0.4.4 Message-ID: > From: pinard at iro.umontreal.ca [mailto:pinard at iro.umontreal.ca] > > I noticed too. To get going, I got Plex installed > separately, and removed the > 'Plex' line in `setup.py' for Pyrex. I decided against that, since one of the ficed bugs was in Plex. Tim Delaney From sgclift at earthlink.net Mon Sep 2 17:23:35 2002 From: sgclift at earthlink.net (Steve Clift) Date: Mon, 02 Sep 2002 14:23:35 -0700 Subject: urllib bug? Message-ID: <3.0.6.32.20020902142335.007d7bc0@mail.earthlink.net> I'm running Python 2.2.1 on a venerable W98 box. Attempts to use urllib.urlopen() to open trivial URLs fail with an exception 'no host given'. >From tracing through urllib: urllib.urlopen() instantiates an instance of FancyURLopener, which subclasses URLopener(). To figure out whether I'm using a proxy, urllib.URLopener.__init__() calls getproxies(), which is an alias for getproxies_registry() under Windows. getproxies_registry() ferrets around in the registry, using the _winreg module to extract values for ProxyEnable and ProxyServer. On this box, regedit lists the value for ProxyEnable as 00 00 00 00, and the value for ProxyServer as "". _winreg.QueryValueEx() returns ('\x00\x00\x00\x00', 3) for ProxyEnable and (u'', 1) for ProxyServer. Clearly, I'm not using a proxy. urllib tests the truth of '\x00\x00\x00\x00' and, because it's a non-zero-length string, incorrectly decides I *am* using a proxy and constructs bogus http and ftp proxy entries that include no host name. The absence of a proxy host name causes urllib to grumble. So, a) It's a bug. b) How come no-one else is complaining about it? What's special about this box? -Steve From deblnononospammmmmyyy at theworld.com Thu Sep 19 00:05:38 2002 From: deblnononospammmmmyyy at theworld.com (David Lees) Date: Thu, 19 Sep 2002 04:05:38 GMT Subject: Thanks guys Message-ID: <3D894D13.6029344C@theworld.com> OK, I see the PCbuild directory and the readme.txt. Thanks everyone for the pointers. David Lees From loewis at informatik.hu-berlin.de Fri Sep 20 16:11:19 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 20 Sep 2002 22:11:19 +0200 Subject: httplib 'getaddrinfo failed' References: Message-ID: "Gordon Williams" writes: > Same problem. Any ideas? I'm using Sympatico high speed edition which was > developed by Efficient Networks Inc. - if that is any help. Not really. More interestingly: What host are you trying to pass to the httplib? When you are trying to access that host, is your DSL connection up? Does a regular name lookup for this host (e.g. via tracert) work? etc. Regards, Martin From ehab_teima at hotmail.com Thu Sep 19 12:08:37 2002 From: ehab_teima at hotmail.com (Ehab Teima) Date: 19 Sep 2002 09:08:37 -0700 Subject: Database Modules to Connect to MSSQL Message-ID: <17aafe08.0209190808.3be7c11@posting.google.com> Hello, I am trying to use DB modules in Python to connect to MSSQL server. I found different modules but I could not find one for MSSQL. Anyone know which module I can use without having troubles. Thanks, Ehab From dgallion1 at yahoo.com Fri Sep 13 08:39:21 2002 From: dgallion1 at yahoo.com (Darrell) Date: 13 Sep 2002 05:39:21 -0700 Subject: Piper Pickling? References: Message-ID: Here's one approach I've used. Create an interface class for each class you plan to store. Also create the schema. --Darrell class A: """ Some data class """ _X1=9.2 _Y1="text" def __init__(self, *arg, **kw): self._x=1 self._y="hello" self._z=arg[0] self._range=zip(range(10),range(10,20)) def show(self): print '*'*10,self.__class__.__name__,'*'*10 for k, v in self.__class__.__dict__.items(): if not callable(v): print "%s: %s"%(k,v) for k, v in self.__dict__.items(): if not callable(v): print "%s: %s"%(k,v) class DbIforA(DbI): def __init__(self, objClass, schema, dbName=None, tableName=None): DbI.__init__(self, objClass, schema, dbName, tableName) def insert(self, *v, **kw): excludes= kw.setdefault("excludeCols",{}) excludes["_dbLocalTimeStamp"]=0 excludes['_dbLocalSerialNum']=0 apply(DbI.insert, (self,)+v,kw) def getValues(self): res=DbI.getValues(self) return res schema={ '_x':{'default':55, 'type':'integer'}, '_y':{'default':65, 'type':'varchar(30)'}, '_z':{'default':75, 'type':'integer NOT NULL', 'constraints':'Primary key '}, '_X1':{'default':None, 'type':'double'}, '_dbLocalTimeStamp':{'default':None, 'type':'TIMESTAMP(10)'}, '_dbLocalSerialNum':{'default':None, 'type':'integer not null auto_increment', 'constraints':'key'}, '_range':{'type':'pickle'} } dbI=DbIforA(A, schema, 'testDb', 'testTable') a1=A(1, x=3, y=4) a2=A(22, x=32, y=42) a3=A(33, x=33, y=43) # Some simple test cases dbI.dropDataBase(IF_EXISTS="IF EXISTS") dbI.createDb(IF_NOT_EXISTS="IF NOT EXISTS") dbI.use() dbI.createTable(IF_NOT_EXISTS="IF NOT EXISTS") dbI.insert(objs=[a1, a2, a3]) dbI.use() dbI.select() dbI.select(WHERE="where _X1 < 10.0 and _X1 > 9.0") ret=dbI.getValues() for i in ret: i.show() i._y='Dog' dbI.update(objs=ret) dbI.select() "Robert Oschler" wrote in message news:... > Forgive me :) > > If Peter Piper pickles a peck of Python packages, can he pack the pickled > Python peckers in a proper packing place? > > Translated: Anybody seen a module that can override the standard pickling > process and store and retrieve Python objects to a MySQL database? > > thx > > P.S. - Whell hell the language is named after the world's best comedy > troupe, what did you expect, green eggs and spam? :) From steve at ferg.org Thu Sep 12 21:45:27 2002 From: steve at ferg.org (Stephen Ferg) Date: 12 Sep 2002 18:45:27 -0700 Subject: ANN: Thinking in Tkinter References: <1a3a9ffa.0209120856.1de06f57@posting.google.com> Message-ID: aicolburn at yahoo.com (Alan C.) wrote in message news:<1a3a9ffa.0209120856.1de06f57 at posting.google.com>... > I enjoyed this tutorial. Thanks! > perhaps include a brief explanation early on about why you're > creating the program within a class structure. I'm embarrassed to say that I was just following a lot of the other tutorial materials that I have read. But to be honest, I can't really say WHY using a class structure is desirable. I have a vague intuition that the program will be more maintainable that way, but I can't clearly articulate the reasons. But you're absolutely right -- this is just the kind of issue I wanted to cover in "Thinking in Tkinter". Now I'll have to try to come up with an answer! > I think it > would be educational to distinguish between, say, > "self.button1Click()" and "self.button1Click" I don't know for sure, > but I bet there are folks who get confused distinguishing between > them. I think you're right. A good idea. From erikprice at mac.com Thu Sep 12 00:22:23 2002 From: erikprice at mac.com (Erik Price) Date: Thu, 12 Sep 2002 00:22:23 -0400 Subject: Use glob not re for regexp? In-Reply-To: Message-ID: <3CA22EAB-C607-11D6-9A79-00039351FE6A@mac.com> On Wednesday, September 11, 2002, at 08:02 PM, Robert Oschler wrote: > I saw a post where someone said to use glob not re for regular > expressions? > Is this true and if so why? I use Secret Labs regexp package. Filename globbing syntax is completely different from regular expression syntax. In some cases, generally when dealing with filenames, it is more familiar to some people (particularly Unix folk or shell programmers). But in general regular expressions provide far more control and precision over your patterns and matches. So, use whichever one you want. Erik -- Erik Price (zombies roam) email: erikprice at mac.com jabber: erikprice at jabber.org From tim.one at comcast.net Thu Sep 5 13:36:47 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 05 Sep 2002 13:36:47 -0400 Subject: Installing Python 2.2.1 on WinNT In-Reply-To: <75848aa7.0209050830.4024ebef@posting.google.com> Message-ID: [Phil Rittenhouse] > Thanks for the feedback Armin, that tells me there must be something > about my install of NT that's not quite right (or at least, not quite > the same as everyone else). > > I assume that the download file is OK because it installed fine > on 95, 98, ME, 2K, and XP without problems. > > In fact, I have just found that if I install Office 2000 first, the > python install on my NT works cleanly. There must be some magic that > the Office install does, maybe a DLL update, or permission change, that > allows it to work. Delighted to hear it finally worked! I'm afraid we're not much help with these when they go wrong: the PLabs installer is 100% vanilla Wise directives, with no custom code of any kind. So when something goes wrong, I'm afraid we're as clueless as the unfortunate user. Luckily, if you keep on buying enough new versions of Windows, the problem eventually fixes itself . From sfeil at io.com Mon Sep 23 21:45:29 2002 From: sfeil at io.com (Steven Feil) Date: Tue, 24 Sep 2002 01:45:29 GMT Subject: Three dumb questions (ordered by dumbness descending) References: Message-ID: On Mon, 23 Sep 2002 16:03:21 -0500, Thorsten Kampe wrote: > Okay, here they are: Ok, I'll take a stab at the first two questions. I do think that a little more clarity on your part could make it a bit easer. The first thing to remember is that Python is a dynamically typed language. It is typed and each object has a type, It would be a little easer if you would disclose the type for each object you are referring to. > 1. Why is 'zip(zip(x)) != x' (should be the same because it's the > transposed) Humm, what is is zip(), a function in the standard Python library or is it something you or someone else made up? I did a quick search in the Python docs and the only zip I found referred to zip compression. If this is something from the standard Python libraries please state the library it comes from. If zip is some general function, then in general, zip(zip(x)) is not equal to x. This comes from fundamental abstract algebra. In trig sin(sin(x)) is not x. There do exist functions who are there own inverse and if zip is one of them then zip(zip(x)) is equal to x. You mentioned transpose. If x is a matrix and the function zip only transposes x, then zip(zip(x)) is equal to x. This is because a transpose function is it's own inverse. I'm not sure where you got this zip function, but zip is suppose to transpose x and zip(zip(x)) != x then there is a bug in zip. Also if zip is a transposition function it can only act on arrays and it should raise an exception if x is not of the required type. I will need to know more about where you got zip from. > 2. Peter Norvig mentions in "Python for Lisp Programmers" some > "don'ts": "[x] + y" and "x[1:]". Are there more things to avoid humm, "[x] + y", again it comes down to type. [x] will always be a list. It will contain a single element x of whatever type x is. y on the other hand is whatever type y is (you haven't told me). In Python when I use "[x] + y" y must be another list, because when used with a list the + operated must have a second list to concatenate to the first. It is the way + is defined. If you wish to appended the list [x] with y you must have a reference to [x] such as z=[x] then append to it with z.append(y). A quicker way would be to start with [x,y] which would be equal to the z after you appended to it. z=[x] z.append(y) z == [x,y] The statement "x[1:]" this is legal if x is a list, or if x is some type in which index slicing has been defined. basically x[1:] means something that has every element that x has except for the first element. So if x = "steve" then x[1"] is "teve". ======================================================================== Steven Feil | Gram-pa, back at the turn of the .~. Programmer/Developer | century, why did people use an /V\ sfeil at io.com | operating system, when they were not // \\ | allowed to see the source code? (X_X) ======================================================================== From daniel.dittmar at sap.com Mon Sep 30 07:29:11 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Mon, 30 Sep 2002 13:29:11 +0200 Subject: is cPickle really this slow? References: Message-ID: Dag wrote: > I have a script which starts by parsing a large file and turning into > a data stucture (a dictonary of lists) which I then use in the script. > This operation however takes about 12-15 seconds. Since the file > hardly ever changes , and if it changes it's because I changed it, > thought I'd save some time by pickeling the datastructure and and > simply getting that at the start of each script. So I pickle my > dictionary, which ends up being a 3.2MB file and try to run my script > again, this time getting the pickled dictonary instead of building it > at runtime. This time however the script takes over 35 seconds to > run, close to three times as long. Am I doing something wrong is > loading and parsing larger pickled files really very slow. Have you used the binary option to 'dump'? dump(object, file[, bin]) : If the optional bin argument is true, the binary pickle format is used; otherwise the (less efficient) text pickle format is used (for backwards compatibility, this is the default). Daniel From kkuroda at crl.ucsd.edu Mon Sep 2 22:41:00 2002 From: kkuroda at crl.ucsd.edu (Kow Kuroda) Date: Mon, 2 Sep 2002 19:41:00 -0700 Subject: RedHat 7.3 and Python2.2.1 In-Reply-To: <3d74176d@news.sentex.net> Message-ID: <95469BCC-BEE6-11D6-B4E4-00050287C0A6@crl.ucsd.edu> On Monday, September 2, 2002, at 06:59 , Peter Hansen wrote: > Kow Kuroda wrote: >> On Monday, September 2, 2002, at 11:43 , Peter Hansen wrote: >>> Doug Farrell wrote: >>>> I'm trying to install the latest version of Python >>>> (python2-2.2.1-1.i386.rpm) from the www.python.org download page, and >>>> I'm having problems. When I run >>>> >>>> rpm -i python2-2.2.1-1.i386.rpm >>>> >>>> I get all kinds of conflict messages like this: >>>> >>>> file /usr/bin/pydoc2 from install of python2-2.2.1-1 conflicts with >>>> file from package python2-2.2-16 >>> >>> Sounds like you already have a previous version of Python2.2 installed. >>> You should probably be using the "-U" option to update instead of >>> the "-i" option to install... or uninstall the previous one first. >> I just wanted to make a comment on Peter's post. >> I think -U or --upgrade option works, but it's dangerious to uninstall >> Python 2.1, which is now part of Red Hat Linux 7.3, unlike in prevous >> releases where Python 1.5.2 or something is used for installation scripts. > > (Note he had a conflict with Python 2.2, not 2.1. It should work fine.) I actuall *did* have a big problem with 2.1 when I tried to install 2.2.1. I don't really remember all the error messages I got then. > Your comments about RH7.3 don't quite fit with my experience. I just > installed it (posting from the machine it's on, in fact) and "python" > executes 1.5.2 still, while "python2" executes 2.2, not 2.1. What am > I missing? Hmmmm, that's odd ... But unfortunatley, I cannot be very precise about what I exlained partly because I'm back to RHL 7.2 now. I had some embarassing experiences with RHL 7.3 including the problem I described in my comments. All I can say right now is just that I nearly gave up the idea of installing 2.2.1 on RHL 7.3 because of the overwhelmingly complicated situation with dependencies. Oh yes, I also tried to update "redhat-config-network" to the most recent version, (I needed it to add the wireless interface to "neat"). It requires a newer version of Alchemist package, writtin in Python 2.x. And Alchemist depends on a newer version of PyGnome, which depends on something, etc, etc. I admit that it's possible that my situation wasn't typical, but believe me, it's true that I got stuck in a very complicated situation caused by Python 2.2.1 installation on RHL 7.3. As a last thought, doesn't Red Hat have different versions of the 7.3 distribution? Kow From sandysj at juno.com Fri Sep 20 19:10:59 2002 From: sandysj at juno.com (Jeff Sandys) Date: Fri, 20 Sep 2002 23:10:59 GMT Subject: general thoughts References: Message-ID: <3D8BAB03.D65F3B7E@juno.com> Benjamin wrote: > hi everybody ... > i've been learning python not for becoming a programmer > ..., but for having fun. ... There was a Python inititive called CP4E, Computer Programming for Everyone. I believe that with the proliferation of computers in society that everyone should know how to write a computer program. Examples of some of Python's successes are in research organizations where computer scientists wrote the programs to do data analysis for the research scientist, now the research scientist can write thier own programs using Python and the computer scientist can work on bigger issues. Python is also being used in some schools like Logo was, to introduce all students to programming. Good Luck on your journey. Thanks, Jeff Sandys From gregory.p.green at boeing.com Fri Sep 20 12:54:52 2002 From: gregory.p.green at boeing.com (Greg Green) Date: Fri, 20 Sep 2002 16:54:52 GMT Subject: Python COM and variable number of arguments References: Message-ID: In this case I was using the makepy generated wrapper. I have M. Hammonds book and used the method of ensuring I was using the early-bound object. So am I out of luck even if I have the wrapper? -- Greg Green From uwe.schmitt at procoders.net Fri Sep 6 08:40:12 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 6 Sep 2002 12:40:12 GMT Subject: What database should I use References: Message-ID: A wrote: > Hello, > I am going to program a small application (in Python and wxPython) which consists about > 2000 - 3000 records . Can you please recommend which database is the best for that. I > use Windows. > Maybe MS Access or FoxPro or MySQL or better? > I want to keep the program as small as possible. > Thanks > Ladislav If your search tasks just rely on one index, the berkley db bindings can be recommended. It is very fast, leightweight and runs on many platforms. Look at anydbm, dbhash or bsdd in the Python module documentation. Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at num.uni-sb.de than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From salmonia.nospam.please at cardiff.ac.uk Wed Sep 18 08:07:29 2002 From: salmonia.nospam.please at cardiff.ac.uk (Alan James Salmoni) Date: Wed, 18 Sep 2002 13:07:29 +0100 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: Lee, I don't know if this is the kind of thing you are looking for, but I've written an application for statistical analysis (the scientific kind) which is available for download from http://salstat.sunsite.dk (screenshots are available too). It's GPL'd, but rather new so there are still some rough edges. The GUI was written using wxPython (absolutely fantastic IMHO - the learning curve is a bit steep to begin with, but shallows extremely quickly). Features: * A spreadsheet like grid for data entry/display * A html display window for the output of the analysis and the online help pages * Custom dialog boxes for each set of analyses * Standard dialogs (file open/save and font choser) * The GUI took a few weeks to write part-time and that was from scratch while learning wxPython. And I'm a psychologist, not a programmer, which means you will probably be up to speed in much less time ;). * A windows installer containing all the required program (ie, non-icon or help) files for a Windows box in one file (using the McMillan installer) * Cross-platform capability - Windows, Linux and OSX (the OSX wasn't even planned - it just happened to work!) Have fun! Alan. Lee Gray wrote: > I'm a fairly new programmer with experience in ASP/VBScript/DHTML. > Other than small utilities, so far I've mostly written ASP apps to > talk to an Oracle database on HP/UX, with Windows NT/2000 clients, and > I've done maintenance work on VB and Oracle Forms apps. > > We're currently looking at .Net, and I'm not very impressed, for a > variety of reasons. A little research makes me feel that either Java > or Python would be a good alternative, and given my level of > experience, I'd much prefer Python over Java. I *think* I could > actually get up to speed faster with Python than with VB and ASP.Net, > in spite of my ASP/VBS experience. > > My boss is pretty open-minded, but also needs to see something working > to be convinced Python is even a viable platform (he had never heard > of it). Otherwise, .Net is a given, whether it's any good or not, > since corporate is MS all the way. > > Can someone point me to a good Python GUI app to demonstrate (other > than IDLE)? > > It may very well be that .Net is best for me/us, but from what I've > seen of Python, I *really* like the language and I'd at least like to > see a good demonstration of a full-blown app before ruling it out. > (Something along the lines of what I mentioned above would be ideal, > but not a necessity.) > > Thanks! > > Lee Gray From trash at terastat.com Tue Sep 17 18:47:52 2002 From: trash at terastat.com (bap) Date: Tue, 17 Sep 2002 22:47:52 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: Actually both may be a solution. I've recently had good success at developing an with a VB (not .net) front end and doing most of the work in Python. Use each for what it's best at. Based on my experience with project, I'd say that Python take about 25% of the code of VB to accomplish the same objective. Plus Python objects tend to do what is expected so that you can often guess at the syntax and be right whereas this is seldom true with VB objects. Lee Gray wrote in message news:96904b50.0209171305.6d65f574 at posting.google.com... > I'm a fairly new programmer with experience in ASP/VBScript/DHTML. > Other than small utilities, so far I've mostly written ASP apps to > talk to an Oracle database on HP/UX, with Windows NT/2000 clients, and > I've done maintenance work on VB and Oracle Forms apps. > > We're currently looking at .Net, and I'm not very impressed, for a > variety of reasons. A little research makes me feel that either Java > or Python would be a good alternative, and given my level of > experience, I'd much prefer Python over Java. I *think* I could > actually get up to speed faster with Python than with VB and ASP.Net, > in spite of my ASP/VBS experience. > > My boss is pretty open-minded, but also needs to see something working > to be convinced Python is even a viable platform (he had never heard > of it). Otherwise, .Net is a given, whether it's any good or not, > since corporate is MS all the way. > > Can someone point me to a good Python GUI app to demonstrate (other > than IDLE)? > > It may very well be that .Net is best for me/us, but from what I've > seen of Python, I *really* like the language and I'd at least like to > see a good demonstration of a full-blown app before ruling it out. > (Something along the lines of what I mentioned above would be ideal, > but not a necessity.) > > Thanks! > > Lee Gray From news at nospam.eml.cc Tue Sep 24 18:06:10 2002 From: news at nospam.eml.cc (Mahesh Padmanabhan) Date: Tue, 24 Sep 2002 22:06:10 GMT Subject: List/Tuple bug or feature? Message-ID: <8765wv6o0d.fsf@nospam.eml.cc> Hi, I spent a lot of frustrating hours tracking this down and I am confused as to why I see this behavior. >>> x = ('a' 'b') >>> x 'ab' >>> x = ['a' 'b'] >>> x ['ab'] As you might have guessed, I missed a comma between two elements in a fairly large list. If this is a concatenation feature, how can I prevent something like this happening in the future ? This is with Python 2.1.3 on Debian Linux. Python 2.1.3 (#1, Sep 7 2002, 15:29:56) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. TIA, -- Mahesh Padmanabhan ------- Replace nospam with prana to email me. From spoermeg at voldelig.com Fri Sep 20 16:12:14 2002 From: spoermeg at voldelig.com (Terje Johan Abrahamsen) Date: Fri, 20 Sep 2002 15:12:14 -0500 Subject: Python Compiling Message-ID: First of all, I am going to warn you. I will ask some stupid questions. I haven't programmed too much, and don't really know how it all links together. But, I guess my question boils down to, why is not Python a compiled language? To my best knowledge, the computer understand 0s and 1s. So, any programming language must be brought down to that. Even assembler must be somewhat remade into computerlanguage. A compiler for for example C, will take my C code, and transform it into computerlanguage. The same does the intepreter for Python. However, the interpreter does that step every time I run the program, versus the compiler does it once, and gets it over with. So, for the computer, the computerlanguage that it runs doesn't really differ between if I wrote my code in Python and run it thru the intepreter, wrote it in C and compiled it, or wrote assambler and did whatever you do with assambler. So, when Guido made the first Python, he deceided he wanted an intepreted language, and wrote an intepreter. Could someone write a compiler and get Python to be a compiled language like C? I guess Py2Exe does to some extent that, but to my understanding it is not exactly the same as a complete compiler. It more just copies the files from the intepreter that the program needs. Is it not possible to write a complete compiler like the C compiler for Python? Or is it just that nobody has done it? Or must the language be constructed differently? Thanks for any help to clearify the subject. But please try to keep it understandable for also one with somewhat more limited understanding of the subject.... From see_reply_address at something.invalid Tue Sep 10 02:04:22 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 10 Sep 2002 18:04:22 +1200 Subject: random.shuffle question References: <3k4f9.7500$yt3.3831288@newssrv26.news.prodigy.com> <3D7CE713.93BC9FAF@alcyone.com> Message-ID: <3D7D8B66.6070903@something.invalid> Erik Max Francis wrote: > You could simply chop up the list, shuffle the part that you want, and > then reassemble it: Or for more fun, you could use the handy class attached below, and simply say: random.shuffle(sublist(mylist, 4, 8)) #------------------------------------------- class sublist: """sublist(x, i, j) is an object which behaves like x[i:j] except that changes to it are reflected in x. (This version only handles getting and setting single items.)""" def __init__(self, base, begin, end): self.base = base self.begin = begin self.end = end def __len__(self): return self.end - self.begin def __getitem__(self, i): return self.base[self.begin + i] def __setitem__(self, i, x): self.base[self.begin + i] = x if __name__ == "__main__": import random l = range(20) print "Before:", l random.shuffle(sublist(l, 5, 15)) print "After:", l #------------------------------------------- -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From see_reply_address at something.invalid Wed Sep 11 22:30:27 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 12 Sep 2002 14:30:27 +1200 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> Message-ID: <3D7FFC43.10002@something.invalid> Stephen Ferg wrote: > So it looks like the > correct mouse-button binding to replace "command" would be to bind to > . That's not quite right either, because the action should only be triggered if the mouse is released inside the button. > Is there any place where definitions or explanations > or discussions of standard button behavior are written down > and available? A book? A Web page? Apple publishes a Human Interface Guidelines document, which ought to be on their website somewhere. There's probably something similar from Microsoft. The generally accepted behaviour for a button on most platforms nowadays is: (1) Mouse-down in the button causes it to be highlighted in some way (changing colour, becoming "depressed", etc.) (2) As long as the mouse is held down, the button is unhighlighted when the mouse moves out of it, and re-highlighted when it moves back in. (3) If the mouse is released inside the button, the button's action is performed. If the mouse is releases outside the button, nothing happens. There's no single event binding in Tk that will give you all of this. There is code built into the Button widget that implements it, but to take advantage of it you have to use the "command" option. It's a fairly universal principle in Tk that the "command" of a widget is invoked according to the standard behaviour of that widget, so I think it deserves treatment as a fundamental principle on the same footing as event binding. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From kennethg at pd.jaring.my Fri Sep 27 11:44:49 2002 From: kennethg at pd.jaring.my (Kenneth Gomez) Date: Fri, 27 Sep 2002 15:44:49 GMT Subject: Local Python Server Installation References: <3d8b47c6.277669@news.jaring.my> <3d8c993c.2190426@news.jaring.my> <3d8d4009.375344@news.jaring.my> Message-ID: <3d947c26.2656654@news.jaring.my> Steve, I stumbled onto this problem while going through the first exmaple in the book Python:How to Progra, by Deitel, Deitel, Liperi and Wiedermann. My little code sniipet, copied exactly from the book except for the path to my python exe is : ________________________________________________ #!C:\prog\Python22\python.exe import time def printheader(title): print """Content-type: text/html %s """ % title printheader("Current Date & Time") print time.ctime(time.time()) print "" ___________________________________________________ I get the following error in IE6 : The XML page cannot be displayed Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later. -------------------------------------------------------------------------------- Invalid at the top level of the document. Error processing resource 'http://localhost/ken.py'. Line 1, Position 1 #!C:\prog\Python22\python.exe ^ and when using Mozilla 1.0, all I get is the listing of the script. Bummer. Any advise? Thank you. Regards, Kenneth. On Fri, 27 Sep 2002 09:16:41 -0400, "Steve Holden" wrote: >"Kenneth Gomez" wrote in message >news:3d8d4009.375344 at news.jaring.my... >> Chris, you're right. It's an Apache config problem. I'll dig into the >> doc's. > > >The Wrox book "Professional Apache 2.0" is helpful if you need to understand >how Apache works and, despite its title, it alos covers older versions of >Apache. > >If you want to write servers in pure Python you could look at "Python Web >Programming", but you will probably find you can get a lot further than you >thought with simple CGI, then you'll know enough about other directions >you'd like to go. > >regards >----------------------------------------------------------------------- >Steve Holden http://www.holdenweb.com/ >Python Web Programming http://pydish.holdenweb.com/pwp/ >Previous .sig file retired to www.homeforoldsigs.com >----------------------------------------------------------------------- > > > Cheers, Kenneth Gomez. From iqbal at colorado.edu Mon Sep 9 20:41:56 2002 From: iqbal at colorado.edu (Naveed Iqbal) Date: 9 Sep 2002 17:41:56 -0700 Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> Message-ID: <6afb9d2c.0209091641.1d9b652e@posting.google.com> Thank you all for your help. I am really a novice when it comes to python. Will someone tell me how to install the win32ui module in windows? thanka naveed Eric Brunel wrote in message news:... > Naveed Iqbal wrote: > > I have to print to a standard printer. I take the data from the > > keyboard and print it using the printer. Please help me....my job > > depends on this!!!! > > Things are quite different on Unix and Windows. Just a sample (untested) > program to print "Hello world!" to the default printer on both platforms: > > ----Unix---------------------- > import os > p = os.popen('lpr', 'w') > p.write("Hello world!\n") > p.close() > ------------------------------ > > ----Windows------------------- > import win32ui > > dc = win32ui.CreateDC() > dc.CreatePrinterDC() > dc.SetMapMode(4) # This is UI_MM_LOENGLISH > ## With this map mode, 12 points is 12*100/72 units = 16 > font = win32ui.CreateFont({'name' : 'Arial', 'height' : 16}) > dc.SelectObject(font) > > dc.StartDoc("HelloWorld") > dc.StartPage() > dc.TextOut(40, 40, "Hello world!") > dc.EndPage() > dc.EndDoc() > ------------------------------ > > And now you wish you were on Unix ;-)! > > For more information on the Windows version, see the documenattion for > win32ui @ > http://aspn.activestate.com//ASPN/Python/Reference/Products/ActivePython/PythonWin/modules.html > and Micro$oft MFC documenation @ > http://msdn.microsoft.com/library/default.asp > > Good luck! > > PS: I'm actually a little biased towards Unix... In fact, if you have the > printer directly connected to your PC, opening LPT1: and just writing the > text to it should work. But if it's a network printer, the only solution is > the code above... > > We also can make things a little more complicated on Unix by using > PostScript. But it's still shorter: > > import os > p = os.popen('lpr', 'w') > p.write('%!PS\n') > p.write('/Helvetica findfont 12 scalefont setfont\n') > p.write('/cm { 72 mul 2.54 div } def\n') > p.write('1 cm 28 cm moveto\n') > p.write('(Hello world!) show\n') > p.write('showpage\n') > p.close() From darksyyyde at earthlink.net Fri Sep 6 23:18:33 2002 From: darksyyyde at earthlink.net (dark) Date: Sat, 07 Sep 2002 03:18:33 GMT Subject: Thinking of joining Message-ID: <3D7970DC.5115BCC8@earthlink.net> Hello. Im currently still learning C, but a friend has been trying to turn me on to python. >From what ive seen it looks pretty good. I was just curious if it will do everything PERL will do, as i dont care for how PERL reads. ( though a lot of proplr i have talked to try to push PERL on me) Im going to try to discipline myself to get C down first, but its tempting to jump into Python now. I am a monty Python fan of many years, if that helps lol. From jhalttun at pp.htv.fi Thu Sep 5 15:41:23 2002 From: jhalttun at pp.htv.fi (janne halttunen) Date: Thu, 05 Sep 2002 22:41:23 +0300 Subject: How to get os.popen subprocess PID? References: <3D775167.6060307@pp.htv.fi> <1031248567.61579.0@doris.uk.clara.net> <1031248831.62067.0@doris.uk.clara.net> Message-ID: <3D77B363.7000802@pp.htv.fi> Ricardo wrote: >>Instead of using os.popen() you could import the popen2 module and use the >>Popen3 or Popen4 classes. >> >>Objects of these classes contain a 'pid' attribute. >> > > > Sorry, forgot to mention these classes are available on Unix only ... Yeah, I'm on linux, so that's no problem. Thanks, janne From bokr at oz.net Sat Sep 28 11:57:27 2002 From: bokr at oz.net (Bengt Richter) Date: 28 Sep 2002 15:57:27 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <7nHk9.172208$pX1.6117207@news2.tin.it> Message-ID: On Fri, 27 Sep 2002 15:24:04 -0700, "Mike Rovner" wrote: > >"Terry Reedy" wrote in message >news:t_3l9.334924$AR1.14880141 at bin2.nnrp.aus1.giganews.com... >> na=1; np=3; nl=1; ng=0 >> print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\ >> (na, na!=1 and 's' or '', np, np!=1 and 's' or '', nl, nl!=1 and 's' >> or '', ng, ng!=1 and 's' or '') >> >> Found: 1 apple, 3 plums, 1 lemon, and 0 grapes. >> >> Alternatives to this 'risky' construct: >> 1. forgo the nicety of correct English output >> 2. nest if/else four levels deep to choose correct variant of 16 print >> statements (ugh) or just generate the correct variant: fmt = "Found: %%d apple%s, %%d plum%s, %%d lemon%s, and %%d grape%s." % \ tuple([('','s')[x!=1] for x in [na,np,nl,ng]]) print fmt % (na, np, nl, ng) or pre-generate all sixteen: >>> fmtList=["Found: %%d apple%s, %%d plum%s, %%d lemon%s, and %%d grape%s." % (a,p,l,g) ... for a in ('','s') for p in ('','s') for l in ('','s') for g in ('','s') ] and select the correct one by index: >>> fmt = fmtList[(na!=1)*8+(np!=1)*4+(nl!=1)*2+(ng!=1)] >>> print fmt % (na, np, nl, ng) Found: 1 apple, 3 plums, 1 lemon, and 0 grapes. >> 3. precalculate 4 suffixes and store in 4 temp vars with 4 if/else's >> (8 or 16 lines); >> though clearly superiour to 2), this is still tedious with some >> risk of typo error. Why so many lines? If you really want the temps: tmpa, tmpp, tmpl, tmpg = [('','s')[x!=1] for x in [na,np,nl,ng]] or tmpa, tmpp, tmpl, tmpg = map(lambda x:'s'[x==1:], [na,np,nl,ng]) >> >4. Try: >use_s=('','s') >print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\ >(na, use_s[na!=1], np, use_s[np!=1], nl, use_s[nl!=1], ng, use_s[ng!=1]) > 5.: >>> na=1; np=3; nl=1; ng=0 >>> def s(n): return 's'[n==1:] ... >>> print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." % ( ... na, s(na), np, s(np), nl, s(nl), ng, s(ng) ... ) Found: 1 apple, 3 plums, 1 lemon, and 0 grapes. 6.: >>> class NQ: ... def __init__(self, name, quant): ... self.name = name ... self.quant = quant ... def __str__(self): ... return '%s %s%s' % (self.quant, self.name, ('', 's')[self.quant!=1]) ... >>> print "Found: %s, %s, %s, and %s." % ( ... NQ('apple',na), NQ('plum',np), NQ('lemon',nl), NQ('grape',ng) ... ) Found: 1 apple, 3 plums, 1 lemon, and 0 grapes. 7.: >>> print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." % \ ... tuple([[x, x!=1 and 's' or ''][y] for x in [na,np,nl,ng] for y in [0,1]]) Found: 1 apple, 3 plums, 1 lemon, and 0 grapes. ... ;-) Regards, Bengt Richter From bokr at oz.net Thu Sep 5 14:36:09 2002 From: bokr at oz.net (Bengt Richter) Date: 5 Sep 2002 18:36:09 GMT Subject: Why read-only nested scopes? References: Message-ID: On 05 Sep 2002 12:11:45 +0200, loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) wrote: >Gon?alo Rodrigues writes: > >> >x = 1 >> > >> >def foo(): >> > x = 2 >> > def bar(): >> > x = 3 >> > def baz(): >> > global x >> > x = 4 >> > >> >If you invoke baz(), which of the variables is changed? How do you >> >denote that you want to change the others? >> >> I think that crawling up the scope hierarchy and stopping at the first x >> that one finds (in the above case, the one defined in bar) is a sensible >> solution. > >This solution is not backwards-compatible. global always refers to >globals(), programs may rely on that. > How about introducing an optional "degree of globalness" for the global declaration? E.g., x = 1 def foo(): x = 2 def bar(): x = 3 def baz(): global(1) x x = 4 would go outwards 1 nested scope and thus target the x in bar, rebinding it from 3 to 4. plain "global x" would be a backwards-compatible spelling of "global(-1) x", where the implication of the -1 is to index the last in a list of scopes starting with global(0) for local and ending with the outermost as the last in the list, at global(-1). Since all the variants would be syntax errors now, there would be no old-code breakage. It might be interesting to let the globals() function take an optional argument corresponding to the above relative scope parameter. Thus globals(0) would return the same as locals(), and globals() the same as globals(-1), but in the context of baz above, globals(1) would return {'x': 3}. Regards, Bengt Richter From larry.tami at gte.net Sun Sep 29 17:46:58 2002 From: larry.tami at gte.net (Larry Wright) Date: Sun, 29 Sep 2002 21:46:58 GMT Subject: Python PAM module Message-ID: Hello, I am wondering if anyone can point me to the location of the Python PAM module. My google searches turn up references to www/ftp.pangalactic.org, but this site seems down. As a side note, I am wanting to use this to do authentication (for Medusa FTP) on a system using shadow passwords. Has anyone tried this, and if so, do you have any advice? Thanks in advance. From bkc at Murkworks.com Wed Sep 25 18:33:17 2002 From: bkc at Murkworks.com (Brad Clements) Date: Wed, 25 Sep 2002 18:33:17 -0400 Subject: a python puzzle References: Message-ID: <3d923704$1_6@goliath.newsgroups.com> It's time to test your brainpower! I will give six months of free web hosting to the first person to solve this cryptogram. Can you figure it out? Since you have taken my challenge and decrypted the secret message, I will even give you the cryptogram-making source code to amaze your friends! import sys, string, random cipher = list(string.letters[:26]) random.shuffle(cipher) cipher = "".join(cipher) cipher += cipher.upper() map = {} for plain, crypt in zip(string.letters, cipher): map[plain] = crypt for line in open(sys.argv[1]): print "".join([map.get(ch,ch) for ch in line])[:-1] -- Novell DeveloperNet Sysop #5 _ "Michal Wallace" wrote in message news:mailman.1032989974.25321.python-list at python.org... > > > > Here's a python puzzle. Solve it and you win a prize. :) > > > > """ > Ha'f ahoy ad ayfa wdqr srxhekdpyr! H phmm zhby > fhv odeajf dc cryy pys jdfahez ad ajy chrfa kyrfde > ad fdmby ajhf irwkadzrxo. Ixe wdq chzqry ha dqa? > > Fheiy wdq jxby axgye ow ijxmmyezy xet tyirwkayt > ajy fyirya oyffxzy, H phmm ybye zhby wdq ajy > irwkadzrxo-oxghez fdqriy idty ad xoxuy wdqr > crhyetf! > """ > hokdra fwf, farhez, rxetdo > ihkjyr = mhfa(farhez.myaayrf[:26]) > rxetdo.fjqccmy(ihkjyr) > ihkjyr = "".ldhe(ihkjyr) > ihkjyr += ihkjyr.qkkyr() > oxk = {} > cdr kmxhe, irwka he uhk(farhez.myaayrf, ihkjyr): > oxk[kmxhe] = irwka > cdr mhey he dkye(fwf.xrzb[1]): > krhea "".ldhe([oxk.zya(ij,ij) cdr ij he mhey])[:-1] > > > > Cheers, > > - Michal http://www.sabren.net/ sabren at manifestation.com > ------------------------------------------------------------ > Switch to Cornerhost! http://www.cornerhost.com/ > Low Priced, Reliable Blog Hosting, With a Human Touch. :) > ------------------------------------------------------------ > > -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From zopestoller at thomas-guettler.de Fri Sep 27 08:28:44 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Fri, 27 Sep 2002 14:28:44 +0200 Subject: comp.lang.python... References: Message-ID: Vincent A. Primavera schrieb: > Hello, > Stupid question... What information do I need to set up > comp.lang.python with my news client(Pan)? > You need to subscribe this newsgroup and you need a newsserver. But how could you post this message without it? thomas From jkraska at san.rr.com Fri Sep 20 00:32:13 2002 From: jkraska at san.rr.com (Courageous) Date: Fri, 20 Sep 2002 04:32:13 GMT Subject: Larry Wall's comment on python... References: Message-ID: >Well, Python code may look awkward --- if not awk-like --- >if you don't know how to customize the tab width in your >editor of choice. Well, there's your problem already. One should use spaces and not tabs in Python code. Otherwise, any python file where tabs and spaces are mixed is also a choice of which indentation level other viewers of the code MUST use in their editors. That's heinous. C// From martin at v.loewis.de Tue Sep 17 18:23:31 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Sep 2002 00:23:31 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: Michael Chermside writes: > I am going to pose a hypothetical situation... please don't argue > about whether these conditions are true now, or whether they will be > true, but take these as assumptions: [...] > The question is this: Would the advantages of making Stackless part > of standard Python outweigh the disadvantages of non-portability and > C-Python specificity? Answering this question is tricky, because the answer may depend on the exact feature set that Stackless would provide. It is also very difficult not to argue about these conditions, because it is certain (for me) that some of them are inherently false, in all possible universes; a false precondition allows to imply anything. That said, I do think the advantages would outweigh the disadvantages: users like the features, and, under those conditions, there is no harm done integrating them. Regards, Martin From Oschler at earthlink.net Sat Sep 14 20:49:19 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 15 Sep 2002 00:49:19 GMT Subject: AspectP? Message-ID: Anybody seen a robust (fairly ready for primetime) implementation of Aspect Oriented Programming for Python? thx From shalehperry at attbi.com Wed Sep 25 19:35:10 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 25 Sep 2002 16:35:10 -0700 Subject: transform strings list in a int lists or other type??? In-Reply-To: <872170378.1032996587856.JavaMail.nobody@webmail2.brturbo.com> References: <872170378.1032996587856.JavaMail.nobody@webmail2.brturbo.com> Message-ID: <200209251635.10059.shalehperry@attbi.com> On Wednesday 25 September 2002 16:29, jubafre at brturbo.com wrote: > Can i tranform a list of strings in a list of int, or > other type in python??? and also write in a file? I think the > open(path,'wb') in __builtin__ dont?t write in a file other types, just > strings, rigth??? > > Juliano Freitas > www.gebrasil.hpg.com.br string_ling = ['14, '42', '83'] int_list = map(int, string_list) or in the newer pythons: int_list = [int(i) for i in string_list] there are equivalent conversion functions for the other types as well. From magnus at thinkware.se Fri Sep 20 08:46:47 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Fri, 20 Sep 2002 14:46:47 +0200 Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <23891c90.0209190014.26c5bb9@posting.google.com> <7xk7lhb943.fsf@ruckus.brouhaha.com> Message-ID: <3D8B18B7.2040203@thinkware.se> Paul Rubin wrote: > I'm finding it hard to imagine how any real-world financial > calculation using IEEE doubles could be off by as much as a penny. Apart from the rounding problems etc that the Decimal FAQ describes, I've seen people getting into trouble when they compare floats for equality. I've seen that several times over the years. In one system it worked well for years, until the application was ported from VMS to HP-UX. It would probably have worked on HP-UX as well, but values calculated on one platform and stored in the database didn't match values calculated on the other. There is always a risk for problems with cancellation errors, but unless the subtracted values are equal in the decimal representation and different in the floating point representation, it will still be a problem in a decimal representaion. But with a flexible system for decimal representation, you can adjust your accuracy to the present needs. With floats the precision is the same regardless of our needs. From steve at ferg.org Wed Sep 18 15:20:42 2002 From: steve at ferg.org (Stephen Ferg) Date: 18 Sep 2002 12:20:42 -0700 Subject: (Newbie) Menu Not Functioning References: Message-ID: I can't help with your code, but I'd like to suggest something that may be helpful. Go to http://home.att.net/~stephen_ferg/easygui/ and download easygui. Then the following program would put up a nice graphic listbox from which you could choose. For my own testing, I made the run() procedure just print the command, rather than run it. But if you change the code in the run() procedure, it should work just fine for you. -- Steve Ferg (steve at ferg.org) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ HERE'S THE CODE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import os import sys from easygui import * menu = [ "1. Copy Python Files from Office Computer to Floppy", "2. Copy Python Files from Home Computer to Floppy", "3. Copy Python Files from Floppy to Office Computer", "4. Copy Python Files from Floppy to Home Computer", ] def run(command): print "Running", command # demo code # os.system(command) # the real code def officetoflop(): run("xcopy C:\MyDocu~1\*.py a:") def hometoflop(): run("xcopy E:\MyDocu~1\*.py a:") def floptooffice(): run("xcopy a:\*.py C:\MyDocu~1") def floptohome(): run("xcopy a:\*.py E:\MyDocu~1") while 1: # do forever # use the easygui choicebox to make the selection choice = choicebox("Choose your selection", "Copy Utilities", menu) if choice == None: print "Goodbye" sys.exit(0) menu_choice = choice[0] # get the first character of the choice if menu_choice == "1": officetoflop() elif menu_choice == "2": hometoflop() elif menu_choice == "3": floptooffice() elif menu_choice == "4": floptohome() else: print "Program Logic error. Choice:", choice sys.exit(0) From jubafre at brturbo.com Tue Sep 10 15:07:01 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Tue, 10 Sep 2002 16:07:01 -0300 (GMT-03:00) Subject: read() file?? Message-ID: <-1076673467.1031684821080.JavaMail.nobody@webmail2.brturbo.com> I have a file with assembler instruction and i want read the lines of the file and put in a list of string, this is easy to do, but i don?t want to consider the caracteres "/" and the othes after him. file.asm: ADD D1 /coment1 LDA D2 /coment2 list of strings: X=[ 'ADD D1' , 'LDA D2' ] Juliano Freitas www.gebrasil.hpg.com.br From tim.one at comcast.net Fri Sep 6 10:04:19 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 06 Sep 2002 10:04:19 -0400 Subject: Python "compiler" is too slow for processing large data files??? In-Reply-To: Message-ID: [someone] > list1 = [ > (323, 870, 46, ), > (810, 336, 271, ), > (572, 55, 596, ), > (337, 256, 629, ), > (31, 702, 16, ), > ] > > Anyway, as my data files went from just a few lines, up to about > 8000 lines (with 10 values in each line for total of about 450KB of text), > the time to 'exec' the file became too slow (e.g. 15 seconds) and used too > much memory (e.g. 50MB) (using ms-windows, python 2.2.1). It is the > "compile" phase, because if I re-run, and there is *.pyc file available, > the import goes very fast (no compilation required). The parse tree created is huge, so the memory use isn't likely to go down in the near future (addressing this requires a fundamentally different parser, and nobody is working on that). Depending on platform, though, there are two things that can hurt speed a lot: 1. Oodles of tiny memory allocations and deallocations for the leaf nodes of the parse tree. 2. Repeated realloc of a high-level parse node to reflect the ever-growing number of top-level children. #1 has been repaired in 2.3 by using pymalloc in the parser instead of the platform malloc. #2 has been repaired in 2.2.2 and 2.3 by changing the parse node growth strategy to sidestep what's currently quadratic-time behavior in some platform realloc()s. Regardless, it would be saner to break any file with 450KB of source code into smaller files and paste them together with import. From bokr at oz.net Wed Sep 4 15:08:23 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2002 19:08:23 GMT Subject: ANN: New PEP Format: reStructuredText References: Message-ID: On Fri, 30 Aug 2002 00:23:15 -0400, David Goodger wrote: >With many thanks to Barry Warsaw for his help and patience, I am >pleased to announce that a new format for PEPs (Python Enhancement >Proposals) has been deployed. The new format is reStructuredText, a >lightweight what-you-see-is-what-you-get plaintext markup syntax and ^^^^^^^^^^^ -- well, the rudiments are light weight ;-) >parser component of the Docutils project. From the new PEP 12: > > ReStructuredText is offered as an alternative to plaintext PEPs, > to allow PEP authors more functionality and expressivity, while > maintaining easy readability in the source text. The processed > HTML form makes the functionality accessible to readers: live > hyperlinks, styled text, tables, images, and automatic tables of > contents, among other advantages. > I like it, but I can see symptoms of "we-can-do-anything-with-this" enthusiasm ;-) I think the "cheat sheet" at http://docutils.sourceforge.net/docs/rst/quickref.html is a better intro than the other intro's, because it's concise and visual (though some table stuff appears broken in my NS4.5 browser). [...] >Docutils and reStructuredText are under active development. Input is >very welcome, especially HTML rendering/stylesheet issues with >different browsers. We welcome new contributors. If you'd like to >get involved, please visit: > > http://docutils.sourceforge.net/ > Whenever I encounter yet another markup language (BTW, are you guys monitoring http://yaml.org/spec/ ;-), I look for fodder for my pet b?te, and if I find an un-nestable and/or otherwise restricted literal-content quoting construct, my pet grunts happily (which it is doing ;-) So I'd like to suggest an optional variant of the literal block, to mimic "here document" functionality. E.g., This::end_of_literal:: . end_of_literal ?? -- no! It has to be by itself on a final line. end_of_literal For rendering in HTML, I might expect to get

This:

<This is arbitrarily indented and might be verbatim copied & pasted from anywhere>.
 end_of_literal ?? -- no! It has to be by itself on a final line.
(I.e., '&', '<' and '>' converted to entity refs and otherwise no change between the
).

("end_of_literal" is of course an arbitrary string chosen or generated so as not to occur within
the quoted text).

Re YAML, perhaps a .. yaml:: yamlDoc_ directive to include a rendering of YAML content might
do something useful? (I won't mention .. xml:: xmlDoc_ ;-)

BTW, you could also use doc-here quoting to delimit the scope of a directive, e.g.,

    .. doit::xxx::

xxx

A last comment/question: It-would-be-nice-if-there-were/is-there-a grammar file for
reStructuredText like, e.g., Python's (comes with source distro)

    D:\Python-2.1\Grammar\Grammar

file !/?

Sorry if this repeats stuff covered in project docs/threads/faqs/todos. Have only browsed
spec and PEP and cheat sheet so far...

Regards,
Bengt Richter


From sholden at holdenweb.com  Tue Sep 10 18:49:22 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Tue, 10 Sep 2002 18:49:22 -0400
Subject: Larry Wall's comment on python...
References:  <3D7E1E28.5040709@bogus.thisisabogusdomain.com>
Message-ID: 

"Jack D. Hammer"  wrote ...
>
> One good argument for having block delimiters is for embedded situations
like
> ASP.  One can conditionally put code into a block as such (ASP is rusty):
>
I can't help feeling that if ASP is the answer I'm asking the wrong question
:-)

> <%
> if (some_condition) {
> %>
> 
> some data
> some more data
> 
> <%
> } // closing curly

I want to thank you for adding this valuable comment to your code. Without
it, I might have thought you were trying to close the parenthesis you
unopened above...

> %>
>
> I would think that for embedding python, having block delimiters would be
> beneficial.
>
Beneficial in the same way as giving $_ and $< and similar constructs
"meaning"? I use the inverted commas deliberately. They no longer have much
meaning for me. However, I do not deny the pragmatic value of the language,
not the value of the many pieces of software written in it.

If something works for us, we are entitled to use it. I just lost contact
with Perl when I looked at its object-oriented features. Of course, that may
not be Perl's fault. None of us is getting any younger.

[...]

I can't see "{%>" and "<%}" making it into the "Top 20 Delimiters" list,
perhaps I underestimate the pervasiveness of keyboard skills, of which I
have relatively few.

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------





From peter at engcorp.com  Wed Sep  4 22:43:20 2002
From: peter at engcorp.com (Peter Hansen)
Date: Wed, 04 Sep 2002 22:43:20 -0400
Subject: 4Suite / McMillan Installer / py2exe
References:  
Message-ID: <3d76c4ac$1@news.sentex.net>

Thomas Heller wrote:
>>Does someone know how to use 4Suite with the McMillan Installer or
>>py2exe on Windows? Any help or hints would be highly appreciated!
> 
> I never used 4Suite, so no. I even heard ;-) that py2exe
> doesn't work so good with _xmlplus.

We appear to have successfully worked around some of these issues
by simply renaming _xmlplus to xml and removing the original
xml directory.  We're about to "finish" this task and verify that
things are still working, but at first glance it seemed to solve
the problems.

For what it's worth.... (and in case anyone wants to say "uh, that
won't work, moron". :-)

-Peter



From skille at ameritech.net  Wed Sep  4 11:16:59 2002
From: skille at ameritech.net (Stevek)
Date: Wed, 04 Sep 2002 15:16:59 GMT
Subject: embeddable ide?
Message-ID: 

We're planning on making extensive use of Python to provide our users with a
powerful scripting mechanism.  I've successfully embedded and extended
Python but now I want to give the user a decent development environment for
writing their scripts.

I know there are several IDEs available for Python development, but I'm
looking for one that can be used from within another application (embedded).

Any suggestions would be appreciated.





From phr-n2002b at NOSPAMnightsong.com  Thu Sep 26 17:40:23 2002
From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin)
Date: 26 Sep 2002 14:40:23 -0700
Subject: Is mmap usable for IPC?
References: 
Message-ID: <7xwup8whtk.fsf@ruckus.brouhaha.com>

janeaustine50 at hotmail.com (Jane Austine) writes:
> Is mmap module usable for inter-process communication?
> 
> Does it provide lock, or semaphore? Is it safe to write
> from a process and read from multiple other processes
> simultaneously?
> 
> Any information appreciated.

Mmap doesn't provide lock.  Use shm instead.

http://gigue.peabody.jhu.edu/~mdboom/omi/source/shm_source/shm.html



From alanmk at hotmail.com  Thu Sep 26 10:16:30 2002
From: alanmk at hotmail.com (Alan Kennedy)
Date: 26 Sep 2002 07:16:30 -0700
Subject: Strange values in Accept-Language header?
References:  
Message-ID: 

Alan Kennedy wrote:

>> On looking at my server logs for the Accept-Language headers (to
>> answer another post in this group), I came across some strange
values
>> that are definitely not ISO language codes. For example,
>> 
>> Accept-Language: en-us,x-ns1rDGeT4e2FpA,x-ns2f67971hgDw1
>> Accept-Language: x-ns13V8cN8S1Xz9,x-ns2T329gfxKa7d

Jeff Epler wrote:

> Searching on google turns up two hits in quoted mail message headers,
> both with Mozilla 4.7x.
>     http://www.google.com/search?q=accept-language+x-ns1
> 
> I wonder whether really ancient mozilla cvs might have some clues.  I
> groveled around a bit in bonsai but didn't come up with anything.

Jeff,

Thanks for the reply.

I've had some more time to analyse the logs. User agents that
submitted
these strange values are

Mozilla/4.75C-CCK-MCD {C-UDP; EBM-APPLE} (Macintosh; U; PPC)
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)
Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:0.9.4.1) Gecko/20020508
Netscape6/6.2.3
Mozilla/4.77C-CCK-MCD {C-UDP; EBM-APPLE} (Macintosh; U; PPC)
Mozilla/4.73 (Macintosh; U; PPC)
Mozilla/5.0 (Macintosh; U; PPC; ja-JP; rv:0.9.4) Gecko/20011130
Netscape6/6.2.1
Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; VZ_IE5; YComp 5.0.0.0)
Mozilla/4.7 [en]C-CCK-MCD   (Win98; I)
Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)
Mozilla/4.79 (Macintosh; U; PPC)
UCmore

Approx 25% of these hits come through a (non-transparent) proxy, with
proxies from

marketscore.com
integrity.com

being the most common. Which is interesting, because marketscore.com
offer "faster surfing at no cost"

http://www.marketscore.com/e/surffaster.asp

Presumably they are modifying requests in some way to achieve that
"faster surfing"?

integrity.com is a filtering ISP that vets all content for obscenity

http://www.integrity.com/

So it is conceivable that they are implementing some form of custom
"signalling" to servers?

Of course, all of this is pure guess-work, but I'd bet that the 75% of
such hits that appear not to have come from a proxy are actually
coming through a transparent proxy of some kind.

That guess aside, I cannot see a single thing in common between all
the requests that contain these values.

I'd still be interested to hear from anyone who knows what these
values signify. I might email integrity.com and merketscore.com to see
if they can shed any light.

Sincerely,

alan kennedy
----------------------------------------------
check http headers here: xhaus.com/headers
email alan:              xhaus.com/mailto/alan


From jonbeebe85 at yahoo.com  Wed Sep 18 09:15:01 2002
From: jonbeebe85 at yahoo.com (Jonathan Beebe)
Date: Wed, 18 Sep 2002 13:15:01 GMT
Subject: running external programs
Message-ID: 

Is there a function or library i can import that i can use to run external
programs from within my program?

example:

runprogram("iexplore.exe")

thanx,
-JONATHAN BEEBE





From helm at dnv.com  Thu Sep 26 06:13:09 2002
From: helm at dnv.com (Jens Bloch Helmers)
Date: Thu, 26 Sep 2002 10:13:09 GMT
Subject: os.makedirs: difference between nt4 and w2k
Message-ID: 

Suppose unc_path is a UNC path refering to a non existing
directory on another computer.
os.makedirs( unc_path ) throws an exception if this path
is on a windows 2000 machine but creates the directory if
it is on a win-nt machine.

Is this a feature of win2k, or could I change the setup
of that win2k computer to accept the creation of unc_path?
Could this be done from Python?
(I have administrator privileges on both computers)

Jens Helmers


From trash at terastat.com  Tue Sep 17 13:22:58 2002
From: trash at terastat.com (bap)
Date: Tue, 17 Sep 2002 17:22:58 GMT
Subject: PIL 1.1.3 and grabscreen
Message-ID: 

I'd like to use the grabscreen function from Lundh's site
(http://effbot.org/downloads) however it won't install or run (I use Python
2.2, it may be compiled for 2.1). The function is now included (according to
the documentation) in PIL 1.1.3 -- but the PIL site only has binary versions
of 1.1.2, for v1.1.3 the site refers to Lundh's site -- where again the
installation routine doesn't work (asks for a directory but will accept no
input). So -- does anyone know of any working sources of either grabscreen
or a binary distributable for windows/activestate python 2.2 of PIL 1.1.3?




From sholden at holdenweb.com  Wed Sep 25 08:31:43 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Wed, 25 Sep 2002 08:31:43 -0400
Subject: Getting started
References:  
Message-ID: 

"holger krekel"  wrote ...
> Lance wrote:
> > Hi All,
> >
> > Last night I attended a Weak typing, C++ Templates, and Python talk by
Bruce
> > Eckel. It was great, my introduction to Python.
> >
> > I'm sold on Python and weak typing.
>
> I am not. But i much prefer dynamic over static typing :-)

Python is comfortable for me because the data is strongly-typed and no type
is associated with names. This gives maximum flexibility and minimum
requirements for compile-time checking, both good attributes for a
rapid-development environment.

> What is 'weak typing' supposed to mean, anyway?  I have heard that a
couple
> of times from java-people because they tend to think that python
> is not strongly typed.
>
There are languages which use type information to allow a relaxed
polymorphism, and there are those (like Java) where either syntax or
predominant style anally forces the programmer to prove they are in tune
with the framework's requirements. The latter might still be programming,
but it sure isn't fun [note: I do not insist that programming *must* be fun,
but if you don't enjoy it you'll probably not be reading this].

> > Would you be able to suggest an indispensable learning Python book?
>
Alex is, of course, far too modest to promote his forthcoming "Python in a
Nutshell", but that's going to be extraordinarily good for Python newbies. I
think its appearance will also make other O'Reilly books on Python more
valuable.

> David Beazley wrote "Python essential reference" which is a very good
> book for programmers. It doesn't cover the most recent developments
> but it still is one of the best IMO.
>
Beazley is indeed helpful; soon a Python book won't need to labor to
introduce the language but simply list the appropriate tomes where the
knowledge can be acquired. This is a good thing.

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------





From duncan at NOSPAMrcp.co.uk  Tue Sep 24 09:40:59 2002
From: duncan at NOSPAMrcp.co.uk (Duncan Booth)
Date: Tue, 24 Sep 2002 13:40:59 +0000 (UTC)
Subject: list problem
References:     <_FZj9.158106$pX1.5692316@news2.tin.it>
Message-ID: 

Alex Martelli  wrote in 
news:_FZj9.158106$pX1.5692316 at news2.tin.it:

> I _do_ think that reduce(operator.__add__, ...) is the only
> really frequent use of reduce, with such dominance that it might
> even be worth having as a built-in -- clearest and fastest.  It
> might even specialcase _strings_ in particular, turning the op
> into a ''.join in this case... just musing...

The simplest thing could be to modify operator.add to accept any number of 
arguments. Then you could use operator.add(*aList) to add up or concatenate 
as appropriate all the elements of the list.

It still wouldn't be as fast as ''.join though unless you special cased it, 
and it might be hard to special case it effectively: you would have to 
check the types of all the objects in the list before deciding whether or 
not to use join.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?


From Oschler at earthlink.net  Mon Sep  2 11:34:36 2002
From: Oschler at earthlink.net (Robert Oschler)
Date: Mon, 2 Sep 2002 11:34:36 -0400
Subject: Must have Python modules?
References: 
Message-ID: <0pLc9.32066$FJ1.5655132@e3500-atl1.usenetserver.com>

"Denis S. Otkidach"  wrote in message
news:mailman.1030971902.24931.python-list at python.org...
> On Mon, 2 Sep 2002, Robert Oschler wrote:
>
> RO> development!)  I want to know what the other favorites are
>
> mx, PIL, DocumentTemplate, TAL, MySQLdb
>

For those of you newbies like me, curious about what TAL is, try this link:

http://dev.zope.org/Wikis/DevSite/Projects/ZPT/TAL

thx






From duncan at NOSPAMrcp.co.uk  Fri Sep  6 08:32:45 2002
From: duncan at NOSPAMrcp.co.uk (Duncan Booth)
Date: Fri, 6 Sep 2002 12:32:45 +0000 (UTC)
Subject: tree data structure
References: 
Message-ID: 

Padraig Brady  wrote in 
news:FM0e9.2860$cP3.6165 at news.iol.ie:

> Hi,
> 
> I've a graph like stucture represented
> by a list of tuples:
> 
> [(L0,S2), (S2,S0), (S2,S1), (S1,Q2), (S0,Q1), (S2,S3)]
> 
> And would like to convert it to
> a tree structure like:
> 
>            S0 - Q1
>          /
> L0 - S2 - S3
>          \
>            S1 - Q2
> 
> Any tips appreciated.
> 
Does this help?

data = [('L0', 'S2'), ('S2', 'S0'), ('S2', 'S1'), ('S1', 'Q2'), ('S0', 
'Q1'), ('S2', 'S3')]

# Produce a tuple where each node contains its name
# and a list of its child nodes:
#  (node, [child1, ...])
nodes = {}
for parent, child in data:
    nodes.setdefault(parent, (parent, 
[]))[1].append(nodes.setdefault(child, (child, [])))

result = nodes[data[0][0]]

assert result==('L0', [('S2', [('S0', [('Q1', [])]), ('S1', [('Q2', [])]), 
('S3', [])])])


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?


From robin at execulink.com  Sat Sep 14 01:59:43 2002
From: robin at execulink.com (robin at execulink.com)
Date: Sat, 14 Sep 2002 01:59:43 -0400
Subject: threads or queue for this task
Message-ID: 

I am missing something I think with the difference between the
threading and Queue modules. These could really do with some updated
docs with examples.

I wish to have a server continually cycle (until interrupted by
keyboard, signal, or whatever). It needs to perform several (say 6)
different tasks, each of which may take significantly different
lengths of time to perform.

My first implementation used threading.py. I wrote a dispatcher to
start each of the threads, and then wait until the thread count was
back down to 1. This I put in a while loop, and surrounded it with the
necessary exception code.

Each cycle through the while has to wait for the slowest process to
finish before completing. During this time, the other processes just
sit around doing nothing. What I really want is for each process to
start up again when they are done, so that there are no more than 6
going at once. In other words, I want to be sure I don't start a new
process 3 before the old process 3 is done.

I have looked at Queue but it doesn't seem to have enough control to
make this happen.

I am sure I am overlooking something obvious. Thanks ahead of time for
any help!

-- robin


From cliechti at gmx.net  Wed Sep 25 15:06:40 2002
From: cliechti at gmx.net (Chris Liechti)
Date: 25 Sep 2002 21:06:40 +0200
Subject: Python and Scite
References: 
Message-ID: 

"Sperry Russ"  wrote in
news:mailman.1032973593.30002.python-list at python.org: 

> Hello,
> 
> I am new to programming.  I have downloaded Python 2.2.1 and Scite
> 1.48 to learn how to program.  I am trying to configure my Scite so
> that it will run the python files by using go.  When I try to do this
> i get a message in the second window at the bottom -- unable to find
> file.  I have tried configuring the global options and have failed can
> anyone help me? I need a step by step example if you can because I
> cannot understand it according to the documentation that came with
> Scite 

works out of the box for me. if you're on windows, make sure that python is 
found in the PATH. i.e. edit PATH that it contains the python directory.
and you could look at PythonWin, it uses the editing component used in 
scite and has some additional features for the python programmer. 
additionaly it comes also with useful, de-facto standard, windows specific 
extensions.

chris

-- 
Chris 



From a_salnikov at yahoo.com  Mon Sep  2 14:11:12 2002
From: a_salnikov at yahoo.com (Andy Salnikov)
Date: Mon, 2 Sep 2002 11:11:12 -0700
Subject: Python GUI
References: <3d8d3c0.0208262339.e7bc02c@posting.google.com>   
Message-ID: 

"Bo M. Maryniuck"  wrote in message
news:mailman.1030954205.15207.python-list at python.org...
> On Monday 02 September 2002 09:16, Andy Salnikov wrote:
> > Problem with X11 is that there is no "OS style manager" (whatever
> > this could mean) for X11, or there is no _single_ style manager.
>
> No. Problem with the license. Use wxWindows instead.
>
  Qt for X11 is free and license for X11 is not restrictive. Good example
is whole KDE built on top of Qt. Trolltech guys are indeed nice when
it comes to disscussing license terms. (Qt/Windows is not free though.)
wxWindows may be good too, but I consider Qt more mature, whole
KDE community works with Qt (although it does not mean Qt is free
of bugs.)

  Andy.




From lee100 at sport.rr.com  Thu Sep 19 19:38:12 2002
From: lee100 at sport.rr.com (Lee Gray)
Date: Thu, 19 Sep 2002 23:38:12 GMT
Subject: Python GUI app to impress the boss?
References: <96904b50.0209171305.6d65f574@posting.google.com> <96904b50.0209181149.429e8533@posting.google.com> 
Message-ID: 

Fred Pacquier wrote:

> lpgray at uop.com (Lee Gray) said :
> 
>> Thanks for all the suggestions, folks!
>> 
>> I've collected lots of links to a variety of very nice screenshots,
>> and I've been playing with the wxWindows demo and Boa Constructor. Boa
>> was a bit disappointing, not as an app, but because of its current
>> alpha status - but it's got great potential and I'll definitely look
>> forward to future releases. I'll check out PythonCard too.
> 
> This just in : the Python Daily URL (http://www.pythonware.com/daily/)
> mentions this collection of classes and tools for UML modeling and
> programming. I don't understand it all, but the sceenshot of the graphical
> model editor sure is a killer :-)
> 
> http://www.abo.fi/~iporres/Projects/fog0000000023.html

Hehe... yep, that was one of 'em I bookmarked.

Lee


From thomas at xs4all.net  Fri Sep 13 09:27:30 2002
From: thomas at xs4all.net (Thomas Wouters)
Date: Fri, 13 Sep 2002 15:27:30 +0200
Subject: Cursed newlines and readline()
In-Reply-To: <6u5g9.11312$Da3.1133980@kent.svc.tds.net>
References: <6u5g9.11312$Da3.1133980@kent.svc.tds.net>
Message-ID: <20020913132730.GD797@xs4all.nl>

On Thu, Sep 12, 2002 at 06:59:14PM +0000, Edward K. Ream wrote:

> According to one of Leo's Linux users, the Python's readline() routine on
> Linux delivers "\r\n" line end strings verbatim, while the windows versions
> force the string to use the Unix convention of using only "\n". This seems
> unfortunate.  Is there a justification for it?  If not, I would like to
> suggest that readline() work the same on all platforms and that it deliver
> only "\n" as a line terminator.

You can open the file in 'binary' mode (adding 'b' to the mode string) and
the file will contain '\r\n' on both platforms (and any other platforms.)

-- 
Thomas Wouters 

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!



From skip at pobox.com  Tue Sep  3 23:11:11 2002
From: skip at pobox.com (Skip Montanaro)
Date: Tue, 3 Sep 2002 22:11:11 -0500
Subject: can distutils build simultaneously on two architectures?
Message-ID: <15733.31183.590119.495095@12-248-11-90.client.attbi.com>

Can I safely execute the standard distutils command

    python setup.py build

simultaneously on two different architectures (Solaris and Linux in this
case) without fear of clashing?  I know about the build/{temp,lib}*
directories for compiling and linking C/Fortran code.  What about the
directories containing .py[co] files?  Does any sort of locking take place?

-- 
Skip Montanaro
skip at pobox.com



From remi at cherrypy.org  Thu Sep 12 09:15:50 2002
From: remi at cherrypy.org (Remi Delon)
Date: Thu, 12 Sep 2002 15:15:50 +0200
Subject: Online XML/XSL transformation tool available (based on 4Suite and CherryPy)
Message-ID: 

Hi everyone,

I just made available a very simple online XML/XSL transformation tool.
You just input your XML document and your XSL stylesheet (in textareas), and
it runs the transformation and displays the result.
This can sometimes come handy to debug XSL stylesheets.

This tool is part of the CherryPy online demo and it is used to demonstrate
the integration of the 4Suite module into CherryPy.

The direct URL is http://www.cherrypy.org/demo/xmlXslOnline

Cheers.

Remi.

PS: Let me know if you have any comments or if you would like more features.

PS2: Thanks to the Fourthought guys for their good work on 4Suite.





From mfranklin1 at gatwick.westerngeco.slb.com  Fri Sep 13 09:45:42 2002
From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin)
Date: Fri, 13 Sep 2002 13:45:42 +0000
Subject: Pmw.ScrolledText programatically scrolling
In-Reply-To: <3D81D44E.C5FC4A8B@mill.co.uk>
References: <3D81D44E.C5FC4A8B@mill.co.uk>
Message-ID: <200209131345.42294.mfranklin1@gatwick.westerngeco.slb.com>

On Friday 13 Sep 2002 12:04 pm, Joe Connellan wrote:
> I've got a Pmw.ScrolledText() that I'm using as a log and I've written
> an addToLog() method like so:
>
>  def addToLog(self, logString):
>   self.logScr.configure(text_state = 'normal')
>   self.logScr.insert(END, logString)
>   self.logScr.configure(text_state = 'disabled')
>
> I now want it to scroll when I add a line so the user doesn't have to
> constantly scroll down to view the most recent lines.
>
> I can't find any info on doing this with ScrolledText or its text
> component - do I need to reposition the scrollbars for it to scroll?
>
> Thanks
>
> Joe

Joe,

Try this:-


st.insert('end',stuff)
st.yview_pickplace('end')

where 'st' is a Pmw.ScrolledText instance


Regards
Martin

-- 
### Python Powered Signature
I started writting this email on 
Fri Sep 13 13:44:27 2002




From rpw3 at rpw3.org  Wed Sep 18 22:29:35 2002
From: rpw3 at rpw3.org (Rob Warnock)
Date: Thu, 19 Sep 2002 02:29:35 -0000
Subject: DNS problem re: International Lisp Conference 2002
References: 
Message-ID: 

Raymond de Lacaze  wrote:
+---------------
|  Registration deadline:  September 31st, 2002
+---------------

Oh, is a new calendrical system being presented at the Conference?  ;-}

+---------------
| Registration information is available at:
| http://www.international-lisp-conference.org/Overview/LC02-Registration.html
+---------------

Unfortunately, while the Internet root servers claim that
"{ns1,ns2}.franz.com" are authoritative for the domain
"international-lisp-conference.org", the "{ns1,ns2}.franz.com"
servers deny any knowledge of it!!!  (Makes it a little bit
hard to access...)

*Help!*


-Rob

-----
Rob Warnock, PP-ASEL-IA		
627 26th Avenue			
San Mateo, CA 94403		(650)572-2607



From hst at empolis.co.uk  Fri Sep 13 03:41:59 2002
From: hst at empolis.co.uk (Harvey Thomas)
Date: Fri, 13 Sep 2002 08:41:59 +0100
Subject: Help with regular expression using findall and .*?
Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D18@hendrix.empolisuk.com>

czrpb wrote
> 
> Could anyone help out with rewriting (still using regular expressions)
> the following so that it does not cause an exception:
> 
> import re
> 
> s1=('macro\n'+'a'*200+'\norcam\n')*10
> s2=('macro\n'+'a'*20000+'\norcam\n')*10
> 
> p=re.compile(r'macro.*?orcam',re.DOTALL)
> 
> for x in re.findall(p,s1):
>     print x
> 
> for x in re.findall(p,s2):
>     print x
> 
> thanks!! Quentin Crain
> 

You need to be very careful about using .*? as the engine "only" allows 10,000 backtracks

Try this

p = re.compile('macro(?:[^o]+|o(?!rcam))*orcam')
for x in p.findall(s2):
    print x

HTH

Harvey

_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.



From whisper at oz.net  Fri Sep  6 15:25:04 2002
From: whisper at oz.net (David LeBlanc)
Date: Fri, 6 Sep 2002 12:25:04 -0700
Subject: Larry Wall's comment on python...
In-Reply-To: 
Message-ID: 

The man obviously can't see the blocks for the indenting ;)

David LeBlanc
Seattle, WA USA 

> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of brueckd at tbye.com
> Sent: Friday, September 06, 2002 13:04
> To: python-list at python.org
> Subject: Re: Larry Wall's comment on python...
> 
> 
> On 6 Sep 2002, Rod Stephenson wrote:
> 
> > "Python is cool to look at small bits of, but I think the "outline"
> > syntax breaks down with larger chunks of code. I'm with Aristotle on
> > the structure of discourse--a story should have a beginning, and
> > middle, and an end. So should blocks"
> > 
> > I'm not quite sure what he's trying to get at here - I guess that for
> > a long heavily indented chunk of code, you could lose track of the
> > overall structure, but I don't write code this way.
> > 
> > Any comments?
> 
> The very idea of Larry Wall lecturing on code readability is hilarious.
> 
> -Dave
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list



From marklists at mceahern.com  Thu Sep 19 13:21:17 2002
From: marklists at mceahern.com (Mark McEahern)
Date: Thu, 19 Sep 2002 12:21:17 -0500
Subject: strong/weak - dynamic/static [Was: Getting started]
In-Reply-To: <87ofaut2xt.fsf@pokey.henrik-motakef.de>
Message-ID: 

[Henrik Motakef]
> There's a difference between a type and a class, I guess...

Alex made the point already, but the following code demonstrates that what
you demonstrated relies on old-style classes, which gives you a misleading
answer imho:

**

class foo(object):

    def changeme(self, newclass):
        self.__class__ = newclass

class bar(object):

    pass

f = foo()
b = bar()

print "type(f) = %s" % type(f)
print "type(b) = %s" % type(b)
print "type(f) == type(b) ==> %s" % (type(f) == type(b))

f.changeme(bar)

try:
    # Try to change back...
    f.changeme(foo)
except AttributeError:
    print "Whaddya know, we can't change f anymore."

print "type(f) = %s" % type(f)
print "type(b) = %s" % type(b)
print "type(f) == type(b) ==> %s" % (type(f) == type(b))

**

Output:

type(f) = 
type(b) = 
type(f) == type(b) ==> 0
Whaddya know, we can't change f anymore.
type(f) = 
type(b) = 
type(f) == type(b) ==> 1

**

My point in posting this is merely to counter the false claim that you
cannot change an object's type at runtime.  I'm not asserting that you can
change any object's class to anything whatsoever without experiencing
problems or runtime errors, of course.

Cheers,

// m

-




From news at datatailors.com  Mon Sep 23 19:08:24 2002
From: news at datatailors.com (Peter van Kampen)
Date: Tue, 24 Sep 2002 01:08:24 +0200
Subject: Solved (was: Cookbook example, DAO error)
References: 
Message-ID: 

In article , Peter van Kampen wrote:
> Hi,
> 
> I am trying to run the jet2sql script from the Python cookbook but it
> fails. 

It turns out it's the the mdb I wanted to process caused the problems.
I created a new one from scratch and jet2sql worked fine.

PterK


From pyth at devel.trillke.net  Wed Sep 25 19:15:34 2002
From: pyth at devel.trillke.net (holger krekel)
Date: Thu, 26 Sep 2002 01:15:34 +0200
Subject: a python puzzle
In-Reply-To: ; from sabren@manifestation.com on Wed, Sep 25, 2002 at 06:21:56PM -0400
References: <20020926000315.K30315@prim.han.de> 
Message-ID: <20020926011534.L30315@prim.han.de>

Michal Wallace wrote:
> On Thu, 26 Sep 2002, holger krekel wrote:
> 
> > OK.  something like 
> > 
> > def decrypt(yourstring):
> >     dedict = {'F': 'S', 'I': 'C', 'H': 'I', 'a': 't', 'c': 'f', 'b': 'v', 'e': 'n',
> >     'd': 'o', 'f': 's', 'i': 'c', 'h': 'i', 'k': 'p', 'j': 'h', 'm': 'l',
> >     'l': 'j', 'o': 'm', 'q': 'u', 'p': 'w', 's': 'b', 'u': 'z', 't': 'd',
> >     'w': 'y', 'v': 'x', 'y': 'e', 'x': 'a', 'z': 'g', 'g': 'k'}
> >     return "".join([dedict.get(i,i) for i in yourstring])
> > returns
> ...
> >     It's time to test your brainpower! I will give
> >     six months of free web hosting to the first person
> >     to solve this cryptogram. Can you figure it out?
> 
> 
> Hi Holger,
> 
> Yep, that's it! I figured it would be easy to solve -
> especially given the python code, but I didn't expect a
> solution THAT quick. Next time I'm using RSA!

No problem :-)

Just letting out the python code would make it a bit harder.
One might even have to start to seriously program ...

> > but i don't know if i need free webhosting :-)
> 
> Hahaha. Well, if you change your mind, just let me know. :)

cheers,

    holger



From aleax at aleax.it  Mon Sep 23 02:58:57 2002
From: aleax at aleax.it (Alex Martelli)
Date: Mon, 23 Sep 2002 06:58:57 GMT
Subject: PyQt setup on Linux Mandrake 8.2
References: <3D8B4898.20808@nospam.attbi.com> <3d8e7141$1@news.nz.asiaonline.net> <3D8E74A4.7000404@nospam.attbi.com>
Message-ID: 

djw wrote:
        ...
> modules). Unfortunately, when I try to install new py modules, they all
> want to install into /usr instead of /usr/local, since /usr/bin/python
> is ahead of /usr/local/bin/python on $PATH, causing sys.prefix to point

The PATH is not etched in stone: edit /etc/profile or wherever it is
you set your PATH, and just put /ust/local/bin ahead of /usr/bin there.


Alex



From huaiyu at gauss.almadan.ibm.com  Tue Sep  3 20:25:15 2002
From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu)
Date: Wed, 4 Sep 2002 00:25:15 +0000 (UTC)
Subject: default tuple unpacking?
Message-ID: 

It is often very convenient to have default arguments such as

    def func(a, b, *c): ...

Is there a way to use this in statements too?  Examples:

    a, (b, *c), *d = e
    for a, *b in c: ...
    return a, *b

I often use small utilities such as

    def split1(x): return x[0], tuple(x[1:])
    def split2(x): return x[0], x[1], tuple(x[2:])

to simulate this in easier situations, but I often find the need to do a
more general unpacking by tuple pattern matching.  They would make the code
so much more readable.  Python can already handle all the following

    def func(a, (b,c), *d)
    a, (b, (c, d), e) = f
    for (a,b), (c,d) in e: ...

I would guess it should not be too difficult to handle the combinations.
Any ideas?  Has this been done?


Huaiyu


From fperez528 at yahoo.com  Fri Sep 27 17:38:11 2002
From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=)
Date: Fri, 27 Sep 2002 15:38:11 -0600
Subject: watching mutables?
References:        
Message-ID: 

Anton Vredegoor wrote:

> But...
> 
> I specifically asked for something that doesn't touch the original
> object. In eventobj.py's docstring there is the following warning:
> 
> 
> Caution : As event management is performed by changing the class of
> the instance, you use eventobj with critical objects at your own
> risk... !
> 
> 
> So, with a lot of thanks for the results sofar ...
> 
> Is it possible?

Well, somehow you have to hook into the object to trap modifications to it, 
no? The other option is via a debugger interface, which works at the bytecode 
level with the interpreter itself. Look into the python debugger (pdb) for 
this. Incidentally, ddd knows how to interface to pdb and can do what you are 
asking about. It's been a long time since I've used it, but I've done exactly 
that with ddd in the past.

Cheers,

f


From Oschler at earthlink.net  Sun Sep 29 12:52:34 2002
From: Oschler at earthlink.net (Robert Oschler)
Date: Sun, 29 Sep 2002 16:52:34 GMT
Subject: Linker can't find library (PyProlog setup)
Message-ID: 

I'm having trouble getting gcc/ld to 'see' the existence of a known shared
library.  I quadruple-checked and I do indeed have the files 'libtermcap.so'
and 'libtermcap.a' in my '/usr/lib/termcap' directory.  'gcc' is being
passed the following library directive '-ltermcap'.  I tried the following
'export' commands in my build script (the echoed results do indeed show
/usr/lib/termcap being properly added to the respective environment
variables):

    export LD_LIBRARY_PATH="/usr/lib/termcap:$LD_LIBRARY_PATH"
    echo "LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
    # run gcc command here

and I also tried:

    export PATH="/usr/lib/termcap:$PATH"
    echo "PATH=$PATH"
    # run gcc command here

and lastly, both:

    export LD_LIBRARY_PATH="/usr/lib/termcap:$LD_LIBRARY_PATH"
    export PATH="/usr/lib/termcap:$PATH"
    # run gcc command here

In all three cases I still get a complaint from 'ld', 'cannot
find -ltermcap'.  What am I doing wrong?

thx




From sholden at holdenweb.com  Tue Sep 17 18:01:42 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Tue, 17 Sep 2002 18:01:42 -0400
Subject: Will "Python in a Nutshell" be too short?
References: 
Message-ID: 

"Hamish Lawson"  wrote ...
> O'Reilly doesn't yet list the forthcoming "Python in a Nutshell" by Alex
> Martelli, but according to Amazon.com's page for the book, it will have
400
> pages. Is that indeed the plan? I know that O'Reilly aims to keep fat out
> of its books, and that Alex is striving to be comprehensive yet concise,
> but I worry that the book's proposed length will simply be too short to
> cover the material I'm hoping will be included.
>
I wil be very surprised if Alex' book does not become the canonical
reference for the language, since his treatment is exceptionally thorough
and (even for him) more than usually precise.

> I regularly consult David Beazley's "Python Essential Reference", but the
> usefulness to me of this otherwise excellent book is compromised by the
> number of (platform-independent and not obsolescent) standard modules and
> packages that had to be left out of the book's 380 pages (htmllib,
> telnetlib, urllib2, CongigParser, unittest, tkinter, xml, etc.).
>
They clearly aren't "Essential" :-)

> Many of us were hoping that "Python in a Nutshell" would not only be a
> comprehensive reference of pretty much all of the modules in the standard
> library that aren't obsolescent or platform-specific, but would also cover
> some of the most popular third-party libraries - e.g. DB-API, PIL,
> mxDateTime, Numeric, win32all, wxPython, mod_python, ReportLab.
>
The omission of some material that particular readers consider desirable is
more or less inevitable, given the different requirements we all have of
this single language. Just the same, I'm sure you will be impressed by what
they *have* found space to include.

> My congratulations to Alex and O'Reilly if they reckon they can somehow
> manage to fit this all into just 400 pages; but if this won't be possible,
> as I worry must be the case, then may I make a plea for the book's length
> to be reconsidered. It would be good to have a one-stop Python reference
> book that would be a suitable companion to the task-oriented "Python
> Cookbook" - I'm hoping "Python in a Nutshell" can still be that book.
>
It's far too late into the production process for such pleas to be
effective, no matter what the individuals concerned may think of their
merits. It's probably at the printers already...

> By comparison, O'Reilly's "Perl in a Nutshell" is 800 pages and has the
> following chapters: Introduction to Perl; Installing Perl; The Perl
> Executable; The Perl Language; Function Reference; Debugging; Packages,
> Modules, and Objects; Standard Modules; CGI Overview; The CGI.pm Module;
> Web Server Programming with mod_perl; Databases and Perl; XML and Perl;
> SOAP; Sockets; Email Connectivity; Usenet News; FTP; Lightweight Directory
> Access with Net::LDAP; The LWP Library; Perl/Tk; Win32 Modules and
> Extensions; OLE Automation; ODBC Extension for Win32.
>
Guess you'll just have to wait and see ...

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------





From TuxTrax at fortress.tuxnet.net  Fri Sep 27 18:05:07 2002
From: TuxTrax at fortress.tuxnet.net (TuxTrax)
Date: Fri, 27 Sep 2002 22:05:07 -0000
Subject: cursor positioning and color
References:  <1b6dca50.0209231022.6fae7f6d@posting.google.com> <30770aa4.0209232242.1e91d9d5@posting.google.com> <1b6dca50.0209260132.6d1d333a@posting.google.com>
Message-ID: 

On 26 Sep 2002 02:32:41 -0700, brrrent Wrote in
Steve Ballmers hair grease:

> bogusdrop at myself.com (TuxTrax) wrote in message news:<30770aa4.0209232242.1e91d9d5 at posting.google.com>...
>> bfarwick at juno.com (brrrent) wrote in message news:<1b6dca50.0209231022.6fae7f6d at posting.google.com>...
>> > TuxTrax at fortress.tuxnet.net (TuxTrax) wrote in message news:...
>> > > Being new to python, I would like to know how one goes about such 
>> > > tasks as precise cursor positioning and output to screen in color.
>> > > 
>> > 
>> > Hi Mathew,
>> > 
>> > Curses is the way to go when using Linux/Unix.
>> > 
>> > Wconio is the way to go when using Microsoft.
>> > You can find in the Vaults of Parnassus.  If you have any trouble
>> > locating it, let me know, I can email it to you.  Small library, works
>> > well.
>> > 
>> > All the best,
>> > 
>> > brrrent
>> 
>> Thanks Brent. Appreciate it. Am I to understand that there are no
>> python libraries that do this as a standard part of the python
>> distribution?
> 
> Mathew,
> 
> A linux or unix distribution without curses is just about unheard of.
> About the only chance of finding a linux installation without curses
> would be in a standalone firewall box.
> 
> WConio is a "tiny" download and very worth it.  Works like a champ. 
> One heck of a lot easier to grasp than curses.  Many thanks to Mr.
> Gonnerman for such a useful library.  If you write a python WConio
> app, why not just send WConio along with the python code.  As I said,
> it's "tiny".
> 
> brent
> 
>  
>> That would be preferable, as it would eliminate the requirement of
>> making
>> the user have curses on their system before they can use the code.
>> 
>> Cheers,
>> 
>> Mathew

Thanks for the info.

I won't be needing WConio, because I don't use windows.

However, I have been tinkering with curses (I use Linux exclusively) and
have found it frustrating. It looks like what I need, but I can't find much
by way of examples on line, as to how to use it.

for instance, when run from a file, this generates an attribute error:

import curses

stdscr = curses.initscr()

stdscr.addstr(0, 0, "Current mode: Typing mode", curses.A_REVERSE) 

_____________

Now that is exactly from the python docs. It croaks on line 3,

stdscr = curses.initscr()

but according to the docs, that initialization should work. Geeze, what
I want to do is so simple, I want to be able to position the cursor and
maybe use some color, in a text application. It shouldn't be this hard.
I had less trouble using NNTPlib.

Cheers,

Mathew

-- 
TuxTrax   (n.) An invincible, all terrain, Linux driven armored assault
vehicle that can take as much fire as it gives ;-)

Yes, I am a Penguin cult high priest. Flipper readings upon request.

ROT13 this email address to mail me:
bar jbeq abg guerr, uvtu qrfreg zna, ng lnubb qbg pbz



From astrophels at yahoo.com  Tue Sep  3 10:17:10 2002
From: astrophels at yahoo.com (Micah Mayo)
Date: Tue, 03 Sep 2002 14:17:10 GMT
Subject: trailing newline in string.splitfields()
Message-ID: 

I was splitting up some fields in a textfile using string.split, which 
works fine, but that it usee ' ' as the delimiter. I've found that some 
of the things I want to split include a space or two, so I've gone to 
using string.splitfields, which also works fine, but for one thing. 
Unlike string.split() it also grabs the newlne('\n') at the end of each 
line.

The way I've worked around this is as such:

var1,var2,var3 = string.splitfields(stringtosplit,',')
list.append(var1)
list.append(var2)
list.append(var3[:-1])

So, I slice of the character, easy enough. And I'm generally satisfied 
with that - but I was wondering if there may be, for the cause of more 
beautiful code, a way to tell string.splitfields() to do it automatically.

Thanks,
Micah



From thomas.heller at ion-tof.com  Thu Sep 26 09:25:00 2002
From: thomas.heller at ion-tof.com (Thomas Heller)
Date: 26 Sep 2002 15:25:00 +0200
Subject: Getting started
References: <00a801c26511$4e084750$df7e4e18@brianspiv1700>  
Message-ID: 

Alex Martelli  writes:

> James J. Besemer wrote:
>         ...
> > Types are otherwise pretty secure in C++ except the "cast" mechanism
> > "foils" the type system and thus allows type errors to occur.
> 
> Actually, unions are at least as bad -- they're not often used
> for type-punning because casts are handier for that, but if you
> took cast aways, people would (ab-)use unions (just like they
> abuse EQUIVALENCE in Fortran for similar purposes).
> 
> Technically I believe that in C++ (not sure about the two ISO
> C standards -- I'm more definite that this was the case in
> Fortran-77 and I believe in Fortran-IV too) storing one union's
> member then retrieving another one puts your program in
> undefined-behavior land.  In practice, I know of no existing
> compiler that goes to the bother of checking (e.g. by storing
> a hidden tag when you store into a union and checking whenever
> you retrieve from it -- even harder if you consider _pointers_
> to the various members of the union).

Hidden fields in a union by the discretion of the compiler?
Don't think that would be allowed by any C standard.

Thomas


From syver-en+usenet at online.no  Mon Sep  9 11:48:14 2002
From: syver-en+usenet at online.no (Syver Enstad)
Date: Mon, 09 Sep 2002 15:48:14 GMT
Subject: win32com.client.gencache and py2exe
Message-ID: 

When using py2exe to make package a python program that uses gencache
to generate wrapper files from COM type libraries, the resulting
installation fails because the win32com system is unable to find the
generated files. Is there any workaround to this problem?z


-- 

Vennlig hilsen 

Syver Enstad


From fgibbons at hms.harvard.edu  Wed Sep 25 09:09:16 2002
From: fgibbons at hms.harvard.edu (Frank Gibbons)
Date: Wed, 25 Sep 2002 09:09:16 -0400
Subject: Python-list digest, Vol 1 #12538 - 15 msgs
In-Reply-To: <20020925052600.22801.4196.Mailman@mail.python.org>
Message-ID: <5.0.0.25.2.20020925090517.02717c70@hms.harvard.edu>

Thanks for the comments, Donn. I was just about to try something like that 
myself. The toy example I posted does not do what I really want to, which 
is to avoid using a temporary file at all, and echo the output from gzip 
directly to the web browser, with appropriate content-type, of course. Your 
blocked input/output seems the way to go.

Thanks again,

Frank

At 01:26 AM 9/25/2002, you wrote:
>It isn't going to be fixed, either, because there are just some
>axiomatic truths in operation here, like "I/O buffers aren't
>infinitely elastic." Since your example doesn't do anything with
>the output, you don't have to shoot yourself in the foot this way.
>Try something like this -
>
>   zip_input = os.popen('gzip -c > popen.gz', 'w')
>   while 1:
>       data = f.read(16000)
>       if not data:
>           break
>       zip_input.write(data)
>   zip_input.close()
>
>The main point is that this allows gzip to write directly to disk.
>If your actual application needs to process the data further at this
>point, you may read it back from disk and write to a new file if you
>like.   Otherwise, if you really want a second pipe, you have to figure
>out how to read some, write some, etc., to keep gzip's output from
>filling up while you're trying to write all its input.

PhD, Computational Biologist,
Harvard Medical School BCMP/SGM-322, 250 Longwood Ave, Boston MA 02115, USA.
Tel: 617-432-3555       Fax: 
617-432-3557       http://llama.med.harvard.edu/~fgibbons




From bobx at linuxmail.org  Thu Sep 12 21:14:21 2002
From: bobx at linuxmail.org (Bob X)
Date: Fri, 13 Sep 2002 01:14:21 GMT
Subject: Coding Style: Quotes
References:  
Message-ID: 

Michael Stenner wrote:

> Since there is no "physical" difference between them, I can't imagine
> why it would matter.  The only reason there "needs" to be two is for
> nested quoting.  Sure, it would be annoying to alternate for each
> string, but beyond that...
Don't you have to escape a single quote within a single quote whereas 
you do not while using a double quote?

i.e. 'It\'s raining'  "It's raining"



From b.maryniuk at forbis.lt  Tue Sep  3 08:59:09 2002
From: b.maryniuk at forbis.lt (Bo M. Maryniuck)
Date: Tue, 3 Sep 2002 14:59:09 +0200
Subject: To all (Re: Servizi Internet)
In-Reply-To: 
References: 
Message-ID: <200209031459.09717.b.maryniuk@forbis.lt>

Somebody can moderate this annoying and  SPAM here?!


On Tuesday 03 September 2002 14:38, Servizi Internet wrote:
> Salve.
> Sono il titolare di "Web Ceating.it", una delle web agency piu' in vista
> sul mercato europeo. Volevamo informarLa che la nostra azienda si
> mette a Sua completa disposizione per qualsiasi esigenza o servizio Lei
> desideri. Ci occupiamo principalmente di:
>
> * Servizio Hosting e registrazione domini .com/.net/.org/.biz/.it;
> * Registrazione nei principali motori di ricerca;
> * Posizionamento garantito in testa ai motori di ricerca;
> * Creazione Siti Personali e Aziendali;
> * Consulenza Web Marketing;

[SKIPPED]

-- 
Regards, Bogdan

If the facts don't fit the theory, change the facts.
                -- Albert Einstein




From max at alcyone.com  Wed Sep 25 15:06:56 2002
From: max at alcyone.com (Erik Max Francis)
Date: Wed, 25 Sep 2002 12:06:56 -0700
Subject: Getting started
References:      
Message-ID: <3D920950.323B25B3@alcyone.com>

"James J. Besemer" wrote:

> However "lame" or "weak" you may consider this feature to be, it does
> NOT constitute "weak typing" per the formal definition.  This is
> simple
> polymorphism, as you seem to acknowledge, same in Perl as in Python.

The problem here is that there is no official "formal definition."  Some
use "weak typing" to mean any type system where the typing can be foiled
by casts; some use it to mean any system where operations, not the
objects themselves, determine the types of the objects.  (I favor the
latter definition, since it carries more information about the
language.)  This is simply a case of differing terminology.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Nothing is true -- all is permissible.
\__/ Hassan i Sabbah
    Maths reference / http://www.alcyone.com/max/reference/maths/
 A mathematics reference.


From greek_bill at yahoo.com  Wed Sep 18 16:56:37 2002
From: greek_bill at yahoo.com (Morfeas)
Date: Wed, 18 Sep 2002 21:56:37 +0100
Subject: [newbie] Calling Python from C++
Message-ID: <8L5i9.841$Ew4.62552@newsfep2-gui>

my struggle to C++ and python to like each other continues....

I've now managed to make my C++ classes visible from python, so I can write 
python scripts that use my C++ code. great!

Now what I need to do is execute python from within C++. Reading from the 
manual this involves embedding the python interpreter into my app. That in 
itself doesn't sound too bad for simple cases. For example, I think I know 
how to call a python script to instantiate some C++ objects and return them 
to the main app.

What I want to do though, is to execute a python script that operates on an 
existing object (that may or may not have been instantiated from Python). 
So my question is : How do I pass an object into the python script?

I've seen in the manual how a python script can access the main app, but 
it's not really what I want.

I suppose a hack would be to place the object I want to operate on on some 
default position (say within a holder class), and then the python scripts 
gets that object from that holder class. Is there a clear / more elegant 
way?

I'm kind of relying on SWIG to do all the data conversion to and from 
python, so I don't really know much on this topic!

Thanks again,

Morfeas


-- 
www.freecfm.com/m/morfeas


From stephen.boulet at motorola.com  Fri Sep  6 17:51:13 2002
From: stephen.boulet at motorola.com (Stephen Boulet)
Date: Fri, 06 Sep 2002 16:51:13 -0500
Subject: py2exe and a single exe file?
Message-ID: <3D792351.3070008@motorola.com>

I'm trying to get py2exe to work for me, and I must be doing something 
wrong.

I have a script that uses easygui (which uses Tkinter) and Numeric. It 
also imports a small module from the same directory that the script 
resides in.

I try building it like this:

    python setup.py py2exe -d N:\ -i easygui

It builds and runs, but only with the other stuff in the build directory 
with the generaged exe. The other stuff is:

   tcl directory containing tcl8.3 and tk8.3 directories
   _numpy.pyd
   _sre.pyd
   _tkinter.pyd
   multiarray.pyd
   umath.pyd

What I would like to accomplish is just having a single exe file lumping 
everything together. Is this possible?

-- Stephen



From mcfletch at rogers.com  Fri Sep 27 18:20:13 2002
From: mcfletch at rogers.com (Mike C. Fletcher)
Date: Fri, 27 Sep 2002 18:20:13 -0400
Subject: Better terminal for windows?
References: <3D94B037.2020202@motorola.com>  <3D94D1DD.40407@motorola.com>
Message-ID: <3D94D99D.9050109@rogers.com>

8<_____ setup command completion.reg ______
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"CompletionChar"=dword:00000009
"EnableExtensions"=dword:00000001
"PathCompletionChar"=dword:00000009

HTH,
Mike

Stephen Boulet wrote:
> Gerhard H?ring wrote:
...
>> cmd.exe isn't *that* bad once you activate tab completion in the
>> registry. Have you done that?
> 
> 
> Nope. How do you do that? I couldn't figure it out just looking through 
> regedit.
...
_______________________________________
   Mike C. Fletcher
   Designer, VR Plumber, Coder
   http://members.rogers.com/mcfletch/





From duncan at NOSPAMrcp.co.uk  Tue Sep 24 09:00:27 2002
From: duncan at NOSPAMrcp.co.uk (Duncan Booth)
Date: Tue, 24 Sep 2002 13:00:27 +0000 (UTC)
Subject: list problem
References:     
Message-ID: 

Alex Martelli  wrote in 
news:tCYj9.157570$pX1.5675986 at news2.tin.it:

>> If you are going to use reduce, then you would be better off writing:
>> 
>>    import operator
>>    reduce(operator.add, x)
> 
> Maybe (marginally).  But timing things is often a good idea:

Apologies for not being clearer. I actually felt that using operator.add 
read more cleanly than using a lambda. I should have made it more obvious 
that was what I meant. I wouldn't particularly worry which is faster unless 
one was actually proven to be a bottleneck, at which point the OP might 
well find the best way to optimise would be to not end up with nested lists 
in the first place.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?


From peter at engcorp.com  Fri Sep  6 08:55:40 2002
From: peter at engcorp.com (Peter Hansen)
Date: Fri, 06 Sep 2002 08:55:40 -0400
Subject: .py to .pyc
References: 
Message-ID: <3d78a5b2$1@news.sentex.net>

andrea.baglioni at redturtle.net wrote:
> Hi everybody,
> 
> I'm a python newbie and i've a problem.
> 
> I want to compile a python file called File.py and i want to produce a file
> called File.pyc, so i do
> 
> python File.py

Actually, that won't do it.  Python only caches the bytecode in a .pyc
file for modules imported by the main routine.  Even if the above
worked properly, it still wouldn't leave you with a .pyc.  Besides,
why do you care about the .pyc anyway?  It's just an optimization
that Python even creates it for you in some cases.

That said, you should be able to get one by just running the interactive
prompt and doing "import File", if File.py has no errors.

> I always find the following error:
> 
> Traceback (most recent call last):
>   File "File.py", line 18, in ?
>     import Globals, StructuredText, string, utils, re
> ImportError: No module named Globals
> 
> Can anybody help me to find the problem? I think it's a problem of
> $PYTHONPATH and $PYTHONHOME but i'm not sure.

Why do you think that's the problem?  It seems more like that the
problem is that you are trying to import modules that are actually
part of the Zope infrastructure (if I recognize the above line),
and you'll likely have far more problems doing that than just what
you've faced so far.  Maybe some more background on what you are
trying to accomplish would help us answer more thoroughly.

-Peter



From loewis at informatik.hu-berlin.de  Mon Sep 16 11:13:24 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=)
Date: 16 Sep 2002 17:13:24 +0200
Subject: python performance
References: <3D84E66F.6020701@linux.ie>    
Message-ID: 

Syver Enstad  writes:

> What about Psyco?

Psyco does not optimize access to global variables.

Regards,
Martin


From mark at mceahern.com  Tue Sep  3 20:22:09 2002
From: mark at mceahern.com (Mark McEahern)
Date: Tue, 3 Sep 2002 19:22:09 -0500
Subject: how do i know i built python --with-threads
Message-ID: 

Suppose somebody else installed python on my system--e.g., my evil twin--and
I wanted to determine whether the python was built like so:

  ./configure --with-threads --without-pymalloc

How would I do it?

I'm just trying to do some sanity checking of the Python 2.1.3 I installed
for Zope.

Thanks,

// mark

-




From syver-en+usenet at online.no  Tue Sep 17 08:58:11 2002
From: syver-en+usenet at online.no (Syver Enstad)
Date: Tue, 17 Sep 2002 12:58:11 GMT
Subject: threads or queue for this task
References:     <6dFh9.120102$pX1.4321019@news2.tin.it>
Message-ID: 

Alex Martelli  writes:

> > Bounded queues are A solution to some problems but not The solution
> for
> 
> > all situations.
> 
> Of course not!  Never did I assert nor imply that you should
> make ALL of your Queue instances bounded -- that would be
> silly indeed.  But the ability to make SOME Queue's bounded,
> and still handle them without fuss, IS important in a vast
> enough number of cases that ruling this possibility out is
> a serious didactic mistake, IMHO.

When should they not be bounded? 

Would it perhaps be easier to program
with Queue.Queue's if they had a default maxsize other than infinity?
That would force the programmer to consider unblocked put's and
setting the maxsize to number reasonable for his/her application.
 

-- 

Vennlig hilsen 

Syver Enstad


From michaels at one.net  Wed Sep 11 22:08:35 2002
From: michaels at one.net (Michael Schneider)
Date: Wed, 11 Sep 2002 22:08:35 -0400
Subject: [FEEDBACK] Is this script efficient...is there a better way?
References:   
Message-ID: <3D7FF723.3050005@one.net>


Bob X wrote:

>
>> 1) readlines() loads the entire file into a list so if you have a 30+ 
>> mb file you just ate 30+mb of memory.  Try using xreadlines() 
>> instead, it reads the file line by line and is much more memory 
>> friendly.
>
> Very cool...I had missed that! 


It is much slower though.  I am not sure about your config, but I am 
running with a Gig of memory.
I would much rather have the speed then the  30 mb of memory.  Again, 
check your config.




From jacek.generowicz at cern.ch  Thu Sep 19 09:30:30 2002
From: jacek.generowicz at cern.ch (Jacek Generowicz)
Date: 19 Sep 2002 15:30:30 +0200
Subject: strong/weak - dynamic/static [Was: Getting started]
References: 
Message-ID: 

Sorry to go off at a tangent ...

"Lance"  writes:

> Hi All,
> 
> Last night I attended a Weak typing, C++ Templates, and Python talk by Bruce
> Eckel. It was great, my introduction to Python.
> 
> I'm sold on Python and weak typing. I want to write a graphics module that
> will link to a C application, permitting scatter plots, bar charts, log
> scales, etc. I suppose the Python Imaging Library will be used for this
> purpose.

A quick google search suggests that Bruce Eckel really claims that
python is weakly typed (at least more weakly typed than C++).

I've seen these claims made so often now (a quick google search
suggests that the majority of opinions in netspace favour the "Python
is weakly typed" thesis) that I am seriously beginning to doubt my
understanding of the concepts of weak, strong, dynamic and static
typing.

Could someone provide a serious reference (i.e. something which would
have gone through some sort of editorial/peer/technical review, rather
than someone's random opinions on the web) explaining or defining the
concepts of weak, strong, dynamic and static typing.

Thanks,


From erikprice at mac.com  Thu Sep  5 11:51:09 2002
From: erikprice at mac.com (Erik Price)
Date: Thu, 5 Sep 2002 11:51:09 -0400
Subject: newbie problem: use socke lib to retrieve one web page:
In-Reply-To: 
Message-ID: <4BA03A21-C0E7-11D6-984F-00039351FE6A@mac.com>

On Wednesday, September 4, 2002, at 11:53  PM, koko wrote:

> I write this to retrieve one web page using socket lib.
>
> # retrieve webpage
> import socket
> HOST='www.uic.edu' # remote host
> PORT=80     # remort port
> s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> m="""GET /home/events.shtml HTTP/1.0
> From: hh at uic.edu
> User-Agent: test/1.0
> """
> s.connect((HOST,PORT))
> s.send(m)
> data=s.recv(4096)
> print data
> s.close()

Works for me:

 >>> import socket
 >>> host = 'www.uic.edu'
 >>> port = 80
 >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 >>> s.connect((host, port))
 >>> header = """HEAD /home/events.shtml HTTP/1.0
... From: hh at uic.edu
... User-Agent: test/1.0
...
... """
 >>> s.send(header)
72
 >>> data = s.recv(4096)
 >>> print data
HTTP/1.1 200 OK
Date: Thu, 05 Sep 2002 15:40:00 GMT
Server: Apache/1.3.26 (Unix) PHP/4.1.2 mod_perl/1.27 mod_ssl/2.8.10 
OpenSSL/0.9.6
Connection: close
Content-Type: text/html


 >>> s.close()


I used the HEAD method instead of GET for brevity.  But GET works too.



Erik






--
Erik Price

email: erikprice at mac.com
jabber: erikprice at jabber.org




From jb at cascade-sys.com  Sat Sep 28 04:38:57 2002
From: jb at cascade-sys.com (James J. Besemer)
Date: Sat, 28 Sep 2002 01:38:57 -0700
Subject: How do I set-up Multiple socket connections
References: <002a01c26604$b515c3c0$0100a8c0@mshome.net>
Message-ID: <3D956AA1.5070806@cascade-sys.com>

Kat & Huw wrote:

> Ok, I want to iterate through a server IP list and establish
> multiple socket connections to the various IP address' in the list.
>  
> I can do the iterations and I can make single connections, but I can't
> work out how I can connect to several address at once.
>  
> I understand that a socket is closed, or closes after its done getting 
> the ACk or
> whatever after sending a request, but how on earth do I connect to like 5
> addresses at once?

This is a complicated problem.

Two general solutions suggest themselves.

A. You can use the select system call to wait on multiple socket I/O 
operations at once.  It waits until one is ready to proceed and it tells 
you which one(s) are ready.  Read the doc.  You would have some 
non-trivial state machine logic to go with it to translate the select 
results into the various i/o functions on individual sockets.  On Unix, 
select will multiplex socket AND regular I/O.  On Windows select only 
works for sockets.

B. You can dispatch multiple threads, one for each host you wish to 
communicate with.  Each thread would do the initial socket() and 
connect() to connect to the remote host and then send() or recv() as 
appropriate.  Then it's up to you to coordinate the results.  If there 
is no coordination to do, e.g., if the results all go to different 
files, then you can skip that part.  If you do need to coordinate 
results, e.g., to funnel all results to a single sink, the Queue class 
likely will be useful.

My preference is alternative B and I have used it successfully on a 
number of projects on Linux.  I have heard rumors that threads and 
socket I/O is problematic on some platforms but I don't know which ones.

Regards

--jb

-- 
James J. Besemer		503-280-0838 voice
2727 NE Skidmore St.		503-280-0375 fax
Portland, Oregon 97211-6557	mailto:jb at cascade-sys.com
				http://cascade-sys.com	







From glingl at aon.at  Thu Sep  5 17:02:39 2002
From: glingl at aon.at (Gregor Lingl)
Date: Thu, 05 Sep 2002 23:02:39 +0200
Subject: German Umlaut Problem with raw_input in IDLE
Message-ID: <3D77C66F.4040305@aon.at>

Hi

This message concerns using IDLE with German
alphabet.

Some month ago I copied sitecustomize.py with
appropriate locale-setting to C:\Python22\Lib
thanks to an advice from some other mailing list.

This worked well until today I made the observation,
that in IDLE raw_input doesn't work correctly:

 >>> a = raw_input("H?? ")
H?? Tsch?s
Traceback (most recent call last):
  File "", line 1, in ?
    a = raw_input("H?? ")
TypeError: object.readline() returned non-string
 >>>

Printing H?? works correctly, reading in Tsch?s doesn't!

Consequently I cannot execute programs with
raw_input from IDLE, if the expected answers (inputs)
may contain "Umlaute". Those same programs,
however, can be executed from the commandline.
And also the interactive Python interpreter can execute
raw_input statements even when Umlaute are input.

So I think, this must be a problem of IDLE.
I must confess, I do not understand the error message.

Does somebody know a patch or a workaround?
Thanks

Gregor Lingl



From aleax at aleax.it  Mon Sep 16 10:07:30 2002
From: aleax at aleax.it (Alex Martelli)
Date: Mon, 16 Sep 2002 14:07:30 GMT
Subject: threads or queue for this task
References:    
Message-ID: 

robin at execulink.com wrote:
    ...
> For example, I really don't know what "proper design" I should use in
> this case. Any sample code?

IMHO, proper design of a multithreaded app in Python almost invariably
uses instances of Queue to for inter-thread communication.  I do not
understand all the details of your requirements, but, roughly speaking,
I gather: you have some dedicated working threads, each of which must
repeatedly run the same function on all "work-units" sutable for that
thread; and another thread that is able to determine what work units
are suitable for what other threads.  In this case, you can have a
separate Queue for each dedicated thread.  Each such thread peels the
next work-unit destined for it from its Queue, performs the work, then
goes back to peeling.  The supervisor thread just posts work units to
the appropriate queues.

If you can post more precise/accurate/detailed specs, I'll be glad
to try to help in more detail.

> The interface to Queue is deceptively simple. Are there constructs to
> avoid or performance trade-offs to different methods? Again, any
> explicit code (or at least explicit help as to which methods are
> preferable) would be appreciated.

The no-wait methods, or explicit timeouts on the normal methods that
do wait, are often symptoms that you're polling.  IF you can avoid
polling (that's not always possible, alas), your performance will be
better: a sleeping thread consumes close to no resources, one that is
polling consumes resources in rough proportion to the frequency with
which it's polling (and suffers response delays in inverse proportion
to it).


> I am also put off by the description of the Queue Object, particularly
> methods like empty() which says: "Return 1 if the queue is empty, 0
> otherwise. Because of multithreading semantics, this is not reliable."
> 
> If it's not reliable, then what's the point of it existing? Why is it

Because some people like "purely indicative" methods to exist.

> not reliable? (I imagine simply because the thread doing the checking
> could be superceded by the thread that implements the Queue in the
> time it takes for the method to return and be acted upon.) Is it just

Of course.  Basically, when method empty returns 1, all you know is
"there was an instant in the reasonably recent past in which this
queue instance was empty" -- this, of course, has nothing to do with
whether the queue is empty now.  Similarly, when empty returns 0, then
there was an instant in which the queue was non-empty, but, again,
this doesn't necessarily matter much.  Things may be a bit better
when your overall architecture is such that only one thread ever
posts to a given Queue, and/or only one thread ever gets stuff from
it: in such case, you may be able to prove stronger and more useful
statements.  For example, if the thread calling the empy method is
the only thread that ever posts stuff to the Queue, then if the Queue
was empty when empty() was running, and the thread knows it has
posted nothing more, then the Queue is still empty.

> in certain cases that it's not reliable? How can one code if you don't
> reliably know when a Queue is empty or full?

By just trying to post, and/or to get, stuff from the Queue, and
sleeping until the action can be performed; or, polling issues
apart, from performing e.g. a get-nowait operation in a try/except and
treating the exception, if it comes, as a VERY reliable indication
that, yes, the Queue WAS indeed empty at the time we tried to peel
an entry off it.


Alex



From jknapka at earthlink.net  Wed Sep 11 13:45:23 2002
From: jknapka at earthlink.net (Joseph A. Knapka)
Date: Wed, 11 Sep 2002 17:45:23 GMT
Subject: Variables vs. names
Message-ID: <3D7F8132.2D5CEC24@earthlink.net>

Hi folks,

I've been using Python for some time now, and I am
completely cognizant of and comfortable with its
semantics. However, I'm curious about something:

I understand that a Python "variable" is really
just a dictionary key; fine. In other languages,
instead of "naming" a dictionary entry, a
variable might directly "name" a chunk of
storage. So other than the layer of indirection
introduced by the dictionary mapping, what is
the practical significance of "names bound to values"
vs "variables with values"? Are there languages that
achieve Python's semantics using "real"
variables? Java's semantics seem pretty much
identical to Python's in this respect, yet
nobody in the Java community will object if
you call a thing-with-a-name-and-a-value a
"variable".

(And does an instance of a class with __slots__
have "names bound to values" for its members, or does
it have actual "variables"?)

Just curious,

-- Joe
  "I'd rather chew my leg off than maintain Java code, which
   sucks, 'cause I have a lot of Java code to maintain and
   the leg surgery is starting to get expensive." - Me


From SBrunning at trisystems.co.uk  Wed Sep  4 10:53:34 2002
From: SBrunning at trisystems.co.uk (Simon Brunning)
Date: Wed, 4 Sep 2002 15:53:34 +0100 
Subject: How to force built-in commands over imported.
Message-ID: <31575A892FF6D1118F5800600846864DCBD721@intrepid>

> From:	Maurice van de Rijzen [SMTP:maurice at akst.tn.tudelft.nl]
> There is a built-in commans called open(fileName). There is also a 
> open() command in the os-module open which needs more than the fileName. 
>   Originally I didn't import the os-module and everything worked fine. 
> However, when I imported the os-module I received an error that open 
> needed more arguments. How can I force to take the built-in open() 
> instead of the open() in the os-module.
 
You are, I assume, importing 'os' as follows:

from os import *

*Don't* *do* *this*. Use:

import os

instead. There *are* reasons for using the former method, but they are few
and far between. The latter form should always be the one you use unless you
have a good reason.

Cheers,
Simon Brunning
TriSystems Ltd.
sbrunning at trisystems.co.uk




-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.



From wilk-spamout at flibuste.net  Mon Sep 30 15:35:12 2002
From: wilk-spamout at flibuste.net (William)
Date: 30 Sep 2002 21:35:12 +0200
Subject: redhat8
References: <873crr4fy6.fsf@flibuste.net> 
Message-ID: <87ofafxocv.fsf@flibuste.net>

Anthony Tuininga  writes:

> According to the release documentation:
> 
> Python 2.2.1 is on the CD.

great, but i would like to know if it's the default version, linked with
/usr/bin/python...

-- 
William Dod? - flibuste.net
http://wikipython.tuxfamily.org


From gerhard.haering at gmx.de  Fri Sep 27 18:20:29 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: Sat, 28 Sep 2002 00:20:29 +0200
Subject: Is Boost Python version 2 ready?
In-Reply-To: <6D4l9.12184$Lg2.3654433@news2.news.adelphia.net>
References:   <6D4l9.12184$Lg2.3654433@news2.news.adelphia.net>
Message-ID: <20020927222029.GB7781@lilith.ghaering.test>

* Bob X  [2002-09-27 22:05 +0000]:
> Is there a page up saying what 2.2.2 will give us?

Bugfixes only. There's a wiki page, probably mostly interesting for
Python committers: 

http://manatee.mojam.com/py222wiki/

-- Gerhard



From dubal at khimjiramdas.com  Thu Sep  5 02:55:53 2002
From: dubal at khimjiramdas.com (J Dubal)
Date: 4 Sep 2002 23:55:53 -0700
Subject: How to install informixdb-1.3 for python2.2 on RH7.3?
Message-ID: 

Hello good people!

As mentioned in its readme, informixdb-1.3 compiles, installs and
works with the stock python 1.5.2 of RH7.3. However, when we try to
compile it for python 2.2.1, informixdb's ./configure fails because it
is looking for Makefile.pre.in which is not there in python 2.2.1. It
appears that someone has to repackage informixdb with distutils. How
to do this? In the meanwhile can we install this manually? I do not
understand Makefile.pre.in. Please help. Thanks in advance.
Dubal.


From jb at cascade-sys.com  Tue Sep 17 02:54:15 2002
From: jb at cascade-sys.com (James J. Besemer)
Date: Mon, 16 Sep 2002 23:54:15 -0700
Subject: Source code
References:      <3d868ccc$1@news.sentex.net>  <7xfzw9qgo7.fsf@ruckus.brouhaha.com>
Message-ID: <3D86D197.9050806@cascade-sys.com>

Paul Rubin wrote:

>"James J. Besemer"  writes:
>  
>
>>Furthermore, even if you formally assign the copyright to somebody
>>else, I understand ownership eventually reverts to the original author
>>after a lengthy period (45 years or something).  Evidently it
>>preserves the copyright for the heirs of the author.
>>    
>>
>
>I heard the opposite.  In fact part of the debate before the 1976
>

That was over 25 years ago and a considerable amount of copyright 
legislation has been passed since.

My above blanket statement is not 100% correct.  It IS possible to 
permanently transfer rights to a copyrighted work.  However, the 
contract has to be "just so" to meet all of the provisions of the law. 
If the contract does not meet all of the statutory criteria, then the 
original author retains the right to terminate transfer of the copyright 
after 35 years (though it's not automatic, as I implied).

I dunno when the various laws came into effect (mid- to late-80's I'm 
guessing) but since before I started my own company in 1994, lawyers 
were very particular about the wording of contracts where copyrightable 
works were being created.  

Anyway, here's a document outlining the legal hoops relevant to 
retaining or transferring copyrights per current US legislation:

    http://tenonline.org/art/ip1/0001.html

--jb

-- 
James J. Besemer		503-280-0838 voice
2727 NE Skidmore St.		503-280-0375 fax
Portland, Oregon 97211-6557	mailto:jb at cascade-sys.com
				http://cascade-sys.com	







From jb at cascade-sys.com  Wed Sep 25 14:45:32 2002
From: jb at cascade-sys.com (James J. Besemer)
Date: Wed, 25 Sep 2002 11:45:32 -0700
Subject: Getting started
References:     
Message-ID: <3D92044C.9050801@cascade-sys.com>

   
Steve Holden wrote:

>"James J. Besemer"  wrote in message
>news:mailman.1032567390.29374.python-list at python.org...
>  
>
>>Alex Martelli wrote:
>>
>>>$a = "2.3";
>>>$b = 45;
>>>print $a+$b;
>>>
>>>emitting 47.3 is pretty close to what I consider "weak typing".
>>>
>>I don't see why you call this "weak typing".  In Perl, the "+" operator
>>is defined to work with strings or numbers.
>>    
>>
>
>Well, it seems pretty weak to me that the *operator* has to examine the
>types of its arguments in order to know which operation to perform. Can we
>say polymorphism?
>

However "lame" or "weak" you may consider this feature to be, it does 
NOT constitute "weak typing" per the formal definition.  This is simple 
polymorphism, as you seem to acknowledge, same in Perl as in Python.

The proper definition of "weak typing" is that in an otherwise strong 
typing system there are ways to cheat the system and apply illegal 
operations to certain types.  The quintessential example is in C++, 
where, despite a fairly robust and secure type system, you always can 
cast objects to the wrong type and force illegal operations on them.   
This is in contrast to Strong typing, where such "type errors" are 
strictly prohibited.  These type errors are not possible in Python nor 
in Perl.  Thus neither is "weakly typed" in the formal sense.  They're 
both strongly, dynamically typed.  

You say "the operator has to examine the types..."  as if this is 
somehow different from Python.  But, e.g., Python's "*" operator has to 
examine it's arguments in order to know which operation to perform, does 
it not?   You don't like to think of it that way but if the notion 
applies to Perl then it applies equally well to Python..  

In FACT, if you examine the source code, this is EXACTLY how both 
languages are implemented.  There is but one each binary "+" and "*" 
operators in Python's byte codes.  At runtime, the interpreter takes the 
operator and then LITERALLY "examines the types of it's arguments (on 
the top of stack) in order to know which operation to perform".  E.g., 
binary_multiply "looks" at it's arguments to decide if  it's to perform 
a string operation, a list operation or a numeric computation. 
 Similarly, the binary subscript has a special test inline if the left 
argument is a List and the right one is an Integer, in which case it 
directly executes PyList_GET_ITEM(); otherwise, it calls the more 
generic PyObject_GetItem(), which in turn continues the decision tree 
down for each valid combination of operand types, ultimately throwing an 
exception if the combination is invalid.

Now that's how it WORKS.  Underneath the hood, Python is implemented in 
flat C code that emulates objects.  The code "switches" on operators 
that in turn inspect object types to decide what specific operation to 
perform.  Now, in principle, you also can "say" that operations are 
defined on a per object basis, since that is the abstraction ultimately 
provided and because we all prefer to view the universe from that 
perspective.  But in any case, the implementation and the fundamental 
abstraction are the same for both Python and Perl.  You can call it OO 
or you can call it operator-inspection.  The difference is merely your 
point of view.

The only real difference between the two languages is the particular 
choice of operators and valid operands  -- and arguably the relative 
wisdom of those choices.

>>This all is no different in principle from Python's:
>>
>>    a = 2.3
>>    b = 45L
>>    print a + b
>>
>>and getting 47.3.  The "+" operator is defined for floats and also for
>>longs.  Since they're all "numbers" it would seem really strange if they
>>did not interact naturally like this.  But fundamentally they're
>>distinct types as "type( 2.3 )" and "type( 45L )" illustrate.
>>
>>    
>>
>It seems very different to me. 
>

I agree "+" is too subtle an example.  "*" is better.

>For example, how does the Perl "+" operator
>find out about a new addable type? 
>

I don't know.  Look it up and you tell me.   In Perl, the greater number 
of builtins are keyword based and Perl classes definitely CAN 
override/overload builtin keywords.

>Is Perl even able to integrate its
>intrinsic data objects with user-defined types? 
>

No.  I don't think so.  Perl's OOP features have lagged behind Python's. 
 And in all fairness, it's a new feature to Python.

>Can we say inheritance hierarchy? 
>

Yes, Perl's OO mechanism includes inheritance.

>In Python it's easy to define methods to integrate your own
>classes into the language's architecture. I could never discern enough
>architecture in Perl to see how to do that, though I willingly accept that
>this deficiency might be in me rather than in Perl.
>

Certainly, Perl's object model is not as good as Python's.  At best, 
it's more like Python's was before type/object unification (and it's not 
even that good).  Nevertheless, the Quality of the object model (and the 
questions you raise above) is IMMATERIAL to my original claim, regarding 
weak vs. strong typing (in the formal sense).  In fact, weak vs. strong 
typing is a distinction that applies equally well to languages without 
any OOP support at all.  It has to do with "type safety", not the 
OOP-ed-ness of the language.  It's not a sliding scale, 0 to 100%; it's 
binary, black vs. white.  Can the user violate the type rules of the 
language (whatever they may be), yes or no?  If yes then Weak; if not 
then Strong.  Perl, like Python, protects its objects with dynamic 
runtime checks, thus it is strong not weak.

I think this is the KEY misunderstanding when you and others attempt to 
argue with me.  Read Cardelli's paper.  Either you concede this point 
and thus my original premise, or else you're simply wrong and I'll have 
done all I can to set you straight.


>>Perhaps an even better example is the "*" operator:
>>
>Not really. Python has strongly-typed data with late binding of methods and
>operators. This is an organised way to obtain the results you have so far
>quoted.
>

Perl and Python work exactly the same way in this regard.  

The confusion is that Perl defines many more primitive operations and 
defines meaning for many operator/type combinations where Python does 
not.  Now you can argue that Perl is flawed in this way but in principle 
there is no difference in how the two work.  Both are absolutely 
deterministic in what specific operation is applied to what object in 
every legal context.  Only Perl defines extra ones, such as arithmetic 
on strings, that Python does not.

One way to think about Perl's "+" and "." operators formally is that 
there actually are several of them, all producing similar (but subtly 
different) results.  

    string + string -> number
    string + number -> number
    number + string -> number
    number + number -> number
    string . string -> string
    string . number -> string
    number . string -> string
    number . number -> string
    list + list -> list
    string * number -> string
    list * number -> list

    (many others)

In principle, it's no different from Python (except in choice of operators):

    string + string -> string
    number + number -> number
    list + list -> list
    number * number -> number
    string * number -> string
    list * number -> list

    (many others)

Fundamentally it's just polymorphism.  This way, you don't have to think 
about the "operators making a decision," if you don't like.   Whether 
the operator or the object "decides" really is an implementation detail. 
 The abstraction is that there exists a thorough enumeration of  valid 
combinations of operations and object types that maps onto a set of 
operations.  In this fundamental sense, the languages are the same.

Of course, each may have some back-door C module that implements "peek" 
and "poke" or some mechanism that does in fact allow type safety to be 
violated.  But I'm intentionally disregarding limit cases such as that; 
certainly they do not constitute the overall intent of either language.


>>Anyway, why should "2" + 5 == 7 be all that much stranger than "2" * 5
>>== "22222"?  If the operation is unambiguous and useful what rule would
>>it break?  Personally, I think Python would be improved slightly by
>>adding this conversion.  It's convenient and there's ample precedent in
>>other languages (Awk, Snobol, Icon, Perl, etc.).  But I am sure that
>>notion will provoke howls of protest from the True Believers.
>>
>Not at all. If I thought such a suggestion would be taken seriously I might
>go so far as to advise against that, but I don't see this being a religious
>debate.
>

Many other languages have worked this way.  And it certainly has some 
utility.  If you don't like it, fine, but there's ample precedent by 
smarter inventors than you and me that indicate it's not a crazy idea.

Anyway, I'm not arguing for the feature's inclusion into Python.  My 
only point is it does not make Perl "weakly typed" in the formal sense.


>For some meaning of strong, I suppose, but please don't bother to define
>what this is.
>

EEEK!  Sarcasm.  ;o)

These terms has been bandied about so much on this list that I thought 
it was generally understood.  Geeze, they're part of the standard 
mantra.  And I didn't start the discussion; I only took issue with 
Alex's misclassification of Perl.  Curiously, this thread reveals that a 
lot of people don't have the first idea what these terms mean..

Anyway, I did give a clear definition at the start of this post, with 
references to back it up.  Also, if you do a google search, you'll find 
a bunch of hits that are consistent with my definition (along with some 
that equate "weak typing" with "dynamic typing", which I'm sure 
everybody here will agree is practically the Opposite of what we all 
mean (perhaps this is why we're confused ourselves)).  

Equates weak and dynamic [Bogus]

   http://www.lispme.de/lispme/doc/lm_sema.htm
   http://www.perlmonth.com/perlmonth/issue5/modules.html
   
http://www.usenix.org/publications/library/proceedings/%20tcl98/full_papers/howlett/howlett.pdf 

   http://www.ruby-lang.org/en/testimony.html

Strong is Safe vs. Weak is Unsafe (specifically preventing vs. allowing 
"type errors"):

   
http://www-lp.doc.ic.ac.uk/UserPages/staff/ft/alp/net/typing/strong.html 
(weak is unsafe)
   http://www.cise.ufl.edu/~jnw/OOCourse-95/Lectures/Jan.31.html (strong 
is safe)
   http://www.cs.auc.dk/~normark/prog3-01/html/notes/fu-intr-1-book.html 
(lead to errors)
   
http://216.239.39.100/search?q=cache:oBq2r3PwR1kC:www.cs.cornell.edu/courses/cs412/2002sp/lectures/lec12.ps+definition+weak+typing&hl=en&ie=UTF- 



Weak == otherwise Strong + Means to override e.g., C:

   http://www.wkonline.com/d/weak_typing.html
   http://www.wkonline.com/d/strong_typing.html ("strict enforcement")

"Strong types for weak minds" [a cute quote I thought y'all'd enjoy] -- 
strong typing is either overly restrictive (Pascal) or allows overrides 
(C) [which is definition of] "weak typing".

   http://people.cs.uct.ac.za/~gaz/teach/cpl/lect2.ppt


Read and understand.

>Well, considering that the %r and %s conversion types are currently
>documented as
>
>"""
>r String (converts any python object using repr()).
>s String (converts any python object using str()).
>"""
>
>it should hardly be surprising that conversions take place. 
>

Perl documents the (surprising to you) behavior of "+".  If it's working 
as advertised it's standard behavior cannot be considered a "type error" 
and thus it's not a sign of weak typing.

>Such
>conversions, however, are not intrinsic to the *language*, but to the *data*
>(where the type is significant) - Python goes so far as to expose explicitly
>how the conversions are performed, and they will clearly work for any object
>with a suitable (returns a string) __repr__() and/or __str__() method. 
>

True but irrelevant to strong vs. weak typing.

>Just
>to clarify the nature of this, try
>
>    "%6.2f" % 2.6
>
>and then try
>
>    "%6.2f" % "2.6"
>
>and we'll see if you still feel that string formatting 'treats numbers as
>strings in a string "context"'.
>

I said it treats numbers as strings, not the reverse.  I'll let this go, 
though, as I am NOT advocating such a change to Python.

>By contrast Perl seems a little muddled, and I personally think it's no
>accident that Wall's own writing tends to stress the significance of
>*context*. The rules are quite explicit in Python, clouded in Perl. Of
>course you must take this as a dim memory frmo one who never claimed to
>understand Perl that well in the first place (I used to program Perl, but
>I'm all right now ;-).
>

I agree Perl is muddled.  It's a pile of crap.  It's a hack on a hack, 
raised to the 1e5th power.  Perl's notion of scalar vs. array "context" 
is the worst idea ever.  Blah blah blah.  I agree it's a crock.  But 
that does not make the language "weakly typed".  It's strongly typed, 
like Python, as it does not allow "type errors."

>It's also possible to enjoy some of the benefits of prison by simply
>refusing to go outside. Your very confession of C's and C++'s weaknesses
>highlights the fact that even "strongly typed" languages have problems
>enforcing the rules (whose value I anyway challenge except for the specific
>promotion of execution efficiency). Python is just a bit less anal :-)
>
These deficiencies of C and C++ make them "weakly typed" by definition. 
 They're good examples while Perl is not one.  Yes, otherwise "strongly 
typed" languages are instead weak if they permit cheating.  Pascal would 
be strong if a few tiny cracks were plugged.

I had an even longer reply to this thread that was rejected for being 
too long.  I think this reply sums things up better in less space.

Anyway, I'm just picking a nit.  Perl is inferior to Python in just 
about every conceivable manner -- except this one, highly technical sense.

Regards

--jb

-- 
James J. Besemer		503-280-0838 voice
2727 NE Skidmore St.		503-280-0375 fax
Portland, Oregon 97211-6557	mailto:jb at cascade-sys.com
				http://cascade-sys.com	







From chris.gonnerman at newcenturycomputers.net  Wed Sep  4 23:46:08 2002
From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman)
Date: Wed, 4 Sep 2002 22:46:08 -0500
Subject: heeelp
References: <001f01c25357$53cb7ca0$2500a8c0@maxitec.co.za>
Message-ID: <00b301c2548e$c9863420$0101010a@local>

First of all, Morne, you should NEVER EVER post to public
mailing lists in HTML format; or to newsgroups either.

Bad poster, no biscuit.

Second, don't hammer us.  You posted here at least twice,
and I read another poster stating you have posted this in
other newsgroups as well.

ALSO, you didn't indicate your Python version or your OS.
You MUST do this, for any but the most general questions.

Now that I've busted your chops, here's the answer to your
question (see attachment).  I'm not sure where your ppp.log
came from (i.e. what OS) so I guessed that a connection
where an IP was not assigned was an error.  If the criteria
for an error is different you might explain it.  Your code
is looking for a string of "ERROR" which did not appear in
your sample.

Here's what my code produced on my system:

----------------------------------------------------------------------------
--
Jul  5 18:45  Connected to Internet (IP 155.239.150.146 )
Jul  5 18:48  Closed connection, connect time = 197 secs
              (5091 octets in, 1864 octets out)
----------------------------------------------------------------------------
--
Successful Connections:        1
Failed Connections:            0
Total Time Online:           197 seconds
Total Data In:              5091 octets
Total Data Out:             1864 octets

Hope this helps.

Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net
http://newcenturycomputers.net

> ----- Original Message -----
> From: Morne
>
> Could someone please help me with this?
> Im really new to any kind of programming
>
> If posible would you be
> able to answer in detail.
> Thanx
> morne
>
> is it wrong of me to send the ppp.log file to just anyone?
>
> HERE IS WHAT I HAVE:
>

--- code sample rudely hacked away here ---

>
> THIS IS WHAT I NEED THE PROGRAM TO DO:
>
> I want the program to read the attached ppp.log file and give me the
> following type of report:
>
>
> PPP Log file summary for 5 Jul 2002
> -----------------------------------
> Jul  5 18:15:01 Connected to internet (IP 155.239.150.146)
> Jul  5 18:18:08 Closed connection. ( Connect time: 197 secs: 5091 octets
in,
> 1864 octets out )
> -----------------------------------
> Successful connections: 5
> Failed connections: 2
> Total time online: 456 seconds
> Total data in: 66576 octets
> Total Data out: 66349 octets


-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: logproc.py
URL: 

From imbosol at vt.edu  Tue Sep  3 14:13:32 2002
From: imbosol at vt.edu (Carl Banks)
Date: Tue, 3 Sep 2002 14:13:32 -0400
Subject: Would you like a Snobol pattern matcher? (Re: Making regex suck less)
References: <3d725881.345921@news.t-online.de>  <3D740DFC.1040009@something.invalid> 
Message-ID: 

John Roth wrote:
> I don't know much about Snobol, unfortunately.
> I think my biggest issue here is that we shouldn't
> reinvent the wheel unless there is a good reason.
> In other words, Larry is taking Perl in a specific
> direction. Assuming we want to make major
> changes to regex,

I don't think anyone wants to make changes to regular expressions, per
se.  I think this discussion is about adding a higher level syntax to
regular expressions, that makes them more readable and versatile, for
cases where that's important.


> is there any _good_ reason
> for doing something conceptually different and
> consequently adding to the cacophony?

I think there is a good reason to have a higher level syntax.  It
serves a purpose heretofore unserved: that complex regular expressions
no longer have to be unbearably unreadable.

I could live without it, though.


-- 
CARL BANKS
http://www.aerojockey.com


From mhammond at skippinet.com.au  Fri Sep  6 23:10:57 2002
From: mhammond at skippinet.com.au (Mark Hammond)
Date: Sat, 07 Sep 2002 03:10:57 GMT
Subject: Win32 question: Problem with NetLocalGroupDelMembers
References: <3D78A350.4010006@btk.utu.fi>
Message-ID: <57ee9.1357$_l1.3640@news-server.bigpond.net.au>

Marten Hedman wrote:
> Hi,
> 
> Im writing a script for administrating local user groups on a remote 
> WinNT computer, using Python 2.2.1 and the Win32 extensions, build 148. 
> Getting information about users in a group and adding users to a group 
> works fine, but when I try to delete users from a group I get an 
> exception, 'TypeError: The object can not be converted to a Unicode 
> object'. An interactive example session looks like this:

This is a bug in the documentation.

>  >>> win32net.NetLocalGroupDelMembers(server, group, mem)
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: The object can not be converted to a Unicode object

This function expects a list of string usernames, *not* 
PyLOCALGROUP_INFO structures.  Thus, the following will work:

names = [ m['domainandname'] for m in mem ]
win32net.NetLocalGroupDelMembers(server, group, names)

I added the following function to win32netdemo.py.

Mark.


def LocalGroup(uname=None):
     "Creates a local group, adds some members, deletes them, then 
removes the group"
     level = 3
     if uname is None: uname=win32api.GetUserName()
     if uname.find("\\")<0:
         uname = win32api.GetDomainName() + "\\" + uname
     group = 'python_test_group'
     # delete the group if it already exists
     try:
         win32net.NetLocalGroupDel(server, group)
         print "WARNING: existing local group '%s' has been deleted."
     except win32net.error:
         pass
     group_data = {'name': group}
     win32net.NetLocalGroupAdd(server, 1, group_data)
     try:
         u={'domainandname': uname}
         win32net.NetLocalGroupAddMembers(server, group, level, [u])
         mem, tot, res = win32net.NetLocalGroupGetMembers(server, group, 
level)
         print "members are", mem
         if mem[0]['domainandname'] != uname:
             print "ERROR: LocalGroup just added %s, but members are %r" 
% (uname, mem)
         # Convert the list of dicts to a list of strings.
         win32net.NetLocalGroupDelMembers(server, group, 
[m['domainandname'] for m in mem])
     finally:
         win32net.NetLocalGroupDel(server, group)
     print "Created a local group, added and removed members, then 
deleted the group"



From jwold at min.midco.net  Sun Sep 22 20:47:36 2002
From: jwold at min.midco.net (Jarrett Wold)
Date: Sun, 22 Sep 2002 19:47:36 -0500
Subject: PyXML Building on OS X?
Message-ID: 

  I downloaded PyXML source distribution 0.8.1 and attempted to build it
using Python 2.2 distribution from Fink (fink.sourceforge.net).  Needless to
say it failed.  Any ideas?  I dug around Google Groups attempting to find an
answer and found a message from September 2000 that briefly touched on the
desire to support OS X.

  If you want some sample output of the build I can certainly rerun it and
post it.

Jarrett L Wold



From fetus at AUTO  Thu Sep 26 16:00:24 2002
From: fetus at AUTO (A. Dimsdale Fetus A. Moser)
Date: Thu, 26 Sep 2002 20:00:24 GMT
Subject: Pythonwin (win32all build 148) on Python 2.2.1 on Win2K, bogus syntax e
References:  
Message-ID: 

"Neil Hodgson"  writes:

>Aaron Dimsdale and Alex Moser:

>> Pythonwin barfed on the quote marks marked by carets, returning: "Failed
>to run script -
>> syntax error - invalid syntax".

>   Try turning on View | End-of-line markers to see if you have non-standard
>line endings such as pure carriage returns, which cause just this sort of
>error. On Windows, you want line endings to be carriage return + line feed.

>   Neil

Well, I did that, and that seems to be the problem. Is there a Pythonwin
setting I can set to make it do standard line endings? Every line except for
whitespace lines seems to end in just a carriage return. How do I fix this?

Thanks.

--Aaron L. Dimsdale



From andreas at andreas-jung.com  Fri Sep 20 11:45:19 2002
From: andreas at andreas-jung.com (Andreas Jung)
Date: Fri, 20 Sep 2002 16:45:19 +0100
Subject: bit operations ?
In-Reply-To: 
References: 
Message-ID: <727165.1032540319@[10.10.1.2]>

You should check this with the Python documentation
See '|', "&" operators.

-aj

--On Freitag, 20. September 2002 16:40 +0200 Shagshag13 
 wrote:

> hello,
>
> i'm looking for any libs which could handle bit operations on integer.
> (i must be able to get 0 to n bits from any int., only bit j, etc.)
>
> thanks in advance,
> s13.
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list





From kalle at lysator.liu.se  Mon Sep  2 03:50:40 2002
From: kalle at lysator.liu.se (Kalle Svensson)
Date: Mon, 2 Sep 2002 09:50:40 +0200
Subject: ascii value
In-Reply-To: 
References: 
Message-ID: <20020902075039.GA2776@i92.ryd.student.liu.se>

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

[Axel Grune]
> How can I get the ascii value of char which is in a string,
> e.g. getting the 97 if the char was 'a'.

>>> ord('a')
97

Peace,
  Kalle
- -- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 

iD8DBQE9cxg7dNeA1787sd0RAsgUAJ9nPP6vQWq1N5tCn+BuZBuV2eMVuACfbl3l
P5Zo5MqtM2jCf+AU/aCWBJo=
=cIb4
-----END PGP SIGNATURE-----



From tismer at tismer.com  Fri Sep 27 22:29:50 2002
From: tismer at tismer.com (Christian Tismer)
Date: Fri, 27 Sep 2002 19:29:50 -0700
Subject: Python threading?
References:    <7xfzw0avrg.fsf@ruckus.brouhaha.com>
Message-ID: <3D95141E.6080302@tismer.com>

Paul Rubin wrote:
> Mark Hammond  writes:
> 
>>A "one thread per connection" model is doomed from the start -
>>therefore, in most applications, I would consider 5 threads a large
>>number - particularly when all are actively doing something.  OTOH, if
>>you are willing to accept that your first version will accept a max of
>>~20 connections, the brain-power saved by using threads beats the
>>additional OS overhead by a mile ;)
> 
> 
> The new Linux native thread implementation was recently benchmarked
> running 100,000 simultaneous threads on a 1 GB machine.  Starting all
> the threads and closing them took around 2 seconds.  

Not too bad.
How about 1,000,000 in 100 MB?
Started and shut down in 15 seconds, from Python?

This was just a rough test of new features, will
give exact timings when I write the article...

ciao - chris
-- 
Christian Tismer             :^)   
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34  home +49 30 802 86 56  pager +49 173 24 18 776
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/





From gerhard.haering at gmx.de  Sun Sep  8 13:29:43 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: Sun, 8 Sep 2002 19:29:43 +0200
Subject: [ANN] pyPgSQL 2.2 released
Message-ID: <20020908172943.GA624@lilith.ghaering.test>

Announce: pyPgSQL - Version 2.2 is released.
===========================================================================

pyPgSQL v2.2 has been released. It is a bug fix release to version 2.1.

It is available at http://pypgsql.sourceforge.net.

pyPgSQL is a package of two (2) modules that provide a Python DB-API 2.0
compliant interface to PostgreSQL databases. The first module, libpq,
exports the PostgreSQL C API to Python. This module is written in C and
can be compiled into Python or can be dynamically loaded on demand. The
second module, PgSQL, provides the DB-API 2.0 compliant interface and
support for various PostgreSQL data types, such as INT8, NUMERIC, MONEY,
BOOL, ARRAYS, etc. This module is written in Python and works with
PostgreSQL 7.0 or later and Python 2.0 or later.

Note: It is highly recommended that you use PostgreSQL 7.1 or later and
Python 2.1 or later.

PostgreSQL is a sophisticated Object-Relational DBMS, supporting almost all
SQL constructs, including sub-selects, transactions, and user-defined types
and functions. It is the most advanced open-source database available any-
where More information about PostgreSQL can be found at the PostgreSQL home
page at http://www.postgresql.org.

Python is an interpreted, interactive, object-oriented programming lang-
uage. It combines remarkable power with very clear syntax. It has mod-
ules, classes, exceptions, very high level dynamic data types, and dynamic
typing. There are interfaces to many system calls and libraries, as well
as to various windowing systems (X11, Motif, Tk, Mac, MFC). New builtin
modules are easily written in C or C++. Python is also usable as an exten-
sion language for applications that need a programmable interface. Python
is copyrighted but freely usable and distributable, even for commercial
use. More information about Python can be found on the Python home page at
http://www.python.org.

---------------------------------------------------------------------------
ChangeLog:
===========================================================================

Changes since pyPgSQL Version 2.1
=================================

The following source code files were added to Version 2.2 of pyPgSQL:

    pyPgSQL.spec	- RPM spec file, contributed by Sean Reifschneider.

Changes to README
-----------------
* Added note about case-insensitiveness of column access in PgResultSet.

Changes to PgSQL.py
-------------------
* Fixed various problems with the PgResultSet: Column (attribute and
dictionary) access is now case-insensitive.  A __contains__ method was added
and the __setattr__ method was fixed. The get method got an optional default
value parameter.

* Fixed various problems with the PgNumeric type:
  - Added code to allow a float as an argument to the PgNumeric constructor.
  - You can now change the precision/scale of a PgNumeric by:
      a = PgNumeric(pgnumeric, new prec, new scale).
    This can be used to 'cast' a PgNumeric to the proper precision and scale
    before storing it in a field.
  - The arithmatic routines (__add__, __radd__, etc) now ensure that the
    arguments are properly coerced to the correct types.
  - Added support for the augmented arithmetic operations (__iadd__, etc).
  - The math routines would lose precision because the precision/ scale were
    set to be the same as the first operand.  This is no longer the case all
    precision is retained for the +, -, and * operations.

* Fixed problem that occurs when a query on an OID field doesn't return any
rows. [Bug #589370].
	
* Applied patch #569203 and also added __pos__ and __abs__ special methods to
PgNumeric.

* Ensure proper SQL-quoting of long ints.

Changes to PgSQLTestcases.py
----------------------------
* 14 new tests, mostly for PgNumeric and PgResultSet.



From fgranger at alussinan.org  Fri Sep 20 13:29:10 2002
From: fgranger at alussinan.org (=?ISO-8859-1?Q?Fran=E7ois_Granger?=)
Date: Fri, 20 Sep 2002 19:29:10 +0200
Subject: [Help]: mailbox classes
References:  
Message-ID: <1fitpvg.gi8n0y1iem93tN%fgranger@alussinan.org>

Alex Martelli  wrote:

> J. Li wrote:
> 
> > Hi,
> > 
> > I am trying to extract a message from a unix mailbox file.
...
> 
> > what is it relationship with email.message classes.
> 
> Not much, intrinsically -- the items in a mailbox object by
> default are rfc822.Message instances.  But you can pass as
> the second argument to the constructor a factory with a
> compatible interface, which should let you get email.Message
> instances instead, if that's what you want.

email does not handle the unix mailbox properly. It sees only the first
message.

I was going the way you suggest by first using mailbox.UnixMailbox, then
i'd like to pass each message given by the next() method to email for
further analysis. But this is way over my current level of understanding
of Python objects and classes. ....

-- 
Une faq de frj: http://faq.jardin.free.fr/, pr?s de l'encyclop?die
http://nature.jardin.free.fr/
MacPython beginners http://francois.granger.free.fr/MacPython/faq/


From loewis at informatik.hu-berlin.de  Wed Sep 18 06:33:14 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=)
Date: 18 Sep 2002 12:33:14 +0200
Subject: python does not start
References: 
Message-ID: 

Brian Lee  writes:

> On SunOS 5.7, python which is compiled on other sun machine does not start.
> How can I fix this?

You need to copy libdb-3.2.so from that machine as well.

Regards,
Martin


From bobx at linuxmail.org  Wed Sep 18 13:52:00 2002
From: bobx at linuxmail.org (Bob)
Date: 18 Sep 2002 10:52:00 -0700
Subject: Python equivalent to perldoc?
References:   <9ywh9.7955$Lg2.1406050@news2.news.adelphia.net> 
Message-ID: <1001ff04.0209180952.57e7b865@posting.google.com>

Fernando P?rez  wrote in message news:...
> Bob X wrote:
> 
> > Skip Montanaro wrote:
> >>     Bob> In Perl you can run "perldoc warnings" and get the definition of
> >>     Bob> what "warnings" does. Is there a equivalent in Python?
> >> 
> >> Try "pydoc warnings".
> >> 
> > What a funny guy!  :-)
> 
> $ pydoc warnings
> NAME
>     warnings - Python part of the warnings subsystem.
> 
> FILE
>     /usr/lib/python2.2/warnings.py
> 
> CLASSES
>     exceptions.Exception
>         _OptionError
> 
>     class _OptionError(exceptions.Exception)
>      |  Exception used by option processing helpers.
>      |
> ... snipped rest.
> 
> What's funny about it? Looks like exactly what you asked for.
> 
> Cheers,
> 
> f.
Actually it works on *nix as was the above...but not on Windows XP as was mentioned.

Cherrios,

Bob


From davidis at diebots.davidis.diebots.plus.com  Sun Sep 29 19:48:27 2002
From: davidis at diebots.davidis.diebots.plus.com (David Harrison)
Date: Mon, 30 Sep 2002 00:48:27 +0100
Subject: windows xp command prompt
References: <576c1752.0209271411.6d7bb4c4@posting.google.com>
Message-ID: 

mike henley wrote:
> i have installed the activestate perl, python, tcl, and pragmatic
> programmer's ruby. when i go to the command prompt on windows xp and
> type perl for example... (or python, ruby... etc) i get the following
> message.
> 
> 'perl' is not recognized as an internal or external command,
> operable program or batch file.
> 
> in the control panel| system | advanced | environment variables | Path
> i have
> 
> C:\ruby\bin;C:\Python22;C:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem
> 
> does anyone know what i should do to fix this problem? (apart from the
> obvious of restarting the machine)


Is it like Win2K, where you have environment variables for 'this user' 
and 'all users' (easiest found by right-clicking on My Computer, 
selecting 'Manage', then right-clicking again on 'Computer Management 
(Local)', and selecting the 'Advanced' Tab and clickign on the 
'Environment Variables' button. You want to edit the 'System' path 
variable).

Just a thought.

Dave H

-- 


"When the tough get going, I'll steal their sandwiches."

If you need to contact me direct, please remove the obvious from the 
reply address



From martin at v.loewis.de  Mon Sep  9 18:56:49 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 10 Sep 2002 00:56:49 +0200
Subject: how to build wxPython w/ Sun's C++ compiler?
References: 
Message-ID: 

Skip Montanaro  writes:

> How do I convince it to use CC for files with .cpp extensions.

Currently, you cannot: distutils does not support usage of separate
tools for C and C++; feel free to contribute patches.

If you can compile all source files as C++, try setting CC to CC in
the installed Makefile.

Regards,
Martin


From marklists at mceahern.com  Mon Sep 16 21:20:39 2002
From: marklists at mceahern.com (Mark McEahern)
Date: Mon, 16 Sep 2002 20:20:39 -0500
Subject: Source code
In-Reply-To: <3d867f4d$0$23173$afc38c87@news.optusnet.com.au>
Message-ID: 

bah, to heck with usability; the OP should consult this fine oracle for 
pearls of wisdom on securing code against all interested parties:

  http://www.mindprod.com/unmain.html

// m
-




From Oschler at earthlink.net  Fri Sep 20 20:35:23 2002
From: Oschler at earthlink.net (Robert Oschler)
Date: Sat, 21 Sep 2002 00:35:23 GMT
Subject: Python threading?
Message-ID: 

How can I tell if the version of Python I am running is thread-enabled?
Also, what is a reasonable number of threads to expect to be able to run
before context switching overhead becomes a problem (I'm using a PIII 500
Mhz with 512MB ram if that helps).

thx





From astrophels at yahoo.com  Fri Sep  6 11:05:20 2002
From: astrophels at yahoo.com (Micah Mayo)
Date: Fri, 06 Sep 2002 15:05:20 GMT
Subject: Getting a proccesses ID
Message-ID: 

Hi,

I'm writing a little tool for SysAdmins on FreeBSD - I'm trying to make
it as portable as possible(as far as the unices go), and have come upon
a problem - one of the things this tool does is restarts various deamons
on the system, in order to do that I have to send a killsignal to the
pid. The problem is getting the process id - right now I've got a hack
using ps, grep, and awk, which I doubt will translate well to other
flavors of *nix because they all seem to have their own method of
delivering info via ps. Can anyone tell me a cross platform way of
grabbing a particular processes ID

Here's what I'm doing now, by the way:

pid = os.popen("ps -x | grep sshd | grep -v grep | awk '{ print $1 }'")
pid = pid.atoi()



From Padraig at Linux.ie  Wed Sep 11 09:13:31 2002
From: Padraig at Linux.ie (Padraig Brady)
Date: Wed, 11 Sep 2002 13:13:31 GMT
Subject: regular expression for space seperated quoted string
References:  
Message-ID: <%jHf9.3635$cP3.7161@news.iol.ie>

Eric Brunel wrote:
> Padraig Brady wrote:
> 
> 
>>Hi, I'm trying to split a string that is seperated
>>by spaces and also contains double quoted words which
>>can contain spaces:

[snip]

> What about:
> 
>>>>p = r'[^ \t\n\v\f"]+|"[^"]*"'
>>>>re.findall(p, '1 2 3')

FYI, I'm using the following:

import fileinput, re
for line in fileinput.input():
     #split fields
     fields = re.findall('[^ "]+|"[^"]+"', line[:-1])
     #remove quotes
     fields = map(lambda field: field.replace('"', ''), listLine)

thanks again,
P?draig.



From quiteblack at yahoo.com  Mon Sep  2 23:27:24 2002
From: quiteblack at yahoo.com (black)
Date: 2 Sep 2002 20:27:24 -0700
Subject: what about things like __*** ?
Message-ID: <7153651c.0209021927.16a3efaf@posting.google.com>

Hi, all~

when reading the tutorial I met some trouble.(Maybe trifle to you all
but really trouble to me)

That is I couldnt figure out what __*** is. Here is the description of
that article but even confused me:

There is limited support for class-private identifiers. Any identifier
of the form __spam (at least two leading underscores, at most one
trailing underscore) is now textually replaced with _classname__spam,
where classname is the current class name with leading underscore(s)
stripped.

What's it trying to say please ???


From tjreedy at udel.edu  Mon Sep 23 09:17:12 2002
From: tjreedy at udel.edu (Terry Reedy)
Date: Mon, 23 Sep 2002 13:17:12 GMT
Subject: convention for Pickler file extension
References: <918bc22f.0209230208.4eaca702@posting.google.com>
Message-ID: 

"Donnal Walter"  wrote in message
news:918bc22f.0209230208.4eaca702 at posting.google.com...
> When one uses Pickler.dump(object) to serialize an object to a file
> associated with the Pickler, is there a Python convention for the
file
> extension name?

If there is not currently, I think .pyp is available.




From chris.gonnerman at newcenturycomputers.net  Fri Sep 13 00:38:01 2002
From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman)
Date: Thu, 12 Sep 2002 23:38:01 -0500
Subject: problems with getpass.getpass() under Linux
References: <008601c25ada$d1a5f580$3101a8c0@borg.fielden.com.au>
Message-ID: <00b501c25adf$5d7a53e0$0101010a@local>

----- Original Message -----
From: "DG" 


> Greetings,
>
> I have Slackware Linux 8.0 with the (as distributed) Python 2.0.1
installed.
> When I import getpass and try to getpass.getpass() I get the following
error
> and the password is echoed:
>
> "Warning: Problem with getpass. Passwords may be echoed."
>
> Looking into getpass.py it does this:
>
> try:
>         import termios, TERMIOS
>
> If that fails, it goes on to try to import Windows and then Mac-specific
> modules, with a fallback to just calling raw_input (effectively).
>
> I have TERMIOS.py in /usr/lib/python2.0/plat-linux2 but I do not have
> termios.py anywhere.

That's because it is termios.so; it should be in
/usr/lib/python2.0/lib-dynload.

> I have the Python 2.2.1 tarball (not (yet) installed), it contains
> TERMIOS.py and but not termios.py (altho it does have a termios.c).  I
> notice that the 2.2.1 getpass.py only tries to import termios.
>
> What do I need to do to have getpass.getpass() work correctly?

If you build the 2.2.1 system it should make the termios.so module for you;
I'd think that would work fine.

Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net
http://newcenturycomputers.net




From xscottgjunk at yahoo.com  Mon Sep 23 18:33:03 2002
From: xscottgjunk at yahoo.com (Scott Gilbert)
Date: 23 Sep 2002 15:33:03 -0700
Subject: numpy array assignment
References: 
Message-ID: <79b2b0bb.0209231433.11f26388@posting.google.com>

John Hunter  wrote:
>
> I have a 2 dimensional array X which is NxM and a 1 dimensional array
> v which is Nx1.  I want to assign v to the k-th column of X
> 
> import Numeric
> import RandomArray
> 
> Z = Numeric.zeros( (3,10), Numeric.Float  )
> v = Numeric.ones( (3,1), Numeric.Float )
> Z[:,4] = v
> 
> But I get the ValueError: Object too deep for desired array.  I have
> read over the numpy manual on slices and array methods and the closest
> thing I saw was the 'put' method, but this seems to be designed for 1d
> indexing.
> 
> What's the best way to assign an arbitrary Nx1 array to a column of X?
> 

Is this what you want?

     Z[:,4] = v[:,0]

v is actually a 2D array from Numeric's perspective, it's just the
second dimension isn't very deep.

Cheers,
    -Scott


From tjreedy at udel.edu  Sat Sep  7 18:23:14 2002
From: tjreedy at udel.edu (Terry Reedy)
Date: Sat, 07 Sep 2002 22:23:14 GMT
Subject: Converting python object reference to int and back
References: <3D79AC95.1000000@NOSPAMbitbuilder.com> 
Message-ID: 

"Martin v. Loewis"  wrote in message
news:m38z2e2qef.fsf at mira.informatik.hu-berlin.de...
> Ahmad Baitalmal  writes:
>
> > How can I get an id (pointer/reference) from a python object and
then
> > get that object back using that integer?
>
> To get an integer, use the id function. To get the object back,
create
> a dictionary mapping the ids to the real objects.

While this answers the OP's question as presented, it seems pretty
useless (and unlikely to solve the real question not asked).  Since
the 'real objects' are represented internally by the same id used as
the key, such a dict would amount to an identity mapping.

Terry




From jslowery at hotmail.com  Fri Sep 13 18:21:46 2002
From: jslowery at hotmail.com (Jeremy Lowery)
Date: Fri, 13 Sep 2002 17:21:46 -0500
Subject: CPython detecting read-only attributes.
Message-ID: 

I'm implementing an extension type in CPython, using the new getsetlist
tp_getset.

I have defined my own tp_setattro function, and my question is: What would
be the easiest way to detect the attempt to write to a readonly attribute.

Scouring PyObject_GenericSetAttr, I see that it always returns -1 on fail,
but that is if it doesn't find a corresponding match or not, and the same
exception is raised PyExc_AttributeError.

I am trying to use the builtin functionality and then, if the attribute is
not found and only if it is not found, I would like to store it in a PyDict
myself.

Is there a better function around to do the Attribute Lookup/setting for the
builtin? I haven't been able to find documentation for these new API
functions (added 2.2) in the reference.

Thanks,
J Lowery






From grabiller at 3dvf.net  Sun Sep 29 19:47:28 2002
From: grabiller at 3dvf.net (Guy Rabiller)
Date: Mon, 30 Sep 2002 01:47:28 +0200
Subject: Python's import: why doesn't it work?
References: 
Message-ID: <3d979112$0$18477$79c14f64@nan-newsreader-02.noos.net>

[ Jurie Horneman]
> python -v script.py >output.txt
>
> It lists the verbose output straight to the DOS shell, not to
> output.txt. The output is useless, I can't scroll back.

try:

python -v script.py 2> output.txt


--
guy rabiller
3d animator / td
grabiller at 3dvf.net
http://grabiller.3dvf.net

Tim Peters wrote:
> [ Jurie Horneman]
>> Actually, I just tried this in a DOS shell under Windows 98:
>>
>> python -v script.py >output.txt
>>
>> It lists the verbose output straight to the DOS shell, not to
>> output.txt. The output is useless, I can't scroll back.
>>
>> Oddly,
>>
>> python -h >output.txt
>>
>> correctly sends the output to output.txt.
>>
>> Does anybody know if this is a bug,
>
> Arguably so, but it's a command.com (the Win9x shell) limitation.
> Your first example printed to stdout, your second to stderr, and
> command.com simply doesn't allow redirecting stderr, or setting the
> DOS box history to a usable value.  cmd.exe (the WinNT/2K/XP shell)
> does both.
>
>> and how I can work around it?
>
> Programming life under command.com is impossible without tcap:
>
>     http://www.simtel.net/pub/pd/11141.html
>
> It's free, tiny, and works great.  It's the only Win9x "console
> capturing" utility I've tried that actually works, and doesn't cause
> system instability.




From skip at pobox.com  Fri Sep 27 13:03:03 2002
From: skip at pobox.com (Skip Montanaro)
Date: Fri, 27 Sep 2002 12:03:03 -0500
Subject: watching mutables?
In-Reply-To: 
References: 
        
Message-ID: <15764.36679.516534.436308@12-248-11-90.client.attbi.com>

    Anton> Variables should be 'marked' to install this function for
    Anton> them. For example 'watch(m,f)' indicates that function f is
    Anton> called if mutable variable m is changed. 

You could implement a proxy object which delegates to the real object and
catches all __setattr__ and __setitem__ calls.  Something like:

    class MutableProxy:
        def __init__(self, obj):
            self.__dict__['obj'] = obj

        def __setattr__(self, attr, val):
            print "Hey! My %s attribute got diddled!" % attr
            setattr(self.__dict__['obj'], attr, val)

        def __getattr__(self, attr):
            return getattr(self.__dict__['obj'], attr)

    if __name__ == "__main__":
        class Dummy:
            pass

        d = MutableProxy(Dummy())
        d.x = 1
        print d.x

__setitem__ and __getitem__ are similar, but you have to worry about ranges.
You'd probably have to wrap __call__ as well.

There's probably a way to do it with metaclasses, but ...  ooh! I just got a
headache, better back off before my brain expl ... <* blam! *>

-- 
Skip Montanaro - skip at pobox.com
"Airplanes don't fly until the paperwork equals the weight of the
aircraft. Same with i18N." - from the "Perl, Unicode and i18N FAQ"



From pearu at cens.ioc.ee  Mon Sep  9 05:24:36 2002
From: pearu at cens.ioc.ee (Pearu Peterson)
Date: Mon, 9 Sep 2002 12:24:36 +0300 (EEST)
Subject: Grumble about too strict an attitude about backward compatibility...
In-Reply-To: <15733.30396.670049.67330@12-248-11-90.client.attbi.com>
Message-ID: 

On 4 Sep 2002, Skip Montanaro wrote:

> 
> I don't want to wake any sleeping dogs, however, as I'm sitting here
> watching a bunch of Fortran function names fly by as SciPy builds, I'm
> reminded of the fairly recent threads about backward compatibility,
> Python-in-a-tie, etc.   Here I am compiling with a Fortran 90/95 compiler
> (Sun's Forte thing-a-ma-bob) and see function names like
> 
>         lpni:
>         klvna:
>         chgubi:
>         cyzo:
>         klvnb:
>         rmn2so:
>         csphik:
> 
> spew forth.  So, while it's great that this same large library compiles and
> runs on compilers back to at least Fortran 77 (and probably earlier),
> programmers are still stuck with the same cryptic function and data names
> they had to deal with 30+ years ago, all in the name of backward
> compatibility.

I don't think that its is due to the backward compatibility.
There is huge amount of Fortran 77 code available and if one wants to fix
the cryptic names of functions to something more meaningful, then one has
to switch to newer Fortran standard (that allows longer names) and edit
huge amount of F77 code. I think nobody is willing to take this task due
to enormous amount of work (and it cannot be fully automated, some
brain has to deside what are meaningful names), the backward compatibility
is a secondary issue (if an issue at all).

> What's the Python connection?  Other than a reminder not to get to slavish
> about backward compatibility, I note that these same function names will
> then go on to pollute the Python namespace because all this Fortran code is
> automatically wrapped using f2py.

The Fortran function names, that you refer to, are visible only in the
extension modules that are wrapping these functions (this is due to how
Python imports shared modules). All functions that f2py generates,
have the f2py_ prefix to avoid name collision with names from Python
or any other library.
So, I don't understand your argument about name pollution.

And btw, f2py supports mapping function names so that wrapping a Fortran
function with a name `tiarcf' can be accessed in Python side as
`this_is_a_really_cool_function', for example.

Pearu




From mhammond at skippinet.com.au  Tue Sep 24 00:33:42 2002
From: mhammond at skippinet.com.au (Mark Hammond)
Date: Tue, 24 Sep 2002 04:33:42 GMT
Subject: Python threading?
References:    <7xfzw0avrg.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin wrote:
> Mark Hammond  writes:
> 
>>A "one thread per connection" model is doomed from the start -
>>therefore, in most applications, I would consider 5 threads a large
>>number - particularly when all are actively doing something.  OTOH, if
>>you are willing to accept that your first version will accept a max of
>>~20 connections, the brain-power saved by using threads beats the
>>additional OS overhead by a mile ;)
> 
> 
> The new Linux native thread implementation was recently benchmarked
> running 100,000 simultaneous threads on a 1 GB machine.  Starting all
> the threads and closing them took around 2 seconds.  

Just because you *can* doesn't mean you *should* .  Are you 
suggesting you would use a threading model to support 100,000 
simultaneous connections to your program on such a system?

Mark.



From daniel.dittmar at sap.com  Wed Sep  4 08:43:30 2002
From: daniel.dittmar at sap.com (Daniel Dittmar)
Date: Wed, 4 Sep 2002 14:43:30 +0200
Subject: newsgroup for zope
References: 
Message-ID: 

stephan wrote:
> but does there exist a newsgrup for zope centric items?
news://news.gmane.org/gmane.comp.web.zope.general. This
is a gateway to the mailing list, so don't expect your ISP
to provide it.

Daniel





From Oschler at earthlink.net  Sat Sep 28 22:08:49 2002
From: Oschler at earthlink.net (Robert Oschler)
Date: Sun, 29 Sep 2002 02:08:49 GMT
Subject: Best way to create a class dynamically on the fly?
References:  <3D96511D.2040407@4-am.com>
Message-ID: 

"Evan"  wrote in message news:3D96511D.2040407 at 4-am.com...
> Robert Oschler wrote:
> > What is the best way to create a Python class dynamically at runtime?
>
> ALL Python classes are created dynamically at runtime.  The following is
> not a declaration in the sense that you're accustomed to from C/C++, it
> is normal code executed when the containing file is run (or imported):
>
> class Foo:
>    def meth1(self):
>      return "I am a method"
>


Evan,

I understand but what I'm after is building the class itself dynamically,
akin to the way you can manufacture a prolog predicate on the fly.  For
example,  if wanted to create a class whose name was provided in a string
variable called ClassName, at runtime.  Or did I misunderstand your reply?

thx





From SBrunning at trisystems.co.uk  Wed Sep  4 08:33:16 2002
From: SBrunning at trisystems.co.uk (Simon Brunning)
Date: Wed, 4 Sep 2002 13:33:16 +0100 
Subject: Please help in  calling python fucntion from 'c'
Message-ID: <31575A892FF6D1118F5800600846864DCBD71E@intrepid>

> From:	Praveen Patil [SMTP:praveen.patil at silver-software.com]
 
(snip)
 
> Please anybody help me solving the problem.
 
Is there anywhere you *didn't* post this?

Cheers,
Simon Brunning
TriSystems Ltd.
sbrunning at trisystems.co.uk




-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.



From tdelaney at avaya.com  Thu Sep 26 01:12:27 2002
From: tdelaney at avaya.com (Delaney, Timothy)
Date: Thu, 26 Sep 2002 15:12:27 +1000
Subject: revenge of the python puzzle
Message-ID: 

May I note of course that I shamelessly stole Holger's code for the basic
framework ;)

Tim Delaney



From printers at sendme.cz  Thu Sep  5 09:20:31 2002
From: printers at sendme.cz (A)
Date: Thu, 05 Sep 2002 15:20:31 +0200
Subject: What database should I use
Message-ID: <3D77763F.23080.BFAFA3@localhost>

Hello,
I am going to program a small application (in Python and wxPython) which consists about 
2000 - 3000 records . Can you please recommend which database is the best for that. I 
use Windows.
Maybe MS Access  or FoxPro or MySQL or better?
I want to keep the program as small as possible.
Thanks
Ladislav




From tismer at tismer.com  Sun Sep 15 14:24:54 2002
From: tismer at tismer.com (Christian Tismer)
Date: Sun, 15 Sep 2002 20:24:54 +0200
Subject: Stackless Python, eventual merge?
References:    
Message-ID: <3D84D076.1000006@tismer.com>

Martin v. L?wis wrote:
> "David Abrahams"  writes:
> 
> 
>>I think it still matters. You don't want people who need stackless'
>>capabilities to have to use a non-standard Python forever, do you?
> 
> 
> Unfortunately, the current implementation is processor-dependent; it
> supports x86, SPARC, and PPC only (not really sure about PPC).

Since today it supports X86, Sparc, PPC and Cygwin.

> It also
> limits extensions: if they call back to Python, they must not keep
> "global" variables on the stack (global in the sense that their
> address is known outside their function).
> 
> These limitations require Stackless users to be more aware of the
> inner workings of Python, or they risk crashes - something that would
> be considered a bug in standard Python.

Yes, but :-)
Stackless is built in a way that by default there is no difference
to the standard. No stack switching occours, all is identical.
If you want stackless behavior, you must switch it on.
And if you want to use task switching, you need to import the
stackless extension (which is now apart).

Therefore I'd claim that putting Stackless into the core trunk
would not do any harm. Users who want to use it can use it,
others may ignore it (and it is very tiny, about 50k).

This could be something like the thread package, which also
does not work on all platforms.

ciao - chris
-- 
Christian Tismer             :^)   
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34  home +49 30 802 86 56  pager +49 173 24 18 776
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/





From diltonm at pacbell.net  Tue Sep 24 23:29:47 2002
From: diltonm at pacbell.net (Dilton McGowan II)
Date: Wed, 25 Sep 2002 03:29:47 GMT
Subject: PythonWin CVS problem
References: 
Message-ID: 

David LeBlanc wrote:

> Second day it's inaccessable with "permission denied"
> 
> David LeBlanc
> Seattle, WA USA

Are you using cvs.pythonpros.com? It worked for me yesterday and again just 
now. They seem to have the latest source. Just a friendly suggestion.


From fbarbuto at telusplanet.net  Fri Sep 20 13:27:08 2002
From: fbarbuto at telusplanet.net (Fausto Arinos de A. Barbuto)
Date: Fri, 20 Sep 2002 17:27:08 GMT
Subject: What the heck? open() requires an integer?
References:  
Message-ID: 

      
Hi Alex and Henrik,

    Thanks so much for your help. I thought it might be
    that open() had been superseded by some other
    function having the same name (but different syntax),
    but didn't know which one.

    Also, it is a good idea to learn more Python before
    venturing to develop code. Or to adapt someone
    else's source code, which was exactly the case.

---Fausto


Alex Martelli  wrote:

> Fausto Arinos de A. Barbuto wrote:
> 
>>     The open() function is returning me a strange error.
>>     An attempt to create an output file with
>> 
>>             f = open("output.txt","w")
>> 
>>     yields the following error:
>> 
>>     Traceback (most recent call last):
>>     File "", line 1, in ?
>>     TypeError: an integer is required
>> 
>>     That happens when I am using either Pythonwin or
>>     IDLE 0.8, but not in interactive mode. In this latter
>>     case I can open, write to and close a file OK.
>> 
>>     What's the matter? Thanks in advance!
> 
> I'd be willing to bet that you did what you SHOULDN'T do,
> specifically a statement
>         from somewhere import *
> before this point in your interactive session.  I'd lay
> good odds that the 'somewhere' is os.
> 
> Don't do it.  "from ... import *" tramples all over your
> namespace: after you use it, how can you know WHAT
> function object is referred to by any given name?
> 
> Well, if you "print open" you could be able to tell, at
> least in Python 2.2...:
> 
>>>> print open
> 
>>>> from os import *
>>>> print open
> 
>>>> 
> 
> So, when you're calling open after "from os import *",
> you're really calling os.open -- and THAT one does indeed
> require an integer (as its second argument).
> 
> 
> A suggestion: forget all about the existence of statement
> "from" until you feel you have totally mastered Python.  I
> think you'll have an easier time learning, using, and
> mastering Python, if you ALWAYS use the import statement
> when you need to do imports, rather than using from.  (The
> "from ... import *" is the main issue, but there are others:
> e.g., built-in reload won't do what you expect if you've
> used statement from -- only if you've used statement import).
> 
> 
> Alex



From dpbmisc at pobox.com  Tue Sep 17 15:31:12 2002
From: dpbmisc at pobox.com (Don Bennett)
Date: Tue, 17 Sep 2002 19:31:12 GMT
Subject: Source code
References: 
Message-ID: <4qLh9.1185$%U1.52435185@newssvr21.news.prodigy.com>

Terje Johan Abrahamsen wrote:
 > If I would like to write some code that would not be possible for 
others to
 > read, after I distribute the program, would Python be suitable?

Yes.

 > I know that
 > there are a few programs like Py2Exe, that creates .exe files. But, I 
also
 > saw this:
 >
 > --------------------
 >  A zip-compatible archive is built, containing all files from this
 >   directory as well as your script, and appended to a custom python
 >   interpreter supplied with py2exe.
 > --------------------
 >
 > Doesn't sound like it is protected very well. Is there some 
alternative to
 > Py2Exe that can do the job, or should I look for a compiled language
 > instead?
 >
Take a look at Tools/freeze.py.

With this tool, you can compile your python files in to C files, and
then link the C files with the python interpreter to create a
stand-alone executable that represents your program.







From teaandbikkie at aol.com  Fri Sep  6 10:48:48 2002
From: teaandbikkie at aol.com (TeaAndBikkie)
Date: 06 Sep 2002 14:48:48 GMT
Subject: example for using calldll with python2.2
References: <20020906104210.15840.00000001@mb-cv.aol.com>
Message-ID: <20020906104848.15840.00000002@mb-cv.aol.com>

a better link is:

http://www.nightmare.com/~rushing/dynwin/

:)


From tibirna at kde.org  Wed Sep 18 19:24:58 2002
From: tibirna at kde.org (Cristian Tibirna)
Date: Wed, 18 Sep 2002 19:24:58 -0400
Subject: RegEx editors
References: 
Message-ID: 

On Wednesday, 18 September 2002 17:05, Eric Arnold wrote to 
comp.lang.python:

> Does anybody know of any good graphical regex editors out there?

There is one in KDE. It's available in KDE-3.1 from most "Find" tools of KDE 
applications. The editor itself is called "KRegExpEditor" :-)

-- 
Cristian Tibirna .. tibirna at sympatico.ca
PhD student .. ctibirna at giref.ulaval.ca .. www.giref.ulaval.ca/~ctibirna
KDE developer .. tibirna at kde.org .. www.kde.org


From ezcoder at mailcity.com  Sat Sep 14 12:20:26 2002
From: ezcoder at mailcity.com (Glenn Scott)
Date: 14 Sep 2002 09:20:26 -0700
Subject: Question regarding mysqldb module and variable table names
References: <45ac92e5.0209131920.23b1c22a@posting.google.com> 
Message-ID: <45ac92e5.0209140820.7d5089f3@posting.google.com>

Ahh...cool trick.  Works great.  Thanks!

Gerhard H?ring  wrote in message news:...
> Glenn Scott wrote in comp.lang.python:
> >  c.execute("""INSERT INTO %s \
> >         SET playerkey=%s, link=%s, snippet=%s, time_created=%s, \
> >         last_seen=%s, relevancy=%s, doc_title=%s """, \
> >          (infoTable, playerKey, urlLink, snippetText,
> > self.getCurrentTime(), self.getCurrentTime(),\
> >          noOfMentions, re.escape(str(self.doc_title))) )
> 
> sql = """INSERT INTO %s (playerkey, link, snippet, time_created,
>          last_seen, relevancy, doc_title)
>          VALUES (%%s, %%s, %%s, %%s, %%s, %%s, %%s)""" % infoTable
> 
> c.execute(sql, (...))
> 
> The reason why your original approach didn't work is that DB-API
> quoting is different from Python-quoting. So MySQLdb quotes your table
> name for SQL insertion, and adds apostrophes around it. You can use
> Python quoting as above to work around this.
> 
> Also, forget about re.escape. The DB-API module will quote the values
> appropriately for insertion into SQL.
> 
> -- Gerhard


From pyth at devel.trillke.net  Thu Sep 26 05:24:11 2002
From: pyth at devel.trillke.net (holger krekel)
Date: Thu, 26 Sep 2002 11:24:11 +0200
Subject: revenge of the python puzzle
In-Reply-To: ; from tdelaney@avaya.com on Thu, Sep 26, 2002 at 03:12:27PM +1000
References: 
Message-ID: <20020926112411.M30315@prim.han.de>

Delaney, Timothy wrote:
> May I note of course that I shamelessly stole Holger's code for the basic
> framework ;)

that was released into the public domain anyway :-)

    holger



From kkto at csis.hku.hk  Sun Sep  8 10:21:50 2002
From: kkto at csis.hku.hk (Isaac To)
Date: 08 Sep 2002 22:21:50 +0800
Subject: python program to watch a file - example.
References:  <3D7B5650.4050304@zute.net>
Message-ID: <7iadms8su9.fsf@enark.csis.hku.hk>

>>>>> "Tim" == Tim Hoffman  writes:

    Tim> If it is always the same file and seeing you are looking at *nix
    Tim> varient, one of the unix like ways would be to tail -f the file,
    Tim> and hook it up to your process which just does blocking reads on
    Tim> stdin.

    Tim> ie tail -f somfile | python my_watch.py

tail -f is doing a polling loop, polling each second by default.  In python
you are probably better off coding even the polling loop in Python as well,
rather than calling tail.

Regards,
Isaac.


From syver-en+usenet at online.no  Thu Sep 12 16:39:15 2002
From: syver-en+usenet at online.no (Syver Enstad)
Date: Thu, 12 Sep 2002 20:39:15 GMT
Subject: [win32all] Out parameter in outgoing interface
Message-ID: 

It does not seem possible use out parameters in an outgoing interface.

Scenario:

outgoing dispinterface, atl implementation of server, makepy support
generated, python client which implements the outgoing interface.

Tried with both win32com.client.getevents and
win32com.client.DispatchWithEvents

Debugged through it, the event gets fired from atl code the python
code gets called, I thought maybe returning a tuple (the return value
+ the outgoing value) would work but the out parameter, a BSTR* (ie a
OLECHAR**) is untouched back in ATL land.

I guess this is unsupported, or??

-- 

Vennlig hilsen 

Syver Enstad


From max at alcyone.com  Thu Sep 19 21:08:15 2002
From: max at alcyone.com (Erik Max Francis)
Date: Thu, 19 Sep 2002 18:08:15 -0700
Subject: lists in dictonaries ?
References:   
Message-ID: <3D8A74FF.A27BF330@alcyone.com>

xtian wrote:

> Andreas.Leitgeb at siemens.at (Andreas Leitgeb) wrote in message
> news:...
>
> > Oh, can I create a dictionary in Python that contains all those
> > dictionaries that don't contain themselves ... ?-)
> >
> > *scnr*'ly yours.
> 
> Would it contain itself?

[universe collapses in on itself]

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Everybody's playing the game / But nobody's rules are the same
\__/ Florence, _Chess_
    Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html
 A new, virtual planet, every day.


From lu_gio at hotmail.com  Wed Sep  4 17:43:22 2002
From: lu_gio at hotmail.com (Max)
Date: Wed, 04 Sep 2002 21:43:22 GMT
Subject: Database BSD on Mac?
References: <3144be3c280c062e5e71a98ab191f664.98737@mygate.mailgate.org> 
Message-ID: <_7vd9.57894$ub2.928923@news1.tin.it>

> > I was looking on BSD but I'm not sure it is ported to all platforms.
> > Wich db should I utilize?
>
> Do you really need one? Or do either pickle or shelve suffice?

I read shelve can be used for small amount of data... will it work with 5mb?




From ataylor at ucsd.edu  Fri Sep 27 15:59:42 2002
From: ataylor at ucsd.edu (Adam Taylor)
Date: 27 Sep 2002 12:59:42 -0700
Subject: Getting started
References:  
Message-ID: 

> Python types objects and their values rather than names and the fixed
> chunks of memory that names usually refer to in name-typed languages.
> Given a definition of type that sees typeness as inhering only in
> names rather than objects, then yes, Python is 'untyped'.  But how
> useful is such a viewpoint?  It obscures a real difference between
> data models.

Yes, I agree.  I think a better way to classify things (as pointed out
by Alex Martelli, referencing the Scheme spec) is as statically typed
vs. dynamically typed vs. untyped.  Basically, I think the best way to
talk about this stuff is summarized in this diagram:

                      Statically typed   Dynamically typed   Untyped
Strongly checked      ML                 Lisp,Python,Perl
Weakly checked        C                                      Assembler

With the term "weakly typed" being a morass best avoided (IMHO).

Adam

-----
"Terry Reedy"  wrote in message news:...
> "Adam Taylor"  wrote in message
> news:mailman.1032917851.23864.python-list at python.org...
> > Based on this definition, it seems to me that Python _is_ untyped,
> > since the type of a variable can change arbitrarily in mid-program.
> 
> Python types objects and their values rather than names and the fixed
> chunks of memory that names usually refer to in name-typed languages.
> Given a definition of type that sees typeness as inhering only in
> names rather than objects, then yes, Python is 'untyped'.  But how
> useful is such a viewpoint?  It obscures a real difference between
> data models.
> 
> If a language has nested scopes and allows the type of a variable to
> be different in different scopes,  then the type associated with a
> particular name can change arbitrarily in mid-program (at scope
> changes) even if the name is strongly and statically typed within each
> scope.  One can say that the name represents different variables in
> the different contexts (scopes), but the net result is similar to what
> Python does.  Ie, one can view the rebinding of a name to an object of
> different type as implicitly defining a new scope with respect to that
> name.
> 
> Terry J. Reedy


From answer at tnoo.net  Mon Sep  9 13:23:38 2002
From: answer at tnoo.net (Martin =?iso-8859-1?q?L=FCthi?=)
Date: 09 Sep 2002 19:23:38 +0200
Subject: Binary input into NumPy.
References: 
Message-ID: 

>From the manual:

fromstring(string, typecode) 

Will return the array formed by the binary data given in string of the
specified typecode. This is mainly used for reading binary data to and from
files, it can also be used to exchange binary data with other modules that use
python strings as storage (e.g. PIL). Note that this representation is
dependent on the byte order. To find out the byte ordering used, use the
byteswapped() method described on page47.

Hope this helps

Martin

Maurice van de Rijzen  writes:

> Dear all,
> I just downloaded Numerical Python and I think it will be very usefull.
> However I have one major broblem:
> I don't know how to import binary data from a file on disk into an array!
> Can onyone help me with this problem?

-- 
Martin L?thi                 answer at tnoo.net


From sholden at holdenweb.com  Thu Sep  5 21:43:55 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Thu, 5 Sep 2002 21:43:55 -0400
Subject: Gratitude due to Red Hat? More work for the PBF?
References:      
Message-ID: 

"Bengt Richter"  wrote in message
news:al8dbo$408$0 at 216.39.172.122...
> On 05 Sep 2002 11:28:14 -0700, Cliff Wells
 wrote:
> [...]
> >
> >The aggravating thing is that this issue would be a snap for RedHat to
> >fix.  Instead of preempting /usr/bin/python for their own use, they
> >could maintain a /usr/bin/python-rh and leave python for user-installed
> >versions (instead of requiring the user version to be called "python2").
> >
> >Problem solved, everyone happy.
> >
> So why don't they do this? Do they need help?
>

Nobody seems to know. It's such an obvious solution to a really annoying
problem that I can only assume they either refuse to uinderstand there *is*
a problem or they don't appreciate how annopying it can be. Pity they didn't
write Anaconda (their maintenance utility) in Perl, then we wouldn't have
had to suufer the results of their success :-)

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                        pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------





From Patrick.Carabin at SciencesNaturelles.be  Thu Sep 19 08:42:56 2002
From: Patrick.Carabin at SciencesNaturelles.be (Patrick Carabin)
Date: Thu, 19 Sep 2002 14:42:56 +0200
Subject: How do I reply to an item in the list ?
Message-ID: <02091914425601.01191@pc20_118>

I 'd like to answer a message, e.g. on the topic ?Installation of 
multiple versions of Python on Unix?, but on the page
http://mail.python.org/pipermail/python-list/2002-September/120875.html
which contains the message i 'd like to ?reply? to, there is NO 
?replybutton?. How can i do ?
TIA


Patrick Carabin.

Institut Royal des Sciences Naturelles de Belgique 
http://www.SciencesNaturelles.be/
Koninklijk Belgisch Instituut voor Natuurwetenschappen 
http://www.NatuurWetenschappen.be/ 

?Het geluk is niet op het einde van de weg, het geluk is de weg.?
?Le bonheur n'est pas au bout du chemin, le bonheur est le chemin.?
						Dala? Lama.



From paul.pichaureau at nospam.laposte.net  Sun Sep 29 19:49:43 2002
From: paul.pichaureau at nospam.laposte.net (Paul Pichaureau)
Date: Mon, 30 Sep 2002 01:49:43 +0200
Subject: Python's import: why doesn't it work?
References: 
Message-ID: 

"Tim Peters"  a ?crit dans le message de news:
mailman.1033322378.3697.python-list at python.org...

> The docs are exactly as good as volunteers have made them (well, actually
> better, thanks to Fred ).  When you find an explanation inadequate
to
> your needs, suggesting specific improvements in the right place is the
only
> way it will improve.

  Then, these are my suggestions to improve documentation on installing and
managing module :

** I have found no explanation of any kind about what I shall put in the
__init__.py file.
** I have seen many module where this file contain just one "import" line,
e.g.

  import the_module_in_this_directory

This seems silly, and I suggest somebody documents the exact way how one
specific function is eventually loaded by the interpreter.

I have read all the documentation about docstrip, and I don't know at all
what I have to do to import a given fonction.

** Is the __name__ list indispensable ? Nobody seems to use it...
** How the sys.path is created in a run, and how can it be cleaned (for
example, when I uninstall a old package, or an obsolete version of a
package).

Suggestion for the distutil package :

** First a complete documentation. I don't like the pseudo-pedagocical style
of the actual documentation. I prefer a complete and clear explanation of
all the command avalaible. The two type of documentation should be
avalaible.

** A clean and safe way to uninstall package. I can't understand why this
hasn't been implemented yet.

** The actual beahviour is quite strange : distutil install all the
subdirectory of the current working directory.
For example, if you consider this tree :

---setup.py
(main dir)
---titi.py
------(lib dir)
---------__init__.py
---------toto.py
------(stuff dir)
---------__init__.py
---------tata.py

  If you declare the package main.lib, the package main.stuff will also be
installed. Seems silly to me

                    Paul




From aleax at aleax.it  Wed Sep 25 05:26:24 2002
From: aleax at aleax.it (Alex Martelli)
Date: Wed, 25 Sep 2002 09:26:24 GMT
Subject: help with print function in extension
References: 
Message-ID: <4jfk9.163306$pX1.5842487@news2.tin.it>

Eric Hagemann wrote:

> I'm handcrafting an extension in C
> 
> If have defined both a str() and a repr() function and when I execute
> either repr(obj), or str(obj) I get what I expect
> 
> however if I execute 'print obj' I get the following error
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
> SystemError: error return without exception set
> 
> although 'print str(obj)' works like I think it should
> 
> Am I mistaken in thinking that  'print str(obj)' should be the same as
> 'print obj'

*ALMOST!*  In the PyTypeObject struct, there's a tp_print slot
that is used by preference, if non-null, when you print something
and stdout is a real file.  What do you have in tp_print for
your type?  It's smack in-between tp_dealloc and tp_getattr.


Alex



From gerhard.haering at opus-gmbh.net  Wed Sep  4 13:55:57 2002
From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: 4 Sep 2002 17:55:57 GMT
Subject: Does BlackAdder really suck?
Message-ID: 

I just checked out the BlackAdder demo and was quite disappointed.

I expected that this is a tight integration of Python and PyQt. But it
looks like it's just Qt Designer embedded in the IDE, while still having to
run pyuic manually. I don't know if at least the debugger is any good,
because the demo was quite limited.

Is there any usable commercial IDE for GUI design? BlackAdder and
PythonWare Pro seem to be the only candidates (yes, I did check out Boa).

-- Gerhard


From Stefan.Schwarzer at tu-clausthal.de  Wed Sep  4 15:10:13 2002
From: Stefan.Schwarzer at tu-clausthal.de (Stefan Schwarzer)
Date: Wed, 04 Sep 2002 21:10:13 +0200
Subject: Strange threads/stack size interaction on FreeBSD
Message-ID: <3D765A95.6090308@tu-clausthal.de>

OS: FreeBSD 4.6.2
Python: 2.2.1 (built from the ports collection)
Hardware: Dual Processor Athlon, 1 GB RAM

I compiled Python while having a default stack size (as shown by ulimit -a)
of 262144 kbytes.

Because of a problem with a Python program (that dumped core, but that's
another problem) I recompiled the kernel with a stack size of 524288 kbytes.
After rebooting the program mentioned succeeded without errors.

A while later I noticed that a unit test case dealing with threads no longer
worked; it hung. Checking with /usr/local/lib/python2.2/test/test_threading.py
I observed that it hung, too, after only printing "waiting for all tasks to
complete".

After rebooting the system with the old kernel with the old stack size, I
saw both my own unit test and test_threading.py succeed! I also tried
compiling Python for the larger stack size but that didn't help either.

It seems, that there is some interaction between the set stack size and
Python's threading code.

I've searched the Python FAQ, Google Groups and the bug database of the
Python project on this, but without success, so I have some questions.

- Has anybody here experienced something similar, perhaps on other
   platforms?

- Is Python's threading code dependent on a stack limit set at compiled
   time (seems so)?

- What are your recommendations to deal with the problem?

- Should I enter a bug report on this topic?

Stefan



From maxm at mxm.dk  Tue Sep  3 04:58:58 2002
From: maxm at mxm.dk (Max M)
Date: Tue, 03 Sep 2002 10:58:58 +0200
Subject: string reading bug in ActiveState Python 2.2 ?
References: <3D74757D.1010405@molgen.mpg.de>
Message-ID: <3D7479D2.60100@mxm.dk>

Axel Kowald wrote:


> I'm using ActiveStates Python 2.2.1 under win2000 to read in the 
> attached text file and it seems that python is only reading part of the 
> string. After
> 
> fp = open("bla.txt")
> z = fp.read()
> print len(z), z
> 
> I see that only 11 of the 15 characters have been read. I know they are 
> non-printable characters, but that shouldn't matter, should it ?  Using 
> another python on one of our unix machines everything works as expected 
> and all 15 chars are read in.  Is that there something special about 
> windows that I should know, or is this a bug in ActiveStates Python ?



Probably you should open it as a binary file:


fp = open("bla.txt","b")


regards max M



From jstavnitzky at atsautomation.com  Fri Sep 20 12:09:08 2002
From: jstavnitzky at atsautomation.com (Jay)
Date: 20 Sep 2002 09:09:08 -0700
Subject: Porting woes
Message-ID: <3a4b2539.0209200809.407d50d5@posting.google.com>

Hello, I am in the process of trying to port Python to a TI
TMS320C6xxx series DSP.  The code now compiles (under the TI Code
Composer IDE), but I have assertions failing at runtime.  The
assertion reads as follows:

Assertion failed, (((cls)->ob_type == &PyClass_Type)), file
typeobject.c, line 649

This failure is occuring during the function classic_mro().  The stack
at that point is classic_mro(),mro_implementation(),mro_internal(),PyType_Ready(),
PyTypeReady(),Py_ReadyTypes(),Py_Initialize(),Py_Main().

Help!! What is happening at this point, and what could be causing this
assertion to fail?

Thanks,
Jay


From pinard at iro.umontreal.ca  Thu Sep 26 10:49:27 2002
From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard)
Date: Thu, 26 Sep 2002 10:49:27 -0400
Subject: HTML page for Pymacs 0.18
Message-ID: 

Hi!

There is now a simple HTML page for Pymacs, which repeats the documentation
found in the `README' file of the version 0.18 of the distribution:

   http://www.iro.umontreal.ca/~pinard/pymacs/

-- 
Fran?ois Pinard   http://www.iro.umontreal.ca/~pinard




From aleax at aleax.it  Tue Sep 24 08:39:32 2002
From: aleax at aleax.it (Alex Martelli)
Date: Tue, 24 Sep 2002 12:39:32 GMT
Subject: Three dumb questions (ordered by dumbness descending)
References: 
Message-ID: <82Zj9.136094$ub2.2966822@news1.tin.it>

Thorsten Kampe wrote:

> Okay, here they are:
> 
> 1. Why is 'zip(zip(x)) != x' (should be the same because it's the
> transposed)

I think this has been answered at length (you need the * special form
for the arguments -- and x to be of the right kind -- and then the
equality will hold).


> 2. Peter Norvig mentions in "Python for Lisp Programmers" some
> "don'ts": "[x] + y" and "x[1:]". Are there more things to avoid
> (especially in a loop)?

Strictly a performance issue: these operations are O(N) in len(y)
and len(x) respectively, and Peter is writing for an audience used
to similar operations (cons and cdr respectively) being O(1).  There
is no special reason to avoid such constructs if they best express
what you really want to do.

The only Python performance pitfall that's REALLY easy to fall into:

    hugestring = ''
    for piece in alotoftinypieces:
        hugestring += piece

Now THIS is guaranteed to kill your program's performance.  Use:

    hugestring = ''.join(alotoftinypieces)

and enjoy roughly O(N) performance rather than roughly O(N squared).

More generally, I think that putting strings together with + or +=
IS something "to avoid (especially in a loop)" -- if you don't
already have a sequence of all the tiny pieces, build one up (e.g.
by appending the pieces to an originally empty list) and finally
''.join it.  Strings are immutable, so "hugestring += piece"
forces Python to free the space it originally held for hugestring
and allocate a new one.  Lists are mutable, and in an amortized
sense there's "always" a free slot at the end, so templist.append
is O(1) [amortized].


> 3. random.shuffle: the documentation says: "Note that for even rather
> small len(x), the total number of permutations of x is larger than the
> period of most random number generators; this implies that most
> permutations of a long sequence can never be generated." I translate
> this to "don't shuffle lists with more than 15 elements if you want a
> randomly ordered list".
> 
> Alex Martelli says the same: "For example, Python users who are
> calling random.shuffle on a sequence of substantial length have a need
> for an underlying random generator with a *HUGE* period, as a
> necessary although not sufficient condition towards ensuring that all
> permutations of the shuffled sequence get generated with equal
> likelihood.
> 
> Wichman-Hill has a period of less than 7,000 billions (7e12),
> insufficient to account even for the permutations of a sequence
> whose length is just 16 (16! > 2e13)."
> 
> Otherwise in the "Python Cookbook" (Selecting Random Elements from a
> List Without Repetition) the shuffle version is called "the winner".
> 
> So: can I use random.shuffle or do I have to write my own - slower -
> version to get a random list?

For most practical purposes, you can use random.shuffle.  If you
must guarantee that *all* permutations are equally likely, then
your first issue is ensuring enough randomness -- a generator with
a period of over 10**68 or so to permute 52 objects, for example --
and that's not at all a sufficient condition, either.  If you really
labor under such strict conditions, maybe it's better to use a
"truly random" (hardware) generator rather than a pseudo-random one.

Once you do have a random or pseudo-random generator that fully
satisfies you, Ian Bicking's snippet reimplementing shuffle as a
Decorate-Sort-Undecorate idiom is truly excellent -- a little jewel,
IMHO, despite the little typo in it.  It does, alas, end up a
little slower than Tim Peters' original -- but losing a speed
competition to Tim is no shame, and Ian's version only loses very
very little indeed.  To wit (having corrected Ian's typo):


import time, sys, operator
from random import random

def shuffle_org(x):
    for i in xrange(len(x)-1, 0, -1):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = int(random() * (i+1))
        x[i], x[j] = x[j], x[i]

def shuffle_ian(x):
    newList = [(random(), i) for i in x]
    newList.sort()
    x[:] = [i[1] for i in newList]


biggie = range(200)

def timit(func, N=1000):
    repeat = [None] * N
    start = time.clock()
    for x in repeat: func(biggie)
    stend = time.clock()
    return "%2.2f %s" % (stend-start, func.__name__)

print sys.version
for i in range(2):
    for func in shuffle_org, shuffle_ian:
        print timit(func)


[alex at lancelot linud]$ python -O timo.py
2.2.1 (#2, Jul 15 2002, 17:32:26)
[GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)]
1.59 shuffle_org
1.87 shuffle_ian
1.60 shuffle_org
1.86 shuffle_ian
[alex at lancelot linud]$



Alex



From duncan at NOSPAMrcp.co.uk  Fri Sep  6 09:12:31 2002
From: duncan at NOSPAMrcp.co.uk (Duncan Booth)
Date: Fri, 6 Sep 2002 13:12:31 +0000 (UTC)
Subject: tree data structure
References:   
Message-ID: 

Padraig Brady  wrote in
news:Us1e9.2865$cP3.6131 at news.iol.ie: 

>> assert result==('L0', [('S2', [('S0', [('Q1', [])]), ('S1', [('Q2',
>> [])]), ('S3', [])])])
>> 
>> 
> 
> It certainly does!
> Just one thing...Why use lists instead of tuples?

Specifically because you can't append to tuples, but you can append to a 
list.

However, a general rule of thumb is to use tuples where you want a record 
(but don't want the overhead of a full-blown class). So each node here is a 
record with the fields name,children. Use a list where you want to store a 
collection of unknown length: so a list is appropriate for the children.

Note that neither your original list, nor the code I used actually force 
this to be a tree, you could equally well have a graph with or without 
cycles. You will find it impossible to represent a graph containing cycles 
if you use tuples throughout.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?


From martin at v.loewis.de  Mon Sep 30 17:17:43 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 30 Sep 2002 23:17:43 +0200
Subject: a question about mailman
References: 
Message-ID: 

"Mark McEahern"  writes:

> In that context, I wonder, "Wouldn't it be easier if you could configure
> Mailman to insert the archive URL into the footer of outgoing messages?"

I'm not sure I understand this question: Do you want to add the URL of
the list archive to the footer, or the URL for the specific message?

Adding the URL for the entire archive is easy (it only varies with the
list, not with the message), so I assume you want to add the URL for
the message itself.

> 1.  Would this generally be useful--having the ability to put message
> specific information in the footers?
> 2.  Would it specifically be useful to put the archive url into the footers?
> (I personally think so.)
> 3.  Is the vague approach I sketched above the way you'd do it?  That is,
> does it seem likely that it would work?

Yes, yes, and no. I believe the trick is that, at the point of sending
the message, you cannot know the URL that the message will get in the
archive. Finding out that URL is particularly tricky in presence of
external archivers.

Regards,
Martin



From writeson at earthlink.net  Tue Sep  3 10:40:14 2002
From: writeson at earthlink.net (Doug Farrell)
Date: 3 Sep 2002 07:40:14 -0700
Subject: RedHat 7.3 and Python2.2.1
References: 
Message-ID: <88bc63c6.0209030640.71e074ff@posting.google.com>

To everyone who responded,

Thanks you for all your help, much appreciated. I ended up solving the
problem (at least I hope so, and didn't create more for myself! )
by doing the following:

rpm -ivh --replacefiles python-2.2*

The --replacefiles option seemed to eliminate the file conflicts and
the RedHat tools (like up2date) still are working.

Again, thanks!
Doug


From aahz at pythoncraft.com  Tue Sep 17 10:36:49 2002
From: aahz at pythoncraft.com (Aahz)
Date: 17 Sep 2002 10:36:49 -0400
Subject: threads or queue for this task
References: 
Message-ID: 

In article ,
Bjorn Pettersen  wrote:
>
>If you have any amount of data to process (why else would you be
>multithreading?) I've never seen producers and consumers being close
>enough in performance to not have the system end up swapping to death --
>unless, that is, if the queue is bounded. The Python Queue module
>supports most of this out-of-the-box, and adding timeouts is fairly
>trivial...

Well, one instance would be where producer and consumer are the same
threads.  For example, a web spider.  You *want* an unbounded queue in
that case to avoid deadlock.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Project Vote Smart: http://www.vote-smart.org/


From tismer at tismer.com  Mon Sep 23 17:53:59 2002
From: tismer at tismer.com (Christian Tismer)
Date: Mon, 23 Sep 2002 14:53:59 -0700
Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss?
References: 
Message-ID: <3D8F8D77.1090500@tismer.com>

Tim Peters wrote:
> [Christian Tismer]

[you cannot discuss it since they want it]

> Bless you, Christian!  That's all the truth.  It reminds me of my first job
> in this business, where after a few months my boss took me aside and
> reminded me that I was hired to be a prostitute, not a missionary .

Hee hee, yes we are prostitutes. Well, Open Source is a way
out. But when you want people to pay you for it, it slips in, again.

> otoh-the-bankers-need-stackless-but-just-don't-know-it-yet-ly y'rs  - tim

I'll let them know, teling them that Stackless is pure decimal.

ciao - chris

-- 
Christian Tismer             :^)   
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34  home +49 30 802 86 56  pager +49 173 24 18 776
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/





From johanfo at essay.org  Mon Sep 23 17:01:54 2002
From: johanfo at essay.org (Johan Fredrik Øhman)
Date: Mon, 23 Sep 2002 23:01:54 +0200
Subject: Dynamic loading of modules
References:  <87sn00zeke.fsf@pokey.henrik-motakef.de>
Message-ID: 

I tried this below.  But as you see, even if the Password.py has a "def init()"
it doesn't work.

Python 2.2 (#1, Mar 26 2002, 15:46:04)
[GCC 2.95.3 20010315 (SuSE)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> z = __import__("plugins.Password")
>>> z.init()
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'module' object has no attribute 'init'

--
Johan Fredrik ?hman


"Henrik Motakef"  wrote in message
news:87sn00zeke.fsf at pokey.henrik-motakef.de...
> "Andreas Lydersen"  writes:
>
> > Hi,
> > I'd like to load a set of modules from a directory.  I have tried to use the
> > __import__(...) statement to do so, but with no success.
> > ?
> > The static approch works (of course), but the dynamic does not!
> >
> > static:
> > import plugins.Password
> >
> > dynamic atttempt:
> > __import__("plugins.Password")
>
> __import__ doesn't really import the module, it returns a module
> object. So do something like
>
> >>> pwd = __import__("plugins.Password")
> >>> pwd.spam()
> Spam!
>
> hth
> Henrik




From torkil at fast.no  Tue Sep 17 05:03:30 2002
From: torkil at fast.no (Torkil Grindstein)
Date: Tue, 17 Sep 2002 11:03:30 +0200
Subject: Regular expression help needed
Message-ID: <3D86EFE2.CFF57171@fast.no>

Hi.

It's been a while since I played around with regexps, and I
realize that I really need some help here.

Mission: I have a string containing a whole WML document. I want
to extract data from following occurences:



That is, I want to extract the content of any occurences of
the meta "michael" key. There may be several occurences in one
document.


will give me the results "owen" and "jackson".

Of course, it is possible that the document has written the
tags in uppercase (META Name, META NAME, etc), but I could
lowercase the whole document string prior to searching. (The
content is case insensitive for my purposes.)

I would really be glad if someone out there took this challenge..:)

Cheers,
Torkil


From wilk-spamout at flibuste.net  Mon Sep 30 05:24:43 2002
From: wilk-spamout at flibuste.net (William)
Date: 30 Sep 2002 11:24:43 +0200
Subject: Why does QT Windows need Visual Studio?
References: <3ljepusnje8iuca90im2r9vceja5tfc5l7@4ax.com>
Message-ID: <87fzvr7rtw.fsf@flibuste.net>

John Hall  writes:

> I was about to download the Windows non-commercial version of QT, but
> noticed that it requires MS Visual Studio, so didn't.
> This requirement surprises me - is there a way around that?

It will work even without visual studio... Just install it, and pyqt.

But this strange licence make me prefer wxpython for now.

-- 
William Dod? - flibuste.net
http://wikipython.tuxfamily.org


From steve at ferg.org  Thu Sep 12 09:04:54 2002
From: steve at ferg.org (Stephen Ferg)
Date: 12 Sep 2002 06:04:54 -0700
Subject: ANN: Thinking in Tkinter
References:  <3D798461.B3FE0E06@earthlink.net>  <3D7C210F.7090708@something.invalid>   <3D7FFC43.10002@something.invalid>
Message-ID: 

Thanks for the tips on where to find Human Interface Guidelines.

> It's a fairly universal principle in Tk that the
> "command" of a widget is invoked according to the
> standard behaviour of that widget, so I think it
> deserves treatment as a fundamental principle
> on the same footing as event binding.

Absolutely!  This observation is GOLD! This is just the kind of thing
I'm trying to get at in "Thinking in Tkinter".

Let me make sure I've got it right.  We have two fundamental, and
different, approaches to specifying the behavior of a widget.

(1) event binding, in which you get to "roll your" own bindings by
binding callbacks to particular events that you specify.

(2) command binding, in which a standard behavior for a widget is
already defined for you by Tkinter (and Tk), and you bind a callback
to that standard behavior.

This explains why "command" binding doesn't automatically pass an
event object the way that event binding does.  The standard behavior
of a widget  might be defined across multiple kinds of events  (e.g.
Button's standard behavior is defined across both a button-press and a
button-release), so there is no *single* event that could be passed.

-- Steve


From Oschler at earthlink.net  Sat Sep 28 14:37:13 2002
From: Oschler at earthlink.net (Robert Oschler)
Date: Sat, 28 Sep 2002 18:37:13 GMT
Subject: Best way to create a class dynamically on the fly?
Message-ID: 

What is the best way to create a Python class dynamically at runtime?  A
sample or doc would be great.  I'm a veteran C++ programmer so this concept
is very alien to me as you can imagine (dynamically created classes).  An
example that would show the creation of a descendant (sub-class), and a
another example showing the creation of an ancestor class would be perfect.

thx





From loewis at informatik.hu-berlin.de  Wed Sep 18 02:48:52 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=)
Date: 18 Sep 2002 08:48:52 +0200
Subject: Detecting IPv6 support
References:    <3D854B7D.1060209@one.net>    <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com>      
Message-ID: 

Pekka Pessi  writes:

> 	I have Redhat 7.3. The prepackaged RPMs have disabled IPv6, but
> 	the underlying OS supports it. So, this is what happens with the
> 	bind() system call, for instance:

I see. Testing for that isn't really supported. A reliable way is to
inspect pyconfig.h, whose location is available through
distutils.sysconfig.get_config_h_filename(); check whether it contains
a line

#define ENABLE_IPV6 1

(more precisely, check whether the line containing ENABLE_IPV6 does
not contain undef, and starts with whitespace*#.

> 	So AF_INET6 is there, and I can create a socket, but everything
> 	dealing with addresses fails. 

That, perhaps, gives a reliable test, too: See whether
socket.getaddrinfo("::",80) succeeds.

Determining whether the system "supports" IPv6 is more tricky: If you
can create an INET6 socket, the system supports the protocol. I don't
know how to find out whether there are any configured non-local
interfaces. I don't think there is a way to determine whether the
system has v6 connectivity to "the world".

Regards,
Martin


From sholden at holdenweb.com  Fri Sep 13 07:56:24 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Fri, 13 Sep 2002 07:56:24 -0400
Subject: [FEEDBACK] Is this script efficient...is there a better way?
References:   <4ZRf9.1782$Lg2.248733@news2.news.adelphia.net> <3hSf9.168947$l_4.98525@atlpnn01.usenetserver.com> <8PSf9.1796$Lg2.257378@news2.news.adelphia.net> <_oUf9.170870$l_4.126599@atlpnn01.usenetserver.com> 
Message-ID: <3pkg9.3313$WV.2782@fe03>

"Bob X"  wrote ...
> Steve Holden wrote:
> > "Bob X"  wrote ...
> > [ ... ]
> >
> >>Thank you very much...your shorter script did work. The keywords are all
> >>"normal" english words that would not have any special characters. I
> >>only added a re.IGNORECASE (since case doesn't matter to me) after a
> >>quick search of the python docs.
> >>
> >
> > Was there any significant difference in the timings for the two
different
> > methods, and how does the number of different keywords affect the
timings?
> >
> I haven't tested...is there an easy way to time it...besides my going
> "that one ran faster"?
>
> However, I had a chance to run your RE version today and it did very
> well. BTW..the line that looked like a debug statement was just a visual
> for me to see the script was actually doing something. I put in a
> counter that prints "lines written:", a where "a" is the counter. I do
> have one question on that. It writes each line sequentially like:
>
> lines written: 1
> lines written: 2
> lines written: 3
>
> Can I just get it to do it in place? Where the numbers are just replaced
> instead of scrolling? Just a thought...
>

That shouldn't be too difficult. Somebody recently posted code for Python
"spinners", that could be the bases of your efforts. See [... googles ...]

Aargh. Apparently I didn't save any attribution for the attached -- it's not
my code, somebody else wrote this and published it in c.l.py, but I don't
have a record of who it was. As far as timing goes, just subtract
time.time() at the beginnig from time.time() at the end for a naiive
approach. If this doesn't show any differences  it's probnably not worth
measuring more closely...

import threading, time, sys


class Spinner( threading.Thread ):

    DELAY = 0.1
    DISPLAY = [ '|', '/', '-', '\\' ]

    def __init__( self, before='', after='' ):
        threading.Thread.__init__( self )
        self.before = before
        self.after = after

    def run( self ):
        write, flush = sys.stdout.write, sys.stdout.flush
        self.running = 1
        pos = -1
        while self.running:
            pos = (pos + 1) % len(self.DISPLAY)
            msg = self.before + self.DISPLAY[pos] + self.after
            write( msg )
            flush()
            write( '\x08' * len(msg) )
            time.sleep( self.DELAY )
        write( ' ' * len(msg) + '\x08' * len(msg) )
        flush()

    def stop( self ):
        self.running = 0
        self.join()


class BarberPole( Spinner ):
    DISPLAY = [ '|/__/__/__|', '|_/__/__/_|', '|__/__/__/|' ]

class HAL( Spinner ):
    DELAY = 0.2
    DISPLAY = [ ' ', '.', '+', '*', '+', '.', ' ', ' ' ]

class MySpin(Spinner):
 DELAY = 0.08
 DISPLAY = [' ', '.', ':', '!', "'"]

def test():

    spinner = MySpin("My own spinner: [", ']')
    spinner.start()
    time.sleep(5)
    spinner.stop()

    spinner = Spinner( "[syncing... ", "]" )
    spinner.start()
    time.sleep( 5.0 )
    spinner.stop()
    print "Disks synced."

    pole = BarberPole( "Shutting down: " )
    pole.start()
    time.sleep( 5.0 )
    pole.stop()
    print "You may now switch off your computer."

    hal = HAL( "[", "]  I'm sorry Dave" )
    hal.start()
    time.sleep( 5.0 )
    hal.stop()
    print "I'm afraid I can't do that."


if __name__ == '__main__':
    test()

Works well, though, and will show you how to update your message in place.

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------





From bdesth at free.fr  Thu Sep  5 08:18:41 2002
From: bdesth at free.fr (Laotseu)
Date: 5 Sep 2002 05:18:41 -0700
Subject: Why Python?
References: 
Message-ID: <4f49d232.0209050418.7668c21@posting.google.com>

Benjamin  wrote in message news:...
> Hi guys (and girls)
> I just begun to learn how to program. And I choosed Python for
> doing that. surfing around the web i found an article about this
> language, they said it's the ideal language for beginners to the
> world of programming. and i admit it, the syntax is very clear making
> the code very readable, i learn easily the concepts of programming
> and i soon wrote some nice programs. but since i finished my
> newbie-tutorial, i am wondering about one question: is it worth to go
> deeper into python? i talked to a friend of mine, he told me that i
> should try php..
> what should i do?? ^_^ in other words: 

> what is python good for?
Python is a 'general', hi level programming language. You can use it
from simple scripting tasks to full-blown applications.

Now what it may not be good for :
- really intensive computing, needing to take advandage of
multithreading on a multi-processor system
- writing low level code, like OS Kernel, Drivers, etc.

For those kind of task, C (or Ada or... ) could be a better choice.

> why should i continue with python?
Because it's easy, powerful, and really funny, and it's ok for most of
what you could have to do as a beginner.

Now you should *also* learn other languages. But you'd better go with
a lo level languages and a functionnal one - C and Lisp could be good
choices.

Once you'll know Python *and* C *and* Lisp, you should not have big
troubles learning many other (Php included) !-)

laotseu

> thank you!
> 
> _____________________________________________________
> I'm going to prove the impossible really exists


From dbasch at yahoo.com  Mon Sep 30 11:59:40 2002
From: dbasch at yahoo.com (Derek Basch)
Date: Mon, 30 Sep 2002 08:59:40 -0700 (PDT)
Subject: Catching user defined exceptions from foreign modules
Message-ID: <20020930155940.23964.qmail@web20805.mail.yahoo.com>

Everyone,
You were correct that the test1 module shouldn't have
worked at all. I needed to change the first line to:

from test2 import TestError, TryItOut

I had test2 open in the PythonWin IDE so it was
already in the namespace.
Which brings me back to my original issue of why it
works here and not in my larger module. Is it normal
to have to import user defined exceptions? I dont
rememeber having to import any of the built in
exceptions. So, here is the output of the fixed test1:

test2.TestError
fudge

Am I doing this all wrong?
Thanks,
Derek Basch




 
Derek Basch fed this fish to the penguins on Sunday 29
September 2002 
07:22 pm:

> I know that TestError has been imported because I
can
> put a "print TestError" before the except clause in
> test1 and I get "test2.TestError". Can anyone tell
me
> why I am having to put the test2.TestError instead
of
> just TestError? It confuses me even further that my
> small test modules work like I would expect and it
> doesn't work on the larger modules.
>

I don't even see why "test1" is working. You
explicitly import the 
exception by name, but you didn't bring in
"TryItOut"... That alone 
should have raised an exception.


[wulfraed at b... wulfraed]$ python test1.py
Traceback (most recent call last):
File "test1.py", line 14, in ?
letitrip.run()
File "test1.py", line 7, in run
tryitout = TryItOut()
NameError: global name 'TryItOut' is not defined


__________________________________________________
Do you Yahoo!?
New DSL Internet Access from SBC & Yahoo!
http://sbc.yahoo.com



From noone at nowhere.com  Fri Sep 13 02:43:34 2002
From: noone at nowhere.com (Marcus)
Date: Fri, 13 Sep 2002 06:43:34 GMT
Subject: Tkinter experts out there?
Message-ID: 

I am trying to get some answers on using Tkinter, does anyone know if there
are channels or forums being actively used?

Thanks
Matthew Bonig




From gkrause at psipenta.com  Fri Sep 13 05:39:02 2002
From: gkrause at psipenta.com (Gernot Krause)
Date: Fri, 13 Sep 2002 11:39:02 +0200
Subject: dynamic includes from classes...
References: 
Message-ID: 

Hi
> First, is there a better way than exec to dynamically include a module?
> i.e.
> importvar = "foo"
> exec("from %s import %s" % (importvar, importvar))
(Sorry for my horrible english)
In my mind,its better - you implement a interface class.
If you know the criteria - on script parse time - which class would be used
,
then try this.

DependClass = importvar

class Interface (DependClass):
    def __init__(self):
       DependClass.__init__(self)
    def __del__(self):
       DependClass.__del__(self)
...
Gernot







From dgallion1 at yahoo.com  Sat Sep 14 09:28:56 2002
From: dgallion1 at yahoo.com (darrell)
Date: Sat, 14 Sep 2002 13:28:56 GMT
Subject: Help with regular expression using findall and .*?
References: 
Message-ID: 

Here's an example with backtracking turned off
>>> s="""a\nb\n1""" 
>>> re.findall("[^\n]+?\d", s) 
['a\nb\n1'] 

Which is not correct.
What ever pattern proceeds the '+' must be reevaluated as the pattern moves 
forward. sre handles this though recursion.

import re
s2=('macro\n'+'a'*20000+'\norcam\n')*10
s2split=re.split("macro\n|\norcam\n",s2)
for r in s2split:
    print r


This should be fast also.
--Darrell


czrpb wrote:
> Harvey:
> 
> Great thanks!! And thanks for sticking to my question's requirements.
> 
> 
> Ok, this is what we thought around here. But what I do not understand is
> why any backtracking data is being kept? The '?' in '.*?' means it is
> non-greedy right? When would backtracking ever occur using '.*?'? What am
> I missing?
> 



From cliechti at gmx.net  Sun Sep  1 07:19:22 2002
From: cliechti at gmx.net (Chris Liechti)
Date: 1 Sep 2002 13:19:22 +0200
Subject: Import error depending on where importing from
References: <20020831.231529.1350573793.13153@cybermesa.com>
Message-ID: 

"Jay O'Connor"  wrote in 
news:20020831.231529.1350573793.13153 at cybermesa.com:
> For certain reasons, I had to put the MySQLdb files in my own directory
> (called 'lib').   Now, when I'm in the lib directory I can import MySQLdb
> and use it fine.  However, when I'm one directory up, and I try to do
> "from lib import MySQLdb" I get 
> ImportError: _mysql: init failed

you need to make sure that the module is in a directory that is in 
"sys.path". you can add you "lib" with 
"sys.path.append(os.path.abspath('lib'))" or whatever is appropriate for 
you.
 
chris

-- 
Chris 



From Nicola.Musatti at ObjectWay.it  Mon Sep 16 07:56:30 2002
From: Nicola.Musatti at ObjectWay.it (Nicola Musatti)
Date: Mon, 16 Sep 2002 13:56:30 +0200
Subject: Good book choice?
References:  <05k9ou4o2m9e41puce9ni3953b5hbhn8c0@4ax.com>
Message-ID: <3D85C6EE.CB7A1F52@ObjectWay.it>


robin at execulink.com wrote:
[...]
> Can't help you with those, but have had luck with Learning Python
> (Mark Lutz & David Ascher, pub. O'Reilly), a great introduction to the
> language that doesn't pad out its length with stuff you can read in
> the reference documentation. I think it's the single-best Python book
> out there. So do the other developers I work with.

While this is definitely a good book, I feel it is a bit slow paced for
someone with programming experience. It is also based on a rather old
version of the language. I'm not sure whether a new edition is in the
works or not.

Cheers,
Nicola Musatti


From skip at pobox.com  Tue Sep 10 14:52:37 2002
From: skip at pobox.com (Skip Montanaro)
Date: Tue, 10 Sep 2002 13:52:37 -0500
Subject: how to build wxPython w/ Sun's C++ compiler?
In-Reply-To: 
References: 
        
        
        <23891c90.0209092359.11acb607@posting.google.com>
        
        
Message-ID: <15742.16245.999727.145361@12-248-11-90.client.attbi.com>

    >> Agreed.  However, disutils commands have this structure:
    >> 
    >> python setup.py [ options ] command [ more options ] ...
    >> 
    >> which I think can get kind of confusing.

    Martin> You forgot 

    Martin>   python [ options ] setup.py [ options ] command [ more options ] ...

    Martin> :-)

I finally concluded that you either need to use command line switches or ini
files plus a setup.py command line switch which enables the .ini file.  If
you use just .ini files which are always enabled, you might well wind up
screwing up a Python install.

Skip



From alienoid at is.lg.ua  Tue Sep  3 06:03:05 2002
From: alienoid at is.lg.ua (Ruslan Spivak)
Date: Tue, 3 Sep 2002 13:03:05 +0300
Subject: code doesn't work: question
Message-ID: <1551859543.20020903130305@is.lg.ua>

Hello python-list user,

I want somebody to explain me why next code doesn't work:

var = 5

if (tmp = var) == 5:         # this is the error line
   print "ok"
else:
   print "error"

Best regards,
 Ruslan                          mailto:alienoid at is.lg.ua




From whisper at oz.net  Thu Sep  5 20:07:21 2002
From: whisper at oz.net (David LeBlanc)
Date: Thu, 5 Sep 2002 17:07:21 -0700
Subject: try blocks in Python vs. C++
In-Reply-To: 
Message-ID: 

I think the biggest reason why try blocks aren't suggested for use in C++ is
that they increase code size substantially (as do some other nice features).

Try...except is good practice in Python IMO.

David LeBlanc
Seattle, WA USA

> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of Roy Smith
> Sent: Thursday, September 05, 2002 16:54
> To: python-list at python.org
> Subject: try blocks in Python vs. C++
>
>
> I'm reading Stroustroup's C++ book, and came upon a piece of advice to
> avoid using try blocks.  I use try blocks a lot in Python and gather
> it's common practice among pythonistas.
>
> Is there something fundamentally different about try blocks in Python
> and C++ which makes them more attractive to use in one vs. the other?
> On the surface, they appear to be virtually identical in just about
> every respect.  Is it simply a cultural difference?  Or just the
> author's own personal style?
> --
> http://mail.python.org/mailman/listinfo/python-list




From lu_gio at hotmail.com  Mon Sep 23 05:20:47 2002
From: lu_gio at hotmail.com (Max)
Date: Mon, 23 Sep 2002 11:20:47 +0200
Subject: PyGame + PyOpenGl + ZBuffer?
Message-ID: <3D8EDCEF.70F827F6@hotmail.com>

Hi!
I found my code is not working well in all computers: with a SiS 300/200
graphic card, the Z buffer seems disabled.

The OpenGL initialization code is:

pygame.init()
pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF|HWSURFACE,32 )
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LESS)
glDepthRange(0,1)

How can I force Opengl to utilize ZBuffer?




From andrew.henshaw at mail.com  Sun Sep 15 00:54:47 2002
From: andrew.henshaw at mail.com (Andrew Henshaw)
Date: Sun, 15 Sep 2002 00:54:47 -0400
Subject: Skipping Parts of a For Loop
References: 
Message-ID: 

Thomas Guettler wrote:

> Hi!
> 
> Is there a way to skip some parts in a for loop?
> 
> 
> for i in range(3):
> print "i before", i
> i=2
> print "i after", i
>
...snip... 
> 
> Is there a way to skip some parts?
> 
> "continue" skipps one element. But how can
> I skip several?
> 

While not really answering your question... In my opinion, it would be 
better to use a while loop for that purpose.  The code would be much 
clearer.

-- 
Andy Henshaw


From aleax at aleax.it  Wed Sep 18 09:16:28 2002
From: aleax at aleax.it (Alex Martelli)
Date: Wed, 18 Sep 2002 13:16:28 GMT
Subject: Copy with __slots__
References: 
Message-ID: 

Griebel, Peer wrote [I'm only leaving the relevant parts of the script]:

> class C1(object):
>     __slots__ = "s1";
> 
> class C2(C1):
>     __slots__ = "s2";

Funny use of semicolons here.  I'd suggest omitting them!

> o2 = C2()
> 
> import copy
> p2 = copy.copy(o2)
> print p2.s2           # attribute s2 does not exist (has not been copied)
> 
> The last print statement fails with the an AttributeError. Since

Traceback (most recent call last):
  File "sloco.py", line 25, in ?
    p2 = copy.copy(o2)
  File "/usr/local/lib/python2.2/copy.py", line 84, in copy
    y = _reconstruct(x, reductor(), 0)
  File "/usr/local/lib/python2.2/copy_reg.py", line 68, in _reduce
    dict = getstate()
TypeError: a class that defines __slots__ without defining __getstate__ 
cannot be pickled

This is with Python 2.2.1 -- as you see, it doesn't get anywhere
as far as the print statement.  The error message is somewhat
peculiar (who's trying to _pickle_ anything...?) -- and if you
do try to define __getstate__ (and possibly __setstate__), you'll
see they're no use for copy.copy (nor copy.deepcopy).  _reconstruct
gets in the way.

If you only care about copy.copy, the simplest alternative is:

class C2(C1):
    __slots__ = "s2"
    def __copy__(self):
        x = self.__class__()
        x.s1 = self.s1
        x.s2 = self.s2
        return x

You can of course also add try/except AttributeError around each of the 
assignments "x.sN = self.sN", if you want to let an instance of C2 be 
copied even when one or both of its attributes are not yet defined.
For deepcopy, you could use a similar special method __deepcopy__ (needs
to deepcopy the attributes, of course).

The way to cover copy.copy, copy.deepcopy AND pickle is to have the
class supply a special method __reduce__.  __reduce__ can return a
pair where the first item is callable, the second item is the tuple
to pass as arguments to the first.  Thus, for example:

class C2(C1):
    __slots__ = "s2"
    def _build(s1, s2):
        x = C2()
        x.s1 = s1
        x.s2 = s2
        return x
    _build = staticmethod(_build)
    def __reduce__(self):
        return C2._build, (self.s1, self.s2)

Here, _build need not worry about deep-copying -- if needed, it's
been performed previously, on the args _build gets passed.


The nicest thing about it is that a class with slots will often
already supply some nice function to build instances of the class
given values to put in the slots -- you don't necessarily have
to write factory functions such as _build just for the purpose
of supporting copy, deepcopy and pickle... you often have them
lying around!-).  For example, a more typical case might be:

class C2(C1):
    __slots__ = 's2'
    def __init__(self, s1=None, s2=None):
        C1.__init__(self, s1)
        self.s2 = s2
    def __reduce__(self):
        return self.__class__, (self.s1, self.s2)

Here I'm assuming C1 has a similar __init__, but that's a detail.
The point is that __reduce__ can use class C2 itself as the
first item of its result -- the class IS callable, after all.

I'm specifically using self.__class__ rather than a literal C2
here as a tiny enhancement -- if a class C3 subclasses C2 and
does not override __init__ in a way that requires arguments
different from the slots' values, then C3 need not override
__reduce__ either -- it can just inherit it from C2.  Not the
end of the world, but sometimes handy.


Alex



From max at alcyone.com  Wed Sep 25 18:43:06 2002
From: max at alcyone.com (Erik Max Francis)
Date: Wed, 25 Sep 2002 15:43:06 -0700
Subject: a python puzzle
References: 
Message-ID: <3D923BFA.B42928F6@alcyone.com>

Michal Wallace wrote:

> Here's a python puzzle. Solve it and you win a prize. :)

tr hokdrafwfezxtculyjqmbipsvHIFg importsysngadfzjehulvcwbxICSk

I started by decoding the (obvious) Python source, which made the job
considerably easier.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Seriousness is the only refuge of the shallow.
\__/ Oscar Wilde
    Church / http://www.alcyone.com/pyos/church/
 A lambda calculus explorer in Python.


From use-net at schabi.de  Wed Sep 18 16:24:21 2002
From: use-net at schabi.de (Markus Schaber)
Date: Wed, 18 Sep 2002 22:24:21 +0200
Subject: Remarks to Python 2.3
Message-ID: <20020918222421.328088eb.use-net@schabi.de>

Hello,

I studied http://python.org/dev/doc/devel/whatsnew/contents.html and was
very impressed - you manage to get python even more fascinating with
every release.

I especially like enumerate() and Bool.

But I have some remarks:

- Mutable sets support some in-place operations - should those, just as
the in place operations on lists, like sort(), return None instead of
the new list to make clear that they are in place operations and for the
sake of consistency?

- When replacing list elements using the extended slice syntax - e. G.
in a[::2] = range(0, -2, -1) - the left side must have exactly the same
numer of elements as the right side. So, to cite the example, a[::2] =
range(3) is illegal for a=[0, 1, -1, 3]. 

Now I could image that it makes sense to allow one single additional
element to be added to the list in case only the step is specified and
the operation doesn't produce a gap. So the given example above would be
valid, giving a sequence of five elements, whereas with a=[0, 1, 2] it
would stay illegal (as it would produce a gap). a[0:3:2]=range(3) would
stay illegal as it explicitly specifies the length of the range,
a[0:3:5]=range(3) could be allowed.

Thanks,
Markus

-- 
Schabi's Flohmarkt: http://www.uni-ulm.de/~s_mschab/flohmarkt/

"XML combines all the inefficiency of text-based formats with most of
the unreadability of binary formats :-)" - Oren Tirosh


From gerhard.haering at opus-gmbh.net  Wed Sep 18 14:13:01 2002
From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: 18 Sep 2002 18:13:01 GMT
Subject: isFloat: Without Exception-Handling
References:   <%82i9.1366$bh1.943@fe03> 
Message-ID: 

Rajarshi Guha wrote:
>>> def isFloat(string):
>>>   if type(string) == type(1.0):
>>>     return 1
>>>   else
>>>     return 0
>>>
>>> This should do what you want without exceptions
>
> If you call it as isFloat(1.2) it works

It answers no interesting question, however. Cos if I want to test if something
is a float or not i use type() or isinstance() anyway.

The original question was how to test if a /string/ can be converted to a
float.

-- Gerhard


From bokr at oz.net  Wed Sep  4 20:51:03 2002
From: bokr at oz.net (Bengt Richter)
Date: 5 Sep 2002 00:51:03 GMT
Subject: Memory fault - core dumped   while compiling python 2.2.1 on  SCO
References: <3D757EFA.9050401@nospam.yahoo.com>   <3D765A05.6030004@nospam.yahoo.com>  <3D768753.8030302@nospam.yahoo.com>  <3D76A139.1030304@nospam.yahoo.com>
Message-ID: 

On Wed, 04 Sep 2002 17:11:37 -0700, Anton Graph  wrote:

>Martin v. Loewis wrote:
>> Anton Graph  writes:
>> 
>> - What is the precise version of the operating system you are using?
>> 
>
>SCO_SV bongo 3.2 5.0.5 i386
>
>> - I'm troubled by the fact that in both configurations (with an
>>   without gcc), the compiler is always referred-to as "cc". Are you
>>   sure you are not using gcc?
>> 
>I'm positive it's SCO cc:
>
>Wed Sep  4 16:17:04 PDT 2002 bongo:/u/src/agl/txb/txt $ gcc -v
>Reading specs from /usr/local/lib/gcc-lib/i386-pc-sco3.2v5.0.5/2.95.2/specs
>gcc version 2.95.2 19991024 (release)
>Wed Sep  4 16:17:07 PDT 2002 bongo:/u/src/agl/txb/txt $ /usr/local/bin/cc
>bash: /usr/local/bin/cc: No such file or directory
>Wed Sep  4 16:17:14 PDT 2002 bongo:/u/src/agl/txb/txt $ /usr/bin/cc
>Usage: cc [ options ] files ...
>Wed Sep  4 16:17:18 PDT 2002 bongo:/u/src/agl/txb/txt $ /bin/cc
>Usage: cc [ options ] files ...
>
How about
    cc -v
?

what does

    which cc

give you? And

    which cc | xargs -ld
?


Regards,
Bengt Richter


From tundra at tundraware.com  Wed Sep  4 18:15:07 2002
From: tundra at tundraware.com (Tim Daneliuk)
Date: 04 Sep 2002 22:15:07 GMT
Subject: [ANN] 'abck'  2.2 Intrusion Reporting System Released
Message-ID: <3D768506.50200@tundraware.com>

'abck' 2.2 is released at:

     http://www.tundraware.com/Software/abck/

Several new and nifty features/options since the last release (1.99).

'abck' is a Python program designed to manage attack attempts on your Unix
machine.  It examines the contents of /var/log/messages for evidence
of an intrusion attempt.  When it finds such a record, it helps you
determine the source and allows you to send email to the system
administrator in the responsible domain.

'abck' was written for and tested on FreeBSD 4.6R, but it should be
easily adapted to Linux or one of the other *nix platforms.

Upgrade to the FreeBSD port has also been submitted.
-- 
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com



From gerhard.haering at gmx.de  Sat Sep  7 09:35:26 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: 7 Sep 2002 13:35:26 GMT
Subject: Python, CGI, MySQL -> 'Error 2004: Can't create TCP/IP socket (10106)'
References: 
Message-ID: 

Doru-Catalin Togea wrote in comp.lang.python:
> I am using Python 2.2 on a win 2000 Pro computer to interact with
> mysql, by means of the MySQLdb module. My non-CGI scripts work as
> expected. 
> 
> I have now installed a webserver (Savant 3.1) am I try to connect to
> mysql by means of CGI and still MySQLdb. My scripts fail now with
> the 'Error 2004: Can't create TCP/IP socket (10106)' error message.

> Anyone who can recommand a free webserver which interacts well with
> MySQL by means of pythonic CGI scripts on Win 2000 Pro?

There's nothing special about MySQL, but I can recommend Apache, even
on Windows.

> [...] These functions work when the script connects to the
> mysql-server directly, but fail when a webserver is in between.

Just guessing: Maybe you're using IIS and the CGI scripts don't have
the privilege to create sockets?

-- Gerhard


From marklists at mceahern.com  Mon Sep 23 17:38:11 2002
From: marklists at mceahern.com (Mark McEahern)
Date: Mon, 23 Sep 2002 16:38:11 -0500
Subject: Elementary confusion
In-Reply-To: <878z1s1kqf.fsf@smtp.blueyonder.co.uk>
Message-ID: 

[Keith]
> I am working through O'Reilly's "Learning Python". I am up to page 33,
> and already I have a problem. The text outlines a cli entry about math
> operators, all really straight forward;
>
> .>>>a=3
> .>>>b=4
> .>>>b/2+a
>  5
> .>>>b/(2.0+a)
>  0.8
>
> This is so straight forward that I wasn't going to type it in, but I
> did anyway, and got instead of '0.8' something I cannot account for. I
> got '0.80000000000000004'.
>
> So after 32 pages, I am already flumoxed. What is going on

This is a FAQ.  Please read the FAQ.  This has to do with floating point
math:

  http://www.python.org/doc/FAQ.html#4.98

// mark




From sismex01 at hebmex.com  Fri Sep 27 10:41:33 2002
From: sismex01 at hebmex.com (sismex01 at hebmex.com)
Date: Fri, 27 Sep 2002 09:41:33 -0500
Subject: Python Process that can survive
Message-ID: 

> From: peeryc at hotmail.com [mailto:peeryc at hotmail.com]
> 
> Alright... I love python but I think I may have found a definite
> problem. I can't seem to run a python process, kick it to the
> back-ground, and then kill the terminal that started it. With most
> other things, the python process would keep running in the
> back-ground regardless. For me, the process always dies with the
> terminal.
> 
> So my question: is there a way to separate a python script from the
> underlying terminal so that this will not happen.
> 
> I'm hoping for some scheme that's supported by the language. I've
> found a few hacks on-line where the python process is daemonized
> but this requires shutting down all the standard io streams.
> There's got to be a better way especially since it can be done in
> Perl very easily with no special tricks.
> 
> By the way, I'm doing this on a linux box.
> 
> Chris
> 

This same question I asked a few weeks ago, and got a few
answers back from lotsa nice peepl, so I pass this function
on to you for it's safekeeping (tag, your it ;-)

def Daemonize():
   "Detach the current process from the console."
   import os, sys
   if os.fork(): os._exit(0)

   # Close connection to current console.
   os.close(sys.__stdin__.fileno())
   os.close(sys.__stdout__.fileno())
   os.close(sys.__stderr__.fileno())

   # Reopen std handles to /dev/null.
   dev_null = os.open("/dev/null", 0)
   os.dup2(dev_null, 0)
   os.dup2(dev_null, 1)
   os.dup2(dev_null, 2)

   # Create new OS session.
   os.setsid()

   # Reset UMASK.
   os.umask(0)

   # Refork to have init as parent.
   if os.fork(): os._exit(0)


This is a synthesis of several replies I received, and it
seems to work, but others might have some observations
to make to this little function.

HTH!

-gustavo










Advertencia: 
La informacion contenida en este mensaje es confidencial y restringida y
esta destinada unicamente para el uso de la persona arriba indicada, Esta
comunicacion representa la opinion personal del remitente y no refleja
necesariamente la opinion de la Compa?ia. Se le notifica que esta
estrictamente prohibida cualquier difusion, distribucion o copia de este
mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error,
o si hay problemas en la transmision, favor de comunicarse con el remitente.


Todo el correo electr?nico enviado para o desde esta direcci?n ser?
procesado por el sistema de correo corporativo de HEB. Tal correo
electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien
ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan
las normas de seguridad de la empresa.



From pinard at iro.umontreal.ca  Tue Sep  3 15:41:10 2002
From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard)
Date: Tue, 03 Sep 2002 15:41:10 -0400
Subject: Servizi Internet
In-Reply-To:  (Gerhard
 =?iso-8859-1?q?H=E4ring's?= message of "3 Sep 2002 16:59:40 GMT")
References: 
	<3bl9nu8924gihfj2nlpog874vfm73qqbh9@4ax.com>
	
Message-ID: 

[Gerhard H?ring]

> The only means you have is complain to their ISP (abuse@{name_of_ISP}).

This is rather discouraging, you know.

Most ISP around here, and especially the big ones, could not care any less.
Thinking about it, some international providers are not fully pink either.
They are far more interested into protecting the anonymity of those from which
they receive money.  Aren't they in business, after all?

They will almost never take action unless forced to do so by police
intelligence services, and such services are so horribly heavy or slow to get
in motion that it is almost a lost cause as far as practice is concerned.

Police people affected to computer crimes told me that they are severely
understaffed, and fully overwhelmed by requests emanating from big banks or
military agencies, which are to be served in priority.  Moreover, in far too
many cases, they have youth protection law in their way.

We pay all the way.  Spammers use our network connectivity, our CPUs, our
disks and our own time for bothering us; they misredirect rejects so companies
pay postmasters or sysadmin services to handle their crap; and everybody
invest effort and energies trying to escape the constant annoyance.  While
politicians, from their ivory towers, discourse on the virtues of Free Speech!

-- 
Fran?ois Pinard   http://www.iro.umontreal.ca/~pinard



From branded at sendme.cz  Thu Sep 19 08:08:32 2002
From: branded at sendme.cz (A)
Date: Thu, 19 Sep 2002 14:08:32 +0200
Subject: Is there a widget or program  for a database browsing
Message-ID: <3D89DA60.8878.8D30C74@localhost>

Hi,
In my program users will search  a database and I need to display choosen
record(s ) in a nice graphical way. Is there a module( program), that I could use together 
with Python, that  could easily  show the database record(s) and take care of all thinks 
during browsing? Thanks for help.
 Ladislav





From cbbrowne at acm.org  Thu Sep  5 11:33:24 2002
From: cbbrowne at acm.org (Christopher Browne)
Date: 5 Sep 2002 15:33:24 GMT
Subject: Graham's spam filter
References:  <3D647B4B.28D9BF04@alcyone.com>  <3D655AE6.A097AA25@alcyone.com>   <3D770156.2E55864C@alcyone.com>
Message-ID: 

Centuries ago, Nostradamus foresaw when Erik Max Francis  would write:
> Aaron Swartz wrote:
>
>> I've been using bogofilter[1], Eric Raymond's Graham-derived spam
>> filter which threw away base64-encoded data and 90% of all spam that
>> got past the filter was base64-encoded. Therefore, I think that base64
>> content really needs to be decoded. I wrote a base64-decoding filter
>> in Python for it and the problem has gone away.
>
> Indeed.  I've been finding very much the same thing with my rule-based
> filter; about 90% of the spam that's getting through is base64 encoded. 
> I haven't yet taken the next step of automatically decoding the base64
> text parts (and then just processing that), but as you have discovered
> it is an obvious solution to the obvious problem.

Have you considered simply replacing strings that appear to be
base64-encoded with a token like "base64-text"?

That allows the database to at least be aware that the spam commonly
contains base64 data.

-> Supposing there is interesting text encoded (such as source code
   for a virus) inside the base64 stuff, it _would_ be useful to
   decode it; 

-> Supposing the base64 stuff is basically just a GIF/JPEG/PNG, or
   something else that doesn't contain "interesting text," you'll
   have not much of value from the decoding process.

Making the "tokenizing" step a tad smarter (e.g. - recognizing "this
is likely base 64" and collecting stats on numbers of lines of base64
material) requires minimal added effort, and I expect it would buy you
_most_ of the benefits of decoding.
-- 
(concatenate 'string "chris" "@cbbrowne.com")
http://cbbrowne.com/info/linux.html
Let me control a planet's oxygen supply and I don't care who makes the
laws.


From d_blade8 at hotmail.com  Fri Sep 27 15:07:20 2002
From: d_blade8 at hotmail.com (Lemniscate)
Date: 27 Sep 2002 12:07:20 -0700
Subject: Silly question about ungzipping a file
References: <7396d2b2.0209261311.1fdd2d3a@posting.google.com> 
Message-ID: <7396d2b2.0209271107.2e3bfd21@posting.google.com>

Wow, thanks a bunch.  Let me just say that this did the trick with
flying colors.  Of course, now I have to go buy FL's book (my wife was
giving me grief but now I have an excellent argument in my cause). 
Thanks a bunch,
Lem


Alex Martelli  wrote in message news:...
> Lemniscate wrote:
>         ...
> >>>> import gzip
> >>>> myFile = gzip.open('LL_tmpl.gz')
> >>>> file('output.txt', 'w').write(myFile.read())
> >>>> 
> > 
> > Now, is there any way to do this so that less memory is used?  I mean,
> 
> import shutil
> shutil.copyfileobj(myFile, open('output.txt', 'w'))
> 
> > 129MB.  I'm sure I'm just missing something simple, but why is that?
> 
> I think the reason you're missing this simple something is that you
> are not entirely familiar with Python's rich standard library -- a
> defect common to us all (I don't recall _every_ useful module either:-).
> 
> A partial help is /F's "Python Standard Library" (O'Reilly) -- it
> won't magically infuse you with knowledge of every such module, but
> by giving at least one example script for each module in the
> library (all in a remarkably concise 280 pages!) it makes it quite
> a bit more likely that more modules will stay in your subconscious
> memory.  Python's online reference, Beazley's New Riders book, my
> Nutshell when it comes (the delay ain't my fault THIS time - the
> complete, technically-revised draft is currently in the editor's
> hands!-), each give a different perspective on Python's standard
> library, and enhance the likelihood that you'll know where to find
> excellent code ripe for reuse.  Probably the best single piece of
> advice is the one in the Python online docs -- "sleep with the
> Library Reference under your pillow" (and use a thin pillow, so that
> the knowledge has an easier time filtering up into your brain:-).
> 
> 
> Alex


From gmuller at worldonline.nl  Sat Sep  7 05:20:03 2002
From: gmuller at worldonline.nl (GerritM)
Date: Sat, 7 Sep 2002 11:20:03 +0200
Subject: Thinking in Tkinter
References: 
Message-ID: 

"Stephen Ferg"  schreef in bericht
news:b16e4ef7.0209062009.26e218e2 at posting.google.com...
> A small page devoted to "Thinking in Tkinter"
> at http://www.ferg.org/thinking_in_tkinter/index.html
> for whoever might find it useful.
>
<...snip...>
I enjoyed reading it! Good work.

regards Gerrit
--
www.extra.research.philips.com/natlab/sysarch/





From anthony_barker at hotmail.com  Wed Sep  4 10:17:02 2002
From: anthony_barker at hotmail.com (Anthony_Barker)
Date: 4 Sep 2002 07:17:02 -0700
Subject: Python critical mass /turning point
Message-ID: <899f842.0209040617.711664fe@posting.google.com>

I have been trying to determine what is holding python back from 
reaching the critical mass/success that perl/c++/Java have experienced.
Caveate - I am not a python guru - so some of the technical stuff may be wrong.

I believe most of the issues are not technical - If technical features were 
key to critical mass then LISP would be the main programming 
language.

1. Interpreter Available on every desktop/server
Perl has this on the server
Java had this in the browser space

Solution(s)
Parrot/Perl6 integration - the if python is included
with the perl interpreter it would be everywhere
Lobby Sun & IBM to include Python on their Unix CDs
Lobby Microsoft to get added to their resource kit
Other options are already available such as freeze....

2. Suitability for commercial products
A couple of the problems I believe are technical and
reputation.
1) Speed issue compared when compared with c/c++
2) The ability to enforce interfaces
Allow enforced type checking and encapsulation - people are often
surprised when they find out data is hidden in python.
3) Access c libraries/apis seamlessly

Solutions(s)
Speed issue I believe may be solved by psycho, and time. As python
matures it seems to be getting faster, while computers are getting
so fast speed matters less.

Having a compiler would allow python to be know not only as a 
scripting language. Unfortunately "scripting language" for some
is equivalent to - not a real language. Enforced interfaces
and the ability to enforce data hiding

SWIG is doing a good job with the last issue.


3) Big corporate sponsor(s)
IBM sponsors Java/Perl/C/C++ & Cobalt 
by having IDEs and corporate support available for those languages.

IBM supports PERL?
Surprise - Tivoli products are glued together with Perl
Lotus Unix server products use perl under the hood
Perl is shipped on every AIX box
Perl courses are available as is support
etc

Microsoft Supports
VB/C/C++/c#/Java(kind of)/Perl etc

Perl is included in the NT/Win2K resource kits
Also is part of the tools for Unix

Sun
Java/Perl/etc

Perl is bundled with Solaris
Sun Solutions has Perl courses available


Cheers,

Anthony
http://xminc.com/anthony/


From franke at ableton.com  Tue Sep  3 08:41:13 2002
From: franke at ableton.com (Stefan Franke)
Date: Tue, 03 Sep 2002 14:41:13 +0200
Subject: Better tracebacks for exec and execfile
Message-ID: <3i99nusjbgpiepva9pkuv3mtl7equ7h88h@4ax.com>

1. I'm toying araound with a text templating engine containing
embedded Python scripts. These scripts are run with exec.
If they throw an exception, the traceback looks like

  File "", line 5
     e = a+c+b+
               ^
 SyntaxError: invalid syntax

Since the scripts are extracted from a bigger file, the filename
"" and line number are almost useless. Is there a way
to pass both to the interpreter and make them appear in
tracebacks?

2. If a command file passed to execfile throws an exception,
again the traceback looks like this:

  File "D:\Programme\Python22\del.py", line 7, in ?
    execfile(filename)
  File "", line 5
     e = a+c+b+
               ^
 SyntaxError: invalid syntax

Why isn't the filename shown instead of ""?




From fperez528 at yahoo.com  Sun Sep 29 19:41:29 2002
From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=)
Date: Sun, 29 Sep 2002 17:41:29 -0600
Subject: [Mac] Editor on Macintosh?
References: <1fj7za2.1erbqps1uvzpj8N%news@agapow.net> 
Message-ID: 

In article <1fj7za2.1erbqps1uvzpj8N%news at agapow.net>, news at agapow.net 
(Paul-Michael Agapow) wrote:

>Sadly, it seems like the excellent editor Pepper is going away. (See
>.) I found it the best editor for Python on
>the Macintosh, having never been really happy with the alternatives. 
>
>So what are other MacPython using? There are some Java-based editors,
>but I'm not persuaded that that they'll perform adequately. There's are
>numerous X11 based options, but who wants to swap into X everytime they
>need to edit a file? The once excellent editor Alpha seems to have
>disappeared permanently into testing for its next release.
>
>Ideas? Anyone? Bueller?

Well, now that the mac has a real operating system, you can use:
http://fink.sourceforge.net/pdb/search.php?s=emacs
http://fink.sourceforge.net/pdb/search.php?s=vim

or you can probabbly compile jed (http://space.mit.edu/~davis/jed/) in a 
minute if you want something a bit lighter than emacs but with the same 
overall feel.

All three fantastic tools, powerful beyond anyone's needs and different enough 
that one of them hopefully will meet your tastes.

Since all three will run happily in a terminal, no need for X11.

Cheers,

f.


From yaipa at aol.com  Fri Sep 13 04:19:44 2002
From: yaipa at aol.com (yaipa)
Date: 13 Sep 2002 01:19:44 -0700
Subject: [Tutor] Paradox  table
References: 
Message-ID: <8d148763.0209130019.57fcef08@posting.google.com>

montana  wrote in message news:...
> Is there a good example on how to use a CSV parser in Python?
> So you have this comma seperated file, does the CSV parser break data 
> up into groups based upon where they are positioned in the file or does 
> it just generate a list of data or both?
> 
> Is there any good sites out there that deal with CSV parsing and python 
> that have some good examples or can someone on this list give some?
> 
> Thanks.
> 
> SA
> 
> "I can do everything on my Mac I used to do on my PC, plus alot more 
> ..."
> --Me
> 
> On Thursday, September 12, 2002, at 09:35 AM, Derrick 'dman' Hudson 
> wrote:
> 
> > On Wed, Sep 11, 2002 at 03:14:30PM +0200, A wrote:
> > | Hi,
> > |  Is there a module for reading Paradox database (.DB) files with 
>  Python?
> > | I need to run the script under Linux, so I can not use ODBC.
> > | Any suggestion would be appreciated
> >
> > One way to access the data is to export it from paradox in CSV format.
> > CSV is an open standard and several (python) parsers exist for it.
> > However, using this method won't allow you to easily access the data
> > from both paradox and from your script, instead you would need to
> > re-export it every time you modified it in paradox and you would not
> > be able to modify it using your script.  If you can, it would probably
> > be easiest to migrate to a different db such as postgresql.  Postgres
> > databases are much more accessible than paradox is (at least with the
> > paradox version I've seen, 3.5).
> >
> > -D
> >
> > -- 
> > Dishonest money dwindles away,
> > but he who gathers money little by little makes it grow.
> >         Proverbs 13:11
> >
> > http://dman.ddts.net/~dman/
> > 

Not sure if this is what you are looking for, but maybe this...

---  ---  ---  ---  ---  ---
#! /usr/local/bin/python

def cfgLstToLst(_cfgTags = [], tokenSeparator = None):
# Note: If tokens are separated by whitespace ONLY 
# (whitespace includes newlines)
# then leave tokenSeparator == None.


   _cfgTagList      = []

   for _i in _cfgTags:
      # split the string at the newline char(s)
      # while consuming the newline char
      #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      _cfgTagList = _cfgTags.split("\n")

      # Rejoin the list into one string w/o
      # newline char(s).
      #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      _cfgTags =  " ".join(_cfgTagList)

      # split the string once more and remove
      # the commas. Presto! We now have
      # a list of tags. We will strip the
      # whitespace from each element next.
      #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      if None:
         # do Nothing
         pass
      else:
         _cfgTagList = _cfgTags.split(tokenSeparator)
     
      
      # This is a List Comprehension.
      # The function of THIS list comprehension is to 
      # strip each list element of whitespace.
      #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      _cfgTagList = [item.strip() for item in _cfgTagList] 

      if _cfgTagList:
         # remove any empty list items, [''], we may have
         # picked up.
         _cfgTagList = [_x for _x in _cfgTagList if _x ]
         del _x

   return _cfgTagList

if __name__ == "__main__":
    
   # turn a string of comma seperated tokens
   # into a python list.

   data = "this, that, the, other,"

   print data

   print cfgLstToLst(data, ",")

---  ---  ---  ---  ---  ---

Viking1% cfgLstToLst.py

>> this, that, the, other,
>> ['this', 'that', 'the', 'other']

Viking1%


From just at xs4all.nl  Mon Sep  9 11:42:56 2002
From: just at xs4all.nl (Just)
Date: Mon, 09 Sep 2002 17:42:56 +0200
Subject: Windows/DOS: double clicking a .py file
References:  
Message-ID: 

In article ,
 "Thomas Heller"  wrote:

> "Just"  wrote in message 
> news:just-A936EC.17062909092002 at news1.xs4all.nl...
> > Sorry if this is a Windows FAQ, I'm a newbie to Windows, but not to
> > Python.
> >
> > If I double-click a Python script (or use the start command in the dos
> > prompt) a new dos prompt window is opened and my program is run. The
> > window goes away when the program is done. However, the window _also_
> > goes away when the program raises an exception, making it virtually
> > impossible to actually _see_ the exception... Is there a way to keep the
> > dos prompt window in this case?
> One solution is outlined here:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287
> This is useful for the development machine. It keeps the DOS window
> open, and leaves you in the Python debugger, where you can play around
> even more to find out about the state of your program.
> >
> > A py2exe-fied version of the program shows the same behavior, which
> > leads my users to report problems like "the output file is mysteriously
> > truncated" instead of "I'm getting a traceback. Here, have a look."...
> >
> > Any suggestions?
> 
> For py2exe-packages apps you should redirect sys.stdout and sys.stderr
> into a log-file.

Thanks for both suggestions. Another workaround just occured to me: do a 
raw_input("type enter to exit") in an exception hook. That should work 
just fine in a py2exe-fied app as well I suppose.

Just


From zopestoller at thomas-guettler.de  Wed Sep 18 11:41:47 2002
From: zopestoller at thomas-guettler.de (Thomas Guettler)
Date: Wed, 18 Sep 2002 17:41:47 +0200
Subject: isFloat: Without Exception-Handling
Message-ID: 

Hi!

Is there a way to write the following
method without using exceptions?

def isFloat(string):
     is_float=1
     try:
         float(string)
     except:
         is_float=0
     return is_float

print isFloat("asdf") # --> 0
print isFloat("0.1")  # --> 1

Somehow I don't like to catch exceptions. Maybe
that's because my first language was C.

  thomas



From bokr at oz.net  Thu Sep 26 19:55:52 2002
From: bokr at oz.net (Bengt Richter)
Date: 26 Sep 2002 23:55:52 GMT
Subject: e vs exp()?
References: <3a838998.0209191933.1f22e977@posting.google.com> 
Message-ID: 

On Thu, 19 Sep 2002 21:51:25 -0700, "James J. Besemer"  wrote:

>
>Buckshot wrote:
>
>>Can anyone here explain why I'm getting different results from
>>e**2 and exp(2)?  Which is more accurate?  
>>
>>Python 2.2 (#1, Mar 27 2002, 14:56:58)
>>[GCC 2.95.3 20010315 (release)] on sunos5
>>Type "help", "copyright", "credits" or "license" for more information.
>>  
>>
>>>>>from math import *
>>>>>e**2
>>>>>        
>>>>>
>>7.3890560989306522
>>  
>>
>>>>>exp(2)
>>>>>        
>>>>>
>>7.3890560989306504
>>  
>>
>Mathematica says e**2 to 30 digits is:
>
>    7.3890560989306502 272304274606
>
We can also brute force the series for e with longs and maybe ignore the last few digits:

 >>> def calce(nd):
 ...     numi = n = 10L**nd
 ...     deni = 1L
 ...     i = 0; s = ''
 ...     while 1:
 ...         i += 1
 ...         numi = numi*i + n
 ...         deni *= i
 ...         sl, s = s, str(numi/deni)
 ...         if sl[:nd+1] == s[:nd+1]: return numi, deni
 ...
 >>> n,d = calce(60)
 >>> n/d
 2718281828459045235360287471352662497757247093699959574966967L
 >>> (n/d)**2
 7389056098930650227230427460575007813180315570551847324087124...
Comparing side by side:
 7.3890560989306502 27230427460575007813180315570551847324087124...
vs
 7.3890560989306502 272304274606 from matlab
 7.3890560989306522              for e**2, and
 7.3890560989306504              for exp(2)

The latter seems more accurate.

>in which case the second form would happen to be more accurate.
>
>Since Python math uses your machine's native floating point formats, 
>precision is necessarily limited and one should not be surprised to 
>encounter minor errors in the least significant bits or digits.
>
>Although Mathematica recognizes that the two forms are identical, Python 
>uses different formula for computing the two results.  The fact that the 
>base is "e" is of no consequence to the computation.  exp() is computed 
>from C's exp() runtime library routine, whereas e**2 is evaluated using 
>C's "pow()" function.  
>
>In general, I would expect pow() to be less accurate, as pow(x,y) 
>probably is computed by exp(log(x)*y).
>
Looks plausible.

Regards,
Bengt Richter


From freddie at madcowdisease.org  Fri Sep 13 20:00:49 2002
From: freddie at madcowdisease.org (Freddie)
Date: Sat, 14 Sep 2002 00:00:49 GMT
Subject: Argh! Python 2.2 + threading + sockets = trouble
Message-ID: 

Hi,

I'm a fairly new Python programmer, but I've written a decent sized 
project (threaded IRC offer bot), and I wrote a threaded IPv6 capable 
IRC bouncer yesterday. Of course, it doesn't work quite as I expected.

MadCowOffer (offerbot) has rarely works properly with Python 2.2. It 
will sometimes manage to start all the threads, then it's fine, but it 
will usually just stop working after the IRC connection thread is started.

cowbounce (bouncer!) is almost the same. It will load fine, start the 
daemon sockets, wait for connections, etc etc. After a while (1 
connection, 3, it varies), the main thread also just stops doing 
anything. Some of the already connected BounceClient() threads will keep 
working, and some won't.

I have absolutely no idea what's causing this, or how to find out what 
exactly is making it unhappy :\


Using Python 2.2.1, from the Debian 'testing' packs python-2.2 2.2.1-6. 
Using 2.1.x isn't an option, as it doesn't seem to have working IPv6 
support.


Links to code:
   cowbounce   - http://www.madcowdisease.org/Files/cowbounce-broken.tar.gz

   MadCowOffer - http://www.madcowdisease.org/Files/MadCowOffer-0.1.2.tar.gz


Any help would be GREATLY appreciated :)

Freddie



From ruediger.maehl at web.de  Mon Sep  2 01:59:56 2002
From: ruediger.maehl at web.de (Rüdiger Mähl)
Date: 2 Sep 2002 05:59:56 GMT
Subject: Document Conversion and Python??
References: 
Message-ID: 

Derek Basch  wrote in 
news:mailman.1030594135.17322.python-list at python.org:

> Hello,
> Does anyone have any suggestions for tools for
> converting documents between different formats
> (html,pdf,tab delimeted, etc...)?

The docutils (docutils.sf.net/docs/rst/quickstart.html) 
might also be interesting for you.

R?diger


From printers at sendme.cz  Mon Sep 23 03:47:08 2002
From: printers at sendme.cz (A)
Date: Mon, 23 Sep 2002 09:47:08 +0200
Subject: How to call a procedure in exe file
Message-ID: <3D8EE31C.32426.219719@localhost>

Hi,
I know that it is possible to call a function in DLL library( even though I have never tried it) 
from Python but is it possible to call a procedure in an exe program?
I have a program that downloads some files( that was written in Delphi, we bought that 
program compiled already in exe).
I must start the program and then push a button that runs a procedure for downloading. 
And I must do it al the time when I want to download a file. So I am thinking about 
downloading automatically from Python. I can start the program
with os.startfile but I do know know how to start the procedure that is started when I push 
the button for downloading.(I may possiblly find address of the procedure
Can you please help?
Ladislav






From martin at v.loewis.de  Mon Sep 16 01:48:11 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 16 Sep 2002 07:48:11 +0200
Subject: Are generator functions thread-safe?
References: 
Message-ID: 

"Robert Oschler"  writes:

> I know that a call to a generator function actually returns an independent
> iterator object (mea culpa if I'm wrong on this), but are there any hidden
> gotchas that would cause the use of the same generator function from
> multiple threads, to result in a sharing (especially local storage) or
> memory collision issue?

Terminology is tricky here: If you call a function that is a
generator, you get a generator object. So it is not clear to me
whether you have the same function in multiple threads, or the same
generator object.

If you access the same generator object from multiple threads, they
clearly share state.

If you call the same generator function from multiple threads, you get
a new generator object each time. You also get a new set of local
variables for each invocation. There is no "hidden" shared state. So
yes, generator functions are thread-safe.

Regards,
Martin



From marklists at mceahern.com  Wed Sep  4 11:01:27 2002
From: marklists at mceahern.com (Mark McEahern)
Date: Wed, 4 Sep 2002 10:01:27 -0500
Subject: How to force built-in commands over imported.
In-Reply-To: <3D761C39.4020802@akst.tn.tudelft.nl>
Message-ID: 

[Maurice van de Rijzen]
> There is a built-in commans called open(fileName). There is also a
> open() command in the os-module open which needs more than the fileName.
>   Originally I didn't import the os-module and everything worked fine.
> However, when I imported the os-module I received an error that open
> needed more arguments. How can I force to take the built-in open()
> instead of the open() in the os-module.

How are you importing os.open?  If you do it like this:

  import os
  f1 = os.open(...)
  f2 = open(...)

you can keep the two open methods separate.  However, if you do it like
this:

  from os import open
  ...

you can't.  Unless you do this:

  from os import open as open_from_os
  ...

But then why would you do that?  ;-)

The idea here is namespaces.  Using 'from module import function' is not
recommended unless you know what you're doing.

Also, for what it's worth, you may want to consider using:

  f = file(...)

instead of:

  f = open(...)

since the method name matches the type:

  >>> type(f)
  

// m

-




From mwh at python.net  Fri Sep 27 06:18:14 2002
From: mwh at python.net (Michael Hudson)
Date: Fri, 27 Sep 2002 10:18:14 GMT
Subject: SET_LINENO
References: <3D92A46E.2030706@cygnus-software.com>
Message-ID: 

I'm the one responsible for SET_LINENO going away in 2.3, so here's
my take...

Bruce Dawson  writes:

> Executive summary: Has the SET_LINENO removal been tested with the HAP
> debugger, 

No.  I'd never heard of it for one thing!

> and wouldn't a breakpoint instruction give much larger
> benefits?

I fail to see how.

> As a partial author of the HAP Python Debugger (available on source
> forge) I read about the imminent removal of SET_LINENO with some
> worry. It *sounds* like it has been done in such way to not cause
> debugger problems, but I'm curious if anyone has tested HAP with 2.3.

I tried really hard to make it transparent to debuggers.  There are a
few very small differences, but unless you're actually scanning for
SET_LINENO instructions they shouldn't bite.  I'd invite you to test,
of course.

> Also, it sounds like the reason for removing SET_LINENO was to improve
> the performance of Python scripts. However one of the posts on this
> topic (can't find it now) suggested that the hoped for improvements
> had not actually materialized.

It speeds programs run without -O.  On Windows, programs run with -O
got somewhat slower after this patch (on Linux it made essentially no
difference, maybe a very slight speedup).  See Tim's post.

> It seems to me (from the sidelines/peanut gallery/wherever) that the
> biggest performance problems in the SET_LINENO area are when
> debugging, not when running free, and that therefore this optimization
> is targeting the lesser problem.

You've got my motivation entirely backwards there.

> The need to check for breakpoints at each line has always made Python
> debugging performance poor at best. Technically the performance under
> the debugger doesn't matter, and yet sometimes it does. Having just
> helped complete a Python based sports game for PC, where real-time
> performance was critical, I can say that the slowdown in HAP was
> definitely annoying.

You're faced with a hard problem.  Good luck :)

> So, wouldn't a break-point opcode be a more substantial improvement
> than removing SET_LINENO? Just bringing up that old topic again to see
> if it gets any more traction :-)

How would a breakpoint opcode differ from what SET_LINENO was?

> P.S. For reference I include the canonical? link to the SET_LINENO
> discussion.
> 
> http://mail.python.org/pipermail/python-dev/2000-July/007652.html

Note that what I did bears little resemblance to the scheme sketched
in that post.  I hack stuff out of co_lnotab.

> P.P.S. A breakpoint instruction would also be a boon for asserts - I'd
> love to be able to stop on the assert when running under a debugger,
> to see what is wrong before the stack frame unwinds.

Well, you break on the exception, don't you?

Cheers,
M.

-- 
  The "of course, while I have no problem with this at all, it's
  surely too much for a lesser being" flavor of argument always
  rings hollow to me.                       -- Tim Peters, 29 Apr 1998


From joconnor at cybermesa.com  Tue Sep  3 09:58:13 2002
From: joconnor at cybermesa.com (Jay O'Connor)
Date: Tue, 03 Sep 2002 13:58:13 GMT
Subject: code doesn't work: question
References: <1551859543.20020903130305@is.lg.ua> 
Message-ID: <3d74bdc4.281693@news.cybermesa.com>

On 03 Sep 2002 12:28:59 +0200, Geert-Jan Van den Bogaerde
 wrote:

>Python doesn't allow assignment inside expressions, the rationale (from
>the Python tutorial at http://www.python.org/doc/current/tut/node7.html
>- section 5.5 last sentence): 
>
>"""
>Note that in Python, unlike C, assignment cannot occur inside
>expressions. C programmers may grumble about this, but it avoids a
>common class of problems encountered in C programs: typing = in an
>expression when == was intended. 
>"""
>
>Given the number of times I've personally made this mistake, I'd agree
>with Python's rationale for leaving this out.


This is really only a problem in a language that doesn't really have a
boolean data type and then allows boolean evaluation of non-boolean
objects (such as C with numbers and pointers and Python with..almost
everything :)

Smalltalk allows assignment within an expression, but does not suffer
from the "I meant == and accidentally typed =" problem because
Smalltalk has a first class Boolean class and does not allow boolean
comparisons for non-boolean objects

(x :=y) ifTrue: [
	"blah"
]

Only works if y is already a Boolean; if it's an Integer, the ifTrue:
message raises an error, so 

((x := y) == 5) ifTrue: [

]

is perfectly ok, and much safer than the equivalent C


Take care,
Jay
Jay O'Connor
joconnor at cybermesa.com
http://www.cybermesa.com/~joconnor


"God himself plays on the bass strings first, when he tunes the soul"


From spam at ob_scure.dk  Sat Sep  7 10:55:21 2002
From: spam at ob_scure.dk (Thomas Jensen)
Date: Sat, 07 Sep 2002 16:55:21 +0200
Subject: Using Python to call a DCOM server - "'Class not registered"
References: <3D787D95.9000907@ob_scure.dk> <5%ce9.1272$_l1.2960@news-server.bigpond.net.au>
Message-ID: <3D7A1359.4010607@ob_scure.dk>

Mark Hammond wrote:
> Thomas Jensen wrote:

[snip - example of not working DCOM]

> Are you sure that the COM object you are using is correctly registered 
> for use as a DCOM server.  The code above insists that the COM object be 
> registered as LocalServer - ie, other than just InprocServer32.

I fought with this 'till 5 AM this morning (0300 CET) and finally got it 
working.
You are absolutely right! The components are made in VB6 (NOT my 
prefered language, but hey - I gotta make a living :-). I don't really 
know very much about the technicalities of COM (or DCOM for that 
matter), but when I saw how simple the testDCOM.py script was, I thought 
I'd give it a try :-)
I don't really know what the relation between an InprocServer32 and a 
LocalServer is, but I somehow figured out, that by changing the project 
type from "ActiveX DLL" to "ActiveX EXE", the component showed up in 
dcomcnfg.exe allowing me to finally get it working!

Now I just need to figure out how to unregister this new .EXE beast 
("regsvr32 /u" doesn't seem to work).

Is it safe to say that "ActiveX DLL" = InprocServer32 and "ActiveX EXE" 
= LocalServer and that I need the later to use DCOM? (I have some 
existing components that I'd rather keep as DLL - don't know why really? :-)

Anyhow, thanks alot for the reply and not least	for the great win32 package!


-- 
Best Regards
Thomas Jensen
(remove underscore in email address to mail me)



From jb at cascade-sys.com  Fri Sep 13 01:42:33 2002
From: jb at cascade-sys.com (James J. Besemer)
Date: Thu, 12 Sep 2002 22:42:33 -0700
Subject: function pointer
References:   
Message-ID: <3D817AC9.4020302@cascade-sys.com>

Gerhard H?ring wrote:

>Broken quoting - yuck! Your newsreader is broken. Please repair it (using
>third party software) or make Usenet a better place by throwing away that
>crapware.
>

I believe this error occured when the line was wrapped by the 
python-list mailer, not necessarily the submitter's newsreader or email 
program.

>If we want to keep the terminology right, Python doesn't have variables. It
>has names and values. 
>

The fact that The Tutorial and other Python doc uses the term "variable" 
makes it confusing for newcomers.

It's doubly confusing, since the general definitions of a variable seems 
to apply equally well to the corresponding Python thingies.

    http://www.webopedia.com/TERM/V/variable.html

    http://www.techweb.com/encyclopedia/defineterm?term=variable

So, what is the difference between a "name" and a "variable"?  

Or is this merely a distinction without a difference?

Regards

--jb

-- 
James J. Besemer		503-280-0838 voice
2727 NE Skidmore St.		503-280-0375 fax
Portland, Oregon 97211-6557	mailto:jb at cascade-sys.com
				http://cascade-sys.com	







From tdelaney at avaya.com  Wed Sep 25 19:36:18 2002
From: tdelaney at avaya.com (Delaney, Timothy)
Date: Thu, 26 Sep 2002 09:36:18 +1000
Subject: comparing all values of a list to regex
Message-ID: 

> From: Alex Martelli [mailto:aleax at aleax.it]
> 
> num_matches = [ there.match(item) is not None for item in 
> alist ].count(1)
> 
> if num_matches == 0:
>     againanothernewlist.append(alist)
> elif num_matches == 1:
>     anothetnewlist.append(alist)
> elif num_matches == len(alist):
>     anewlist.append(alist)

I would actually prefer to do this another way.

match_all = []
match_one = []
match_some = []
match_none = []

# Expanded out for clarity - could be one line
matches = map(regexp.match, alist)
matches = filter(None, matches)
matches = len(matches)

# Find out which list to append to

match_list = match_all

if not matches:
    match_list = match_none
elif matches == 1:
    match_list = match_one
elif matches != len(alist):
    match_list = match_some

match_list.append(alist)

Note that I added an additional case - where more than one matched, but not
all.

Tim Delaney



From gua81 at XXXyahoo.com  Thu Sep 26 04:29:54 2002
From: gua81 at XXXyahoo.com (CheapSkate)
Date: Thu, 26 Sep 2002 18:29:54 +1000
Subject: IGNORE ABOVE POST!
References: 
Message-ID: 

Sorry,
my mistake...
my web server took a while o refresh itself.

"CheapSkate"  wrote in message
news:amug6m$ivm$1 at lust.ihug.co.nz...
> This thing worked before.... I dont know why it didn't work now.
>
> this code is in the other page with the link:
> '%s'% (dirname, filename, filename)
>
> This code is the one that crash:
> all_values=cgi.FieldStorage()
> kkk=all_values["link"].value
> start_parse(kkk)
>
> when I run it, it gives this error:
> Traceback (most recent call last):
>   File "parser.cgi", line 53, in ?
>     direc=all_values["link"].value
>   File "/usr/local/lib/python2.1/cgi.py", line 550, in __getitem__
>     raise KeyError, key
> KeyError: link
>
>




From maurice at akst.tn.tudelft.nl  Wed Sep  4 10:44:09 2002
From: maurice at akst.tn.tudelft.nl (Maurice van de Rijzen)
Date: Wed, 04 Sep 2002 16:44:09 +0200
Subject: How to force built-in commands over imported.
Message-ID: <3D761C39.4020802@akst.tn.tudelft.nl>

Dear all.
I'm a newbie on the field of python, therefore the answer to my question 
may be simple.
There is a built-in commans called open(fileName). There is also a 
open() command in the os-module open which needs more than the fileName. 
  Originally I didn't import the os-module and everything worked fine. 
However, when I imported the os-module I received an error that open 
needed more arguments. How can I force to take the built-in open() 
instead of the open() in the os-module.

Gr,
Maurice



From codic at stasis.org  Wed Sep 11 16:11:48 2002
From: codic at stasis.org (Ian Crawford)
Date: 11 Sep 2002 13:11:48 -0700
Subject: Global Interpreter Lock
Message-ID: <3822aca1.0209111211.8a1538f@posting.google.com>

Hi everyone,
    I'm working on a project with an embedded Python
interpreter which I'd like to be capable of parallel
execution on a multi-processor machine.  I'm still
trying to figure out one thing in particular.  Is
there a global interpreter lock per interpreter (i.e.
if I call Py_NewInterpreter, does that interpreter
have it's own lock), or will I have to embed seperate
interpreters in their own processes to have parallel
execution?

Thanks,

Andrew


From itsmikeytime at hotmail.com  Mon Sep  9 11:22:01 2002
From: itsmikeytime at hotmail.com (Mikey at Work)
Date: Mon, 9 Sep 2002 11:22:01 -0400
Subject: Possible bug in WxPython
References: <9ff6b66.0209090557.3c0e3c94@posting.google.com>
Message-ID: 

"vtail"  wrote in message
news:9ff6b66.0209090557.3c0e3c94 at posting.google.com...
> Greetings.
>
> When trying to run an example program from wxWiKi
> http://wiki.wxpython.org/index.cgi/Getting_20Started, section 7.1.2, I
> encounter following error. Could someone please explain it to me?
> I've attached the error message and the program that causes it.
>
> O:\_PUBLIC\Newdbase\Python\wxPython>python test4.pyw > aaa.txt
> 17:52:59: Debug: c:\Projects\wx\src\msw\app.cpp(542):
> 'UnregisterClass(no redraw
>  canvas)' failed with error 0x00000584 (class still has open
> windows.).

I had the exact same problem this morning.  I got around it by adding:

app.MainLoop()

at the end of the program.  It solved my problems.





From cbbrowne at acm.org  Mon Sep 23 10:20:37 2002
From: cbbrowne at acm.org (Christopher Browne)
Date: 23 Sep 2002 14:20:37 GMT
Subject: WSDL for XML-RPC ??
References: <_YAj9.21316$0p1.377838@news2.ulv.nextra.no>
Message-ID: 

"Thomas Weholt" <2002 at weholt.org> wrote:
> SOAP has WSDL to describe a webservice. Doeas XML-RPC have something
> similar?
> Is WDDX the right way to go or have I totally missed the point?
>
> Ref :
> http://www.wddx.org
> http://www.openwddx.org/

The express intent of XML-RPC is to provide a fairly /minimal/ set of
useful functionality.

Contrast with SOAP, where it's kind of "expressly indicated" that
there will be some nebulous set of "extended standards," where it is
supremely unlikely that anyone would actually be able to implement
them all at once.

The result, with SOAP, is that there's something of a "dog's
breakfast" of implementations, where they may assortedly trumpet:
  "WSDL is supported!"
  "UDDI is supported!"
  "We support 8 alternative transport methods!" (SOAP::Lite for Perl)
  "We support these bits of WSSecurity!"

And every implementation is free (and likely) to choose different bits
to support.  They'll probably /try/ to support WSDL (though support
for that in scripting languages like Perl/Python/Ruby is spotty, at
best); they /might/ support UDDI; other stuff scatters all over the
map, likely only being implemented by Big Vendors...

XML-RPC takes a vastly less ambitious road, not claiming any of that
sort of extensibility.  And so the standard fits on about two pages,
and most implementations provide pretty much complete coverage of it.

There are three fairly common XML-RPC extensions:
"system.listMethods", "system.methodSignature", "system.methodHelp"

These are, in theory, able to provide some WSDL-like information,
albeit being vastly simpler, as XML-RPC eschews the use of XML Schemas
and has no support at all for the "complex schema" of SOAP.

It's not totally evident where WDDX fits in, except as a 'possibly
slightly more convenient way of transferring results of DBMS queries'
than SOAP/XML-RPC.  If you really need the differences between
SOAP/XML-RPC and WDDX< you're probably as well off setting up an XML
'schema' specifically for your application, and transferring around
data as XML documents whose generation and degeneration /you/ control.
-- 
(concatenate 'string "cbbrowne" "@acm.org")
http://cbbrowne.com/info/soap.html
"Starting a project in C/C++ is a premature optimization."
-- Peter Jensen


From gerhard.haering at gmx.de  Fri Sep 20 20:59:25 2002
From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: Sat, 21 Sep 2002 02:59:25 +0200
Subject: Python question on cgi
In-Reply-To: 
References: 
Message-ID: <20020921005924.GA3318@lilith.ghaering.test>

* Ken  [2002-09-21 10:41 +1000]:
> Hi all, how do I pass parameters to a backend C++ program and how do I know
> when does the C++ program ends so that I can read the output file produced
> by the C++ program and print to the HTML interface?

Check out the os.popen and/or the functions in the popen2 module. The
most simplistic example would be:

output_of_other_program = os.popen("/bin/ls /").read()

waiting-to-be-bashed-for-not-closing-the-stream-ly yours,

-- Gerhard



From ch_knievel at gmx.de  Sat Sep 21 12:13:29 2002
From: ch_knievel at gmx.de (christopher knievel)
Date: Sat, 21 Sep 2002 18:13:29 +0200
Subject: [newbie] mod_python apache w32
Message-ID: 

Hi all,
i got some problems running mod_python with apache under windows.
I am using python 2.2 and apache 1.3.26.
As written in the manual i configured httpd.conf like this:

LoadModule python_module modules/mod_python.dll

AddModule mod_python.c


  AddHandler python-program .py
  PythonHandler mptest
  PythonDebug on


I copied the mod_python.dll to C:/Python22/lib/mod_python.

The Apache server is starting with "Apache/1.3.26 (Win32) mod_python/2.7.6
Python/2.2.1 running..."
So i guess it should be working....

The test script looks like this:

#! C:/Python22/python.exe

from mod_python import apache

def handler(req):
    req.send_http_header()
    req.write("Hello World!")
    return apache.OK

my error.log (last entry):
[Sat Sep 21 18:00:13 2002] [error] [client 192.168.1.99] python_handler:
make_obcallback returned no obCallBack!

i've read several newsgroups and googled a lot but i didn't found a working
solution
Thanks a lot in advance...
christopher knievel




From mangwirop at kwekwepoly.co.zw  Mon Sep  9 10:06:45 2002
From: mangwirop at kwekwepoly.co.zw (Phillip Mangwiro)
Date: Mon, 9 Sep 2002 15:06:45 +0100
Subject: Accessing Tk-inter Popup menu entry
In-Reply-To: 
Message-ID: <001101c2580a$21c87de0$0700a8c4@ict4>

Can anybody help me to learn Python?




From andy.elvey at paradise.net.nz  Thu Sep 12 04:22:07 2002
From: andy.elvey at paradise.net.nz (Andy Elvey)
Date: Thu, 12 Sep 2002 20:22:07 +1200
Subject: Overloading the ">>" operator in Python 2.2.1
Message-ID: 

Hi all .
   I'm using Python 2.2.1 under Win98.  I'm doing some experimenting with
parsing, and as part of that, I'm trying to overload the right-shift
operator (>>) so that I can use it as follows (testing against a sequence
that I read in) -
  a >> b   would mean  "a is followed by b" .
   So,  you could have a function like seqtest("string_to_test" ,
"foo">>"bar" ) , and that function would return true or false, depending on
whether foo was followed by bar.
 (  I know it's possible to use regexes for this,  but being able to create
a sequence-testing operator like this would be useful .)
    Many thanks in advance ......







From spam07 at thack.org  Mon Sep 23 14:31:14 2002
From: spam07 at thack.org (Tapio Kelloniemi)
Date: Mon, 23 Sep 2002 18:31:14 GMT
Subject: Non-interpreted Python?
Message-ID: 

Hi
I'm new to Python and would like to know, wheter it is possible to
compile Python code to binary executables (and on which platforms)? Or
better, if it is possible to compile code into object format and then
link with C/C++/whatever code.

Thanks for all answers!

--
Tapio



From marklists at mceahern.com  Mon Sep 23 23:05:35 2002
From: marklists at mceahern.com (Mark McEahern)
Date: Mon, 23 Sep 2002 22:05:35 -0500
Subject: confusion about opening files
In-Reply-To: <3D8FD2F3.81F3831C@alcyone.com>
Message-ID: 

[Erik Max Francis]
> Note:  open() is an alias for file().

I read somewhere that 'file' was preferred to the use of 'open' because of
the symmetry to the type:

  >>> f = file("junk.txt")
  >>> type(f)
  

Anyway, that's how I've trained myself to spell 'open'.

Cheers,

// m

-




From oren-py-l at hishome.net  Thu Sep 12 03:26:46 2002
From: oren-py-l at hishome.net (Oren Tirosh)
Date: Thu, 12 Sep 2002 03:26:46 -0400
Subject: iterators and generators, is this the Python Way???
In-Reply-To: <3D7FF921.2040305@one.net>
References: <3D7FF921.2040305@one.net>
Message-ID: <20020912072646.GA19246@hishome.net>

On Wed, Sep 11, 2002 at 10:17:05PM -0400, Michael Schneider wrote:
> Hello All.
> 
> I just updated my python to 2.2 and noticed that generators, and 
> iterators were in there.
> 
> I often parse through many files (one at a time), and wanted the speed 
> of read,  and
> the convience of   for x in myGen:

"for x in fileobject" uses xreadlines for readahead buffering. It's faster
than reading a file with readline and should be faster than anything you 
can implement in Python.  If you must have backward compatibility to 
Python 2.1 use "for x in fileobject.xreadlines()".

Python 2.3 makes files into their own iterators. It's even faster than
xreadlines. 

> The code below works just fine,  could you review this code against the
> intent of iterators and generators.

IMHO, much of the intent of iterators and generators is to *avoid* reading 
everying into memory in advance. This way the memory requirements can often
remain constant regardless of input size.  Another good reason not to read
everything into memory is if the source is a real-time stream instead of a
file and you don't even know when it's going to end.

	Oren



From rsrchstr at msn.com  Mon Sep 30 15:33:50 2002
From: rsrchstr at msn.com (mike henley)
Date: Mon, 30 Sep 2002 20:33:50 +0100
Subject: idea for a much needed application
References: <576c1752.0209291326.56dcdf31@posting.google.com>   
Message-ID: 

Dear Sir

With all due and deserved respect, I really don't know why you insist on
arguing over this. I said my point was not about tim burners-lee, not about
economics or politics, and yet you insist on discussing them.
As for IRC; i have used IRC for several years, and AIM is not the only thing
i ever used. Yes, I believe IRC compared to modern instant messaging is a
messy medium, and perhaps a dying one even, and i'm not the only one who
believes so. Several years ago, IRC was lively and interesting, nowadays,
not many people go there. There are too many networks, many servers on the
same network don't communicate with each other, net splits are common
occurence, lags happen from time to time, servers come and go like the
passing wind, here today gone tomorrow, some may let you access, some may
not... etc. There are good reasons why modern instant messaging is easier
and more popular.
However, that's not my point, and anyway, it really don't matter now, i
found a webhost, but thanks a lot for your comments and replies, much
appreciated, honestly.

"TGOS"  wrote in message
news:fn0gpu8kh44oa1t7ih2qjmu413gvab7dou at 4ax.com...
>
> On Mon, 30 Sep 2002 01:38:51 +0100 "mike henley" 
> wrote in comp.lang.java.programmer:
>
>  
>
> > that's the whole idea of giving a personal webserver "presence", so that
> > others don't have to "go there and wait in my channel till i log on".
>
> And how does it work when you use AIM? They connect to the AIM server
> and wait till you log on. So where's the difference? Where is the
> difference whether they are running a tiny AIM client, that constantly
> monitors the AIM network, to detect when you connect to AIM, compared to
> a small IRC client, the permanently monitors a channel (in an IRC
> network) to detect when you connect to IRC? There is no difference at
> all.
>
> Except that the IRC client supports bots and they can even make a bot
> that will automatically open the browser and go to your page when you
> log on, while this is not possible in AIM.
>
> > Also, i want to be able to give a simple AOL or MSN username to
> > anyone without assuming they can write specific scripts.
>
> They don't have to write a script, YOU must write a script. They can
> install pre-written scripts for mIRC, for example, that will notify them
> once a certain user joins the channel (these already exist hundreds of
> times) - or maybe meanwhile mIRC already has this ability hard-coded,
> who knows.
>
> However, they can write a script, which gives much more power any stupid
> AIM client will ever give them. E.g. they can write a script that
> monitors for your presence and at the very second you log in, it will
> immediately resume a download, that was stopped because you logged off
> last time.
>
> If you are unhappy with the abilities of existing IRC software, write
> your own client for users (if you think you can convince them to use
> it). It doesn't even have to "present" IRC to them, IOW, they may not
> even know that they are connected to an IRC network (not chat window or
> anything). The program just sits in the background and when it detects
> that you log into the IRC channel, it will open a window:
>
> User "mike" just went online, _click here_ to visit his/her page.
>
> And if they click there, they are taken to your page.
> Your "address" would then include the information:
>
> IRC server, channel, nickname
>
> And you could choose the format yourself, if you wrote the client
> yourself, the user would input something like:
>
> irc.service.org:dyndns:mike
>
> The channel dyndns could then be also used by your friends. E.g. if the
> user enters:
>
> irc.service.org:dyndns:pete
>
> into the client, and pete goes online, the client window will say:
>
> User "pete" just went online, _click here_ to visit his/her page.
>
> Every user can add as many "watch addresses" into his client as he
> likes. Maybe this will be a completely new task for IRC, nobody has
> considered so far. You just have to write such a client, if you are
> unhappy with the existing clients.
>
> > IRC is a messy medium.
>
> IRC is no messy medium. Methinks it's above your horizon, as you never
> dealt with anything but AIM so far.
>
> --
> TGOS




From anthony at interlink.com.au  Tue Sep 24 00:37:23 2002
From: anthony at interlink.com.au (Anthony Baxter)
Date: Tue, 24 Sep 2002 14:37:23 +1000
Subject: Outlook 2002 and Python 
In-Reply-To: <03F53405C6ED434A986221919785A6A78C9339@nca-postal.ncaustin.com> 
Message-ID: <200209240437.g8O4bNK23193@localhost.localdomain>


> What:  I saw an idea for a way to create a good SPAM filter for email. 
> 
> How: I would like to try to implement the algorithm in Python.
> 
> Why:  I am trying to get familiar with Python, as I will be using it at
> work quite a bit, and would like to keep my skills honed.
> 
> Where:  Windows XP and Outlook 2002

There's work going on in this area at http://spambayes.sf.net/, 
and if you check the mailing list archives, you'll see that the
issue of integrating it with Outlook just came up in the last day
or so (subject was something like "Practical Applications").

Anthony
-- 
Anthony Baxter        
It's never too late to have a happy childhood.




From marklists at mceahern.com  Fri Sep 27 15:31:10 2002
From: marklists at mceahern.com (Mark McEahern)
Date: Fri, 27 Sep 2002 14:31:10 -0500
Subject: [XML-SIG] well-formed xml
In-Reply-To: 
Message-ID: 

[Mike Rovner]
> IIRC, double quotes are the must:
> s = 'search'

Thanks for the reply.  It seems to be the ampersand:

from xml.dom import minidom
s = "search"
s2 = s.replace("&", "&")
for x in (s, s2):
    try:
        doc = minidom.parseString(x)
    except Exception, e:
        print "Failed: %s" % x
    else:
        print "Succeeded: %s" % x

Output:

Failed: search
Succeeded: search

// m



From padraig.brady at corvil.com  Wed Sep 11 08:02:47 2002
From: padraig.brady at corvil.com (Padraig Brady)
Date: Wed, 11 Sep 2002 13:02:47 +0100
Subject: deleting the first and the last character of a string
References:  <3D7F2960.20507@Linux.ie> <20020911115118.GE2054@partagas.as.de.cw.net>
Message-ID: <3D7F30E7.6070406@corvil.com>

Manuel Hendel wrote:
> On Wed, Sep 11, 2002 at 12:30:40PM +0100, Padraig Brady wrote:
> 
>>How about: line = line[1:-1]
> 
> 
> This worked quite good, but I found another problem. There seams to be
> trailing whitespaces. I tried to strip(s) to get rid of them, but this
> doesn't work, I get the following error message:
> 
> Traceback (most recent call last):
>   File "./pop3create.py", line 9, in ?
>       print strip(line)
>       NameError: name 'strip' is not defined
> 
> What's wrong here?
> 
> manuel
> 

You need to do: line.strip()
Note the alternative is to 'import string'
before you 'string.strip(line)' however
it's much better IMHO to use the new
string methods on the string object.

P?draig.




From ulbi at ivs.tu-berlin.de  Mon Sep 23 10:24:50 2002
From: ulbi at ivs.tu-berlin.de (Andreas Ulbrich)
Date: Mon, 23 Sep 2002 16:24:50 +0200
Subject: Jython file manipulation?!
References: <2yej9.32454$gA4.4053@sccrnsc02>
Message-ID: 

Matthew Bonig wrote:
> I am trying to rename a file in Jython...
> the command I am using is just
> os.rename(filename, newFilename)

This works for me (Jython 2.1, JDK 1.4.1)

You should give us some details, i.e. exceptions etc., to get some 
better answers here.



From sholden at holdenweb.com  Mon Sep  9 16:11:02 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Mon, 9 Sep 2002 16:11:02 -0400
Subject: Windows/DOS: double clicking a .py file
References:   
Message-ID: <3h7f9.77472$l_4.28399@atlpnn01.usenetserver.com>

"Just"  wrote in message
news:just-F18BA3.17425609092002 at news1.xs4all.nl...
[ how top see messages ]
>
> Thanks for both suggestions. Another workaround just occured to me: do a
> raw_input("type enter to exit") in an exception hook. That should work
> just fine in a py2exe-fied app as well I suppose.
>

python -i

will allow you to enter interactive statements after your execution
finishes, which can be useful when you're debugging.

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------





From syver-en+usenet at online.no  Thu Sep 12 16:12:59 2002
From: syver-en+usenet at online.no (Syver Enstad)
Date: Thu, 12 Sep 2002 20:12:59 GMT
Subject: embedded Python sample
References: <2a0f4cc4.0209100520.1d3a723b@posting.google.com>  <2a0f4cc4.0209110609.1bca6901@posting.google.com>
Message-ID: 

monnetb at yahoo.com (bruno Monnet) writes:

> This sample looks great, but I'm coding for windows and the library
> used by python for fopen is not compliant with the multithreaded lib
> used by Visual 6.0 projects ...

Oh yes, I use Visual 6.0 myself. I posted here recently on what to do
with the compiler. But the quick fix is:

Don't use the debug version, use release (check my previous post on
how to debug)
Don't use anything but the multithreaded release dll version of the
cruntime libraries.

Compile and run.



-- 

Vennlig hilsen 

Syver Enstad


From LogiplexSoftware at earthlink.net  Wed Sep 11 16:50:07 2002
From: LogiplexSoftware at earthlink.net (Cliff Wells)
Date: 11 Sep 2002 13:50:07 -0700
Subject: deleting the first and the last character of a string
In-Reply-To: <200209111246.03080.shalehperry@attbi.com>
References: <20020911105818.GC2054@partagas.as.de.cw.net>
	
	 
	<200209111246.03080.shalehperry@attbi.com>
Message-ID: <1031777408.17116.65.camel@software1.logiplex.internal>

On Wed, 2002-09-11 at 12:46, Sean 'Shaleh' Perry wrote:
> On Wednesday 11 September 2002 12:25, Markus wrote:
> > Sean 'Shaleh' Perry wrote:
> > >> Is there anything which says delete the first or last
> > >> character of a string? I checked the string module on the web, but I
> > >> couldn't find anything.
> > >>
> > >>>> s = '|f|o|o|'
> > >>>> s.strip('|')
> > >>>
> > >>> s[1:-1]
> >
> > 'f|o|o'
> >
> > -Markus
> 
> True, but I like that the strip() call handles the case where one of the 
> delimiters is missing.  One of the bugs that always bit me in perl was using 
> chop() to eat the newline character when there was not a newline there to 
> eat.  I try to avoid putting myself in that situation now.

Let me apologize in advance for this:

>>> def chopd(s, d):
...     s = s.strip()
...     return s[s[0] == d : {0:len(s), 1:-1}[s[-1] == d]]
... 
>>> chopd("|f|o|o|", '|')
'f|o|o'
>>> chopd("|f|o|o", '|')
'f|o|o'
>>> chopd("f|o|o|", '|')
'f|o|o'
>>> chopd("f|o|o", '|')
'f|o|o'
>>> 

Of course, since you are worried about missing delimiters, you also have
to consider whether the data being delimited contains whitespace
(strip() might then remove some of the data).

Have you considered using one of the many delimited-file handling
modules that already exist?

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308




From lee100 at sport.rr.com  Tue Sep 17 20:49:28 2002
From: lee100 at sport.rr.com (Lee Gray)
Date: Wed, 18 Sep 2002 00:49:28 GMT
Subject: Python GUI app to impress the boss?
References: <96904b50.0209171305.6d65f574@posting.google.com>  
Message-ID: 

Cameron Laird wrote:

>>lpgray at uop.com (Lee Gray) wrote in
>>news:96904b50.0209171305.6d65f574 at posting.google.com:
>>> My boss is pretty open-minded, but also needs to see something working
>>> to be convinced Python is even a viable platform (he had never heard
>>> of it).  Otherwise, .Net is a given, whether it's any good or not,
>>> since corporate is MS all the way.
> .
> While we're pointing out individual applications that
> might be of interest, please keep in mind that Python
> is in serious production use at tens of THOUSANDS of
> sites.  Don't judge it solely by what you see of the
> first two demonstrations someone happens to push your
> way.

I read that all the time (and believe it), but that's not going to impress 
my boss, much. He's still going to want something demonstrated up close and 
personal.

> their efforts only "off the record".  I'm willing to
> bet, though, that Python will be around for longer
> than VBScript.

I can certainly agree with that. There's already conflicting information 
about MS' continuing support of VBS, the Windows Script Host and IE's HTAs 
(HTML Applications) in the scripting newsgroups.  That's one reason I want 
to learn Python personally, but if we're going to use it at work, I need to 
show something quickly to convince anyone (including myself!) that that's a 
good direction.

Thanks,
Lee



From no at mail.com  Mon Sep 16 16:17:12 2002
From: no at mail.com (BT)
Date: Mon, 16 Sep 2002 20:17:12 GMT
Subject: Source code
References:   
Message-ID: 

> |If your code is that valuable, run it on your server remote from end
> |users as a trade secret, or force them to agree to a license and protect
> |it w/ copyright.
>
> I would reformulate the issue slightly:  If you BELIEVE your code is
> that valuable, seek psychiatric help.
>

I really don't understand posts like these.
You think I'm fool to protect my work?
Ok, let's say I make a software in two years and I market it on internet.
The software is good and sell some copy.
You find the software, like it, change the name, add some feature and resell
it.
My time: 2 years, yours: 1 month.

I think you need a psychiatric help.
Only Id shared some source code, after years...
Noooooooo!!! IDDDDD!!! Foolish people!!! You want to sell it???!!! You want
to live with that???!!!
Go working in a mine, and write games for fun!!!
I can give you the phone of my clinic, but stop it NOW, join the ideal
world.




From erikprice at mac.com  Wed Sep  4 10:35:40 2002
From: erikprice at mac.com (Erik Price)
Date: Wed, 4 Sep 2002 10:35:40 -0400
Subject: help on log
In-Reply-To: <009201c253e6$b4f47ba0$2500a8c0@maxitec.co.za>
Message-ID: <959E9362-C013-11D6-BB50-00039351FE6A@mac.com>

This message has popped up quite a few times on c.l.p. and on the Tutor 
list, under two different email addresses even.

If you are really new to any kind of programming, I think this script 
is a little bit advanced.  For instance, I see that you're using the 
regular expression module, but I'm not sure that you understand how to 
use it.  It looks like you're trying to compile a regular expression 
for the text that you want generated by the script, but regular 
expressions help you search for text in an already-existing file.  
Also, you're using the string module to find a "LayerUp" string, but I 
don't see that string anywhere in your log -- so is this really even 
necessary?  (Even if it's necessary to your code, it could be omitted 
from your post.)

Also, few people have the time to sit down and troubleshoot an entire 
script, even a small one like this.  If you knew exactly what your 
problem was, you could isolate the problem from the rest of the script 
and then just ask that question.  Once it's solved, you can move on to 
the next problem.  This mailing list gets so much traffic that I end up 
deleting a lot of the messages without reading them, even the short 
ones.  Long ones which vaguely ask for help and then post a lot of code 
go right to my Trash folder.

My advice to you is that you -not- tackle an entire script like this 
right off the bat.  Fire up your interactive Python interpreter.  
Import the regular expression and string modules.  Open up a file 
handle to your ppp.log file.  Then start playing with the various 
features of the regular expression and string modules, and see what you 
can do interactively.  When you can get something to look good, write 
down what you did.  When you have a straightforward question, go ahead 
and ask it here or on the Tutor list.

I'm not trying to sound mean, but you will find this a lot easier if 
you break it down into smaller steps.  The interactive Python 
interpreter is the ultimate tool for doing this.



Erik

PS: don't use HTML-formatted or Rich Text-formatted email, on some mail 
clients (such as mine) it makes your text render too small to read.  
That only exacerbates your problem.




On Wednesday, September 4, 2002, at 03:42  AM, Morne wrote:

> Could someone please help me with this? Im really new to any kind of 
> programming .If posible would you be
> ?able to answer in detail.
> ?
> Thanx
> ?
> ?HERE IS WHAT I HAVE:
>
> ?import re
> ?import string
>
> ?secondsMatcher=re.compile("Connect time: (\d+) secs")
>
> ?def getStuff(file):
> ???? closeline = 0
> ???? errorcount = 0
> ???? secondscount = 0
> ???? connectcount = 0
> ???? data_outcount = 0
> ???? data_incount = 0
> ???? ppplist = file.readlines()
>
> ???? for line in ppplist:
>
> ?????? if string.find(line,"LayerUp") >= 0:
> ?????????? print "found connect"
> ?????????? connectline = string.split(line)
> ?????????? connectcount = connectcount + 1
>
> ?????? elif string.find(line,"ERROR") >= 0:
> ?????????? print "found error"
> ?????????? errorcount = errorcount + 1
>
> ??????? elif string.find(line,"Connect time") >= 0:
> ?????????? print "found close"
> connectSecs=secondsMatcher.search(line).group(1)
> ?????????? print "Connected for",connectSecs
> ????????? closeline = string.split(line)
> ?????????? secondscount = secondscount + string.atoi(connectSecs)
>
> ?def main():
> ??? f=open("C:/my documents/ppp.log","r")
> ???? getStuff(f)
> ???? return None
>
> ?if __name__=="__main__":
> ???? main()
>
> ?THIS IS WHAT I NEED THE PROGRAM TO DO:
>
> ?I want the program to read the attached ppp.log file and give me the
> ?following type of report:
>
>
> ?PPP Log file summary for 5 Jul 2002
> ?-----------------------------------
> ?Jul? 5 18:15:01 Connected to internet (IP 155.239.150.146)
> ?Jul? 5 18:18:08 Closed connection. ( Connect time: 197 secs: 5091 
> octets
> in,
> ?1864 octets out )
> ?-----------------------------------
> ?Successful connections: 5
> ?Failed connections: 2
> ?Total time online: 456 seconds Total data in: 66576 octets
> ?Total Data out: 66349 octets
>
> HERE IS part of the olg file seems noone wants to touch the 
> Attachment(lol)
>
> > Jul? 5 18:00:00 maxigate newsyslog[87300]: logfile turned over
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Phase: Connected to local 
> client.
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Command: /var/run/internet: 
> quit
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Phase: /var/run/internet: 
> Client
> connection dropped.
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Phase: Connected to local 
> client.
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Command: /var/run/internet: 
> set
> timeout 180
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Command: /var/run/internet: 
> dial
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Phase: bundle: Establish
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Phase: deflink: closed -> 
> opening
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Phase: deflink: Connected!
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Phase: deflink: opening -> 
> dial
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Chat: Phone: 0860007249
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Chat: deflink: Dial attempt 
> 1 of
> 1
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Phase: /var/run/internet: 
> Client
> connection closed.
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Chat: Send: AT^M
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Chat: Expect(5): OK
> Jul? 5 18:15:00 maxigate ppp[34607]: tun0: Chat: Received: AT^M^M
> Jul? 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Received: OK^M
> Jul? 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Send: ATE1Q0^M
> Jul? 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Expect(5): OK
> Jul? 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Received: ATE1Q0^M^M
> Jul? 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Received: OK^M
> Jul? 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Send: 
> ATx1DT0860007249^M
> Jul? 5 18:15:03 maxigate ppp[34607]: tun0: Chat: Expect(40): CONNECT
> Jul? 5 18:15:22 maxigate ppp[34607]: tun0: Chat: Received:
> ATx1DT0860007249^M^M
> Jul? 5 18:15:22 maxigate ppp[34607]: tun0: Chat: Received: CONNECT
> 33600/ARQ/V34/LAPM/V42BIS^M
> Jul? 5 18:15:22 maxigate ppp[34607]: tun0: Phase: deflink: dial -> 
> carrier
> Jul? 5 18:15:23 maxigate ppp[34607]: tun0: Phase: deflink: /dev/cuaa0: 
> CD
> detected
> Jul? 5 18:15:23 maxigate ppp[34607]: tun0: Phase: deflink: carrier -> 
> login
> Jul? 5 18:15:23 maxigate ppp[34607]: tun0: Phase: deflink: login -> lcp
> Jul? 5 18:15:23 maxigate ppp[34607]: tun0: LCP: FSM: Using "deflink" 
> as a
> transport
> Jul? 5 18:15:23 maxigate ppp[34607]: tun0: LCP: deflink: State change
> Initial --> Closed
> Jul? 5 18:15:23 maxigate ppp[34607]: tun0: LCP: deflink: State change
> Closed --> Stopped
> Jul? 5 18:15:24 maxigate ppp[34607]: tun0: LCP: deflink: LayerStart
> Jul? 5 18:15:24 maxigate ppp[34607]: tun0: LCP: deflink: 
> SendConfigReq(179)
> state = Stopped
> Jul? 5 18:15:24 maxigate ppp[34607]: tun0: LCP:? ACFCOMP[2]
> Jul? 5 18:15:24 maxigate ppp[34607]: tun0: LCP:? PROTOCOMP[2]
> Jul? 5 18:15:24 maxigate ppp[34607]: tun0: LCP:? ACCMAP[6] 0x00000000
> Jul? 5 18:15:24 maxigate ppp[34607]: tun0: LCP:? MRU[4] 1500
> Jul? 5 18:15:2
>
>
>





--
Erik Price

email: erikprice at mac.com
jabber: erikprice at jabber.org




From aleax at aleax.it  Fri Sep 20 02:45:27 2002
From: aleax at aleax.it (Alex Martelli)
Date: Fri, 20 Sep 2002 06:45:27 GMT
Subject: Destructor never called ???
References: <76710511.0209111450.40999dd8@posting.google.com>  <4e8lou018f9uosl5p9mb0tt6691mfivamj@4ax.com> 
Message-ID: 

Aahz wrote:
        ...
> There are several different issues.  First of all, __del__ does not get
> called if an object is destroyed by GC (GC gets used to clean up cyclic
> garbage).  Secondly, Jython does not use refcounting; it's pure GC, just

Right, but, I'd put it differently: GC is inhibited from destroying
objects whose types define a __del__ -- rather, it collects them into
gc.garbage, because it can't know that finalizing them is safe.  I
find this has a strong inhibitory effect against defining __del__ --
if and when I do, then reference loops become a potential problem
again, i.e., may lead to resource leaks once more.


Alex



From mcfletch at rogers.com  Sat Sep 21 16:35:55 2002
From: mcfletch at rogers.com (Mike C. Fletcher)
Date: Sat, 21 Sep 2002 16:35:55 -0400
Subject: WxString and python string module?
References: <36de4780.0209211158.2fc3815@posting.google.com>
Message-ID: <3D8CD82B.6070201@rogers.com>

wxString is automatically converted to/from regular Python string (or 
unicode under wxPython 2.3.3, depending on the wxPython build type).

HTH,
Mike

Decent wrote:
> Dear all:
> 
> I'm trying to rewrite my apps using wxpython,
> but how do I convert WxString object to python string?
> I have to use python's default string module, not the wxWindow's WxString.
> 
> Any Idea?

-- 
_______________________________________
   Mike C. Fletcher
   Designer, VR Plumber, Coder
   http://members.rogers.com/mcfletch/





From Gareth.McCaughan at pobox.com  Mon Sep 16 20:13:34 2002
From: Gareth.McCaughan at pobox.com (Gareth McCaughan)
Date: Tue, 17 Sep 2002 01:13:34 +0100
Subject: CFP: UK Python Conferece 2003
References: 
Message-ID: 

Duncan Booth wrote:
>                     *** Call for Participation ***
>                       UK Python Conference 2003
> 
>                             April 2-3 2003
>                          Holiday Inn, Oxford
...
> To submit a proposal, send an email message to duncan at rcp.co.uk by 2nd
> October 2003. In your message, please include the following:
          ^^^^

I'd like to propose a paper on "Novel applications of
Guido's time machine". :-)

-- 
Gareth McCaughan  Gareth.McCaughan at pobox.com
.sig under construc


From jon+usenet at unequivocal.co.uk  Mon Sep 23 18:35:48 2002
From: jon+usenet at unequivocal.co.uk (Jon Ribbens)
Date: Mon, 23 Sep 2002 22:35:48 -0000
Subject: Python and cgi and  problem!
References:  
Message-ID: 

In article , Chris Liechti wrote:
> print '%s' % (filename, filename)

I hope none of your filenames have '"', ">" or "&" in.


From aleax at aleax.it  Mon Sep 16 03:45:32 2002
From: aleax at aleax.it (Alex Martelli)
Date: Mon, 16 Sep 2002 07:45:32 GMT
Subject: raw post data
References: 
Message-ID: 

:B nerdy wrote:

> how would i retrieve the raw post data in cgi python scripts ?

I think something like:

import sys
all_posted_lines = sys.stdin.readlines()

should do it.  Raw POST'ed data should be no more and no less
than the contents of the CGI script's standard-input.


Alex



From pyth at devel.trillke.net  Tue Sep  3 06:03:19 2002
From: pyth at devel.trillke.net (holger krekel)
Date: Tue, 3 Sep 2002 12:03:19 +0200
Subject: Why it is so dramatical?
In-Reply-To: ; from list-python@ccraig.org on Tue, Sep 03, 2002 at 01:04:45AM -0400
References: <200209021107.25761.b.maryniuk@forbis.lt>  <3D73E035.2040300@nospam.attbi.com> 
Message-ID: <20020903120319.L3893@prim.han.de>

Christopher A. Craig wrote:
> djw  writes:
> 
> > Stupid question:
> > 
> > If ""join() is 100-1000 X faster, why doesn't the Python interperter
> > translate s = s1 + s2 + ... into s = "".join( [ s1, s2, ... ] ) 
> > automatically?
> 
> You won't see that kind of dramatic results if you did that.  In fact,
> my testing shows it would be slower.  
> 
> s = "".join(s1, s2) is slower than s=s1+s2.

That's not really the question.  The OP wanted to build up a huge string
(for XML/XSTL-processing) in single steps.  Using

    something += otherstring

in *loops* is usually slow.  Doing

    stringlist.append(otherstring)

and at the end

    "".join(stringlist)

is orders of magnitude faster (depending on the size of the strings).  

Another speedy option is to use cStringIO.  See my example in another 
part of this discussion.

    holger



From prittenhouse at hotmail.com  Thu Sep  5 12:30:35 2002
From: prittenhouse at hotmail.com (Phil Rittenhouse)
Date: 5 Sep 2002 09:30:35 -0700
Subject: Installing Python 2.2.1 on WinNT
References:  
Message-ID: <75848aa7.0209050830.4024ebef@posting.google.com>

Thanks for the feedback Armin, that tells me there must be something
about my install of NT that's not quite right (or at least, not quite
the same as everyone else).

I assume that the download file is OK because it installed fine
on 95, 98, ME, 2K, and XP without problems.

In fact, I have just found that if I install Office 2000 first, the
python install on my NT works cleanly.   There must be some magic that 
the Office install does, maybe a DLL update, or permission change, that 
allows it to work.

Thanks again!
Phil

 
> I have recently installed Python 2.2.1 on a NT 4.0 machine with SP6.
> 
> The install process worked flawless. 
> Is your dowloaded install file OK ??
> 
> - Armin


From thorsten at thorstenkampe.de  Wed Sep 11 10:09:02 2002
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Wed, 11 Sep 2002 16:09:02 +0200
Subject: Python primer - comments appreciated!
References:    
Message-ID: 

*  Terry Reedy
> "Thorsten Kampe"  wrote in message
>> * Terry Reedy
>>>      result.setdefault(func(item),[]).append(item)
>>
>> To make every item hashable, I made this:
>> result.setdefault(repr(func(item)),[]).append(item)

Is repr(seq) a "bulletproof", "canonical" way to make a mutable 
sequence hashable and most important for this algorithm:
repr(x) = repr(y) <=> x = y ?

I think so...

>>>      # {}.setdefault(key,default) was added for just this sort of
>>> usage
>>
>> Sorry, I just don't get it: your mixing (chaining?) a dict method
>> and
>> a list method as if it was a f(g(x)) and /it works/!?! Where is that
>> documented? How is is that evaluated (left to right)?
>
> Yes, left to right.  Dict.setdefault returns the value corresponding
> to the key after setting d[key]=default if key not already in d.  In
> this case, *all* values are initialized to [] by such a call.

You mean the value corresponding to the prior non existent key is set 
to '[]':

>>> D = {'0': [3, 6], '1': [4]}
>>> D.setdefault('2', [])
[]
>>> D
{'1': [4], '0': [3, 6], '2': []}

> Then
> append to the list.  This working depends on there being *two*
> references to the list.  The one in the dict (possibly new, possible
> not) and the one returned by the method and used by append().

Okay, let's make this clear:
D = {'0': [3, 6], '1': [4]}
D.setdefault('1', [])
  ...returns: [4]
[4].append(7)
 ...puts [4, 7] on the "stack"

But where is the instruction saying "store [4, 7] back to D['1']"?
Shouldn't this be: D['1'] = D.setdefault('1', []).append(7) ?

>> (Mathematically spoken, the quotient set is the set of all
>> equivalence
>> classes induced by func, which is what we return)
>
> Since the equivalence lists may have duplicates, they are not,
> strictly speaking, sets.  If the set of return values were made to be
> dicts (or, in 2.3, sets) instead of lists, then they would be.

This is correct. Fortunately the /quotient set/ *is* a set and does 
*not* contain duplicates (duplicate equivalence classes). It's a 
partition and partitions are always disjoint and non-empty.

Thorsten


From thorsten at thorstenkampe.de  Sat Sep  7 16:05:38 2002
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 7 Sep 2002 22:05:38 +0200
Subject: Simulating "getopt" in functions (newbie)
Message-ID: 

Hi,

I want to simulate a "getopt"-like behaviour within a _function_. This 
is to avoid having to define two functions: "function" and 
"slightly_different_function".

If the function was a standalone program, it would work like this 
("v" for "verbose"):

$ function.py 5
1

$ function.py -v 5
The result is: 1

I've thought of this to simulate it in a function:
def function(a, b=None):
    if b == "v":
        print "The result is: 1"
    else:
        print "1"

>>> function(5)
1

>>> function(5, "v")
The result is: 1

So: what is the "pythonic", "natural" way to do this in Python?


Thanks in advance,
Thorsten


From a.clarke11 at pop.ntlworld.com  Mon Sep 23 19:10:22 2002
From: a.clarke11 at pop.ntlworld.com (a.clarke11)
Date: Tue, 24 Sep 2002 00:10:22 +0100
Subject: list problem
References: 
Message-ID: <3D8F9F5E.DC48B13F@pop.ntlworld.com>

How about:

for item in x:
 while item:
  y.append(item.pop(0))
print'y=',y
?
hope this helps
Tony Clarke
Glasgow

jubafre at brturbo.com wrote:

> i have:
> x=[['0020', '0000x9'], ['0030', '0000xa'], ['00B4', '0000x8'], ['0030', '0000xb'], ['00F0'], ['0001'], ['0003'], ['0005']]
>
> and i want:
> y=['0020', '0000x9', '0030', '0000xa', '00B4', '0000x8', '0030', '0000xb','00F0', '0001',
> '0003', '0005']
>
> how to do this?
>
> Juliano Freitas
> www.gebrasil.hpg.com.br



From loewis at informatik.hu-berlin.de  Mon Sep 30 04:34:47 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=)
Date: 30 Sep 2002 10:34:47 +0200
Subject: sizeof PyTypeObject difference
References:   
Message-ID: 

"Tom Widrick"  writes:

> Well, aren't instances of a metatype types?  I know this statement was
> probably made from invalid assumptions, but just as a point.
> Since types are variable sized, as you say, how does this tie in with
> tp_basicsize and metatypes?

The instances of the type type are types, yes. If you have your own
metatype, it is your decision to determine what instances of it are.

The snippet you posted looks consistent, so the error must lie
elsewhere.

As for variable-sized objects: the instances of the type type are
variable-sized; if you create your own metatype, it is your decision
what the layout of them is. Of course, if you use functions of the
type type to implement your meta-type, you have to follow the
conventions of the type type, which are undocumented, and may be
unaccessible to external code.

> > That is hard to believe. Declaring the typedef alone can't cause a
> > core dump. Defining an object of that type, and putting the value of
> > 196 into it can't cause a core dump, either. You must be doing other
> > things, like using the resulting object in some way, to cause a core
> > dump.
> 
> Trying to use the metatype as a metaclass for a python class.

That's still not precise enough: Did you merely use the type as the
__metaclass__ attribute, or did you also try to create instances of
the resulting type?

> As an aside, are there any other quarks about making metatypes in C? the
> xxsubtype.c example in the distrib is helpful, along with the PEPs, but I'm
> yet to find a good example of a metatype implemented in C (besides the 2
> builtin metatypes, but I don't think those serve as  great minimalistic
> examples).

xxsubtype demonstrate how to subtype a type in C. Creating metatypes
in C is not really supported; you need to study the source code, and
may find that the things you want to do cannot be done without
changing typeobject.c.

In any case, I recommend to contact Christian Tismer.

Regards,
Martin


From emile at fenx.com  Thu Sep 26 11:51:31 2002
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 26 Sep 2002 08:51:31 -0700
Subject: revenge of the python puzzle
References:  
Message-ID: 

Mark McEahern
> One man's obvious is another man's enigma.  I thought it was a fine
puzzle.
>
> Another way to make it harder would be to scramble all characters.
>

This is the result of the self test I use in my scramble function:


Wkjbj Uqypfu

Fdmnjn Wpxms
(A ykhwneb pwxezmh nu l jiznjmze zinb rsrwfodpxe l zpxstmby.)
Ykhwneb: Hkfy rmymbufkz.
Wpxstmby: Kmymbufkz.
Ykhwneb: Kp, mkqmmq poj nez'b nb?
Wpxstmby: Kqp, 'ynd yprb.
Ykhwneb: Tkk tmbm fu tkmnpoj?
Wpxstmby: Skrm, Y mnqm 'xwp.
Ykhwneb: Op, akfy gku mkk. Lp... ypfep KJV zpxms rwxu'b ypxq?
Wpxstmby: Tmrp.
Ykhwneb: Xqq, ypfiapb ypxq embm. Oumq, eprb rwp ypxq pknus hs nu ypp
ywxmd?
Wpxstmby: A gonw nixeynfu ruh fup yprb nu bmdmjb emxzd 're jmxu iidp fu
iq injy. Zb'd iq dkjenyxwxy fsnunkz yprb ypxq'bm jmzbnu'.
Ykhwneb: Smzbnus?
Wpxstmby: Kqp.
Ykhwneb: Onpm jnbyd?
Wpxstmby: Vfrkydj. Zb'd iq jmmnxm yprb ypxep zpxms rwp mojkbnz' hupmu
ypp inzorsbmtmjenkz yprb ypxq'bm jnbyd. Ohzmbdp ypxnu jm'rdnku
. Yopm gku l zbrwb ypp zpxmre' ymjyxudq yk 'fs rhfib ypp gnxdh fu ypxnu
'nuh mmae. Skg enyuxed ypxnu rbymisye yk gdj gwfq ywxm yk yw
xm. Skyndm yprb ypxq pk jkb zk iidp gdj re... rdhqimb.
(Coro joro... gdrs gdrs gdrs... epfkzp... yphy.)
Ykhwneb: Tmd, jib epj pk ypxq ypnup ypxq'bm jnbyd?
Wpxstmby: Kufbtmu gonw nixeynfu. Oup ypnus ne gku zibm, ypp zpxms ne jkb
l dwxoyibm fm ypp rnu. Ypxq toqm xufwikhe pngmnkhdyq nu ypp
 dkisrwrbndxdj znismm rkb fm rmbktnz'. (Coro joro... gdrs gdrs gdrs...
epfkzp... yphy.) Ywfijdp ne, zpxms rwp qmbq pnq. Oudm ypxq am
b ru nyxo nu ypxnu 'xope, ypxwp'd jk zpnmynz' nb.
Ykhwneb: Cib epxwp pnh ypxq amb ypp nyxo?
Wpxstmby: Fwfq Xobkmy. Xm'd yprb ikzb pojnxwfid fm dwxoyibmd, l ddxdxw
zpxms. 'V'd bmrdnbxy yprb l zpxms'd mngm dkjeneye fm zbrupnz'
 rwfijy gku l gmg ikjbte ruh ypxu jmnu' xoymz. Kuh yprb'd l pmrwxeznjn
rwfermdb gku ru rqjnynfid zpxms.
Ykhwneb: Vmmd epj pkz'b mkk kizb bmikqm Xobkmy?
Wpxstmby: Cmdohep fm ypp xufwikhe dkiqxwdnrd rkzenhndnbnmd nm 'p
zidkxmpe.
Iknkp Odxw: Kuh eprb xfrkydj rwp ypp dkiqxwdnrd rkzenhndnbnmd fm fdnup
rdnoynfu?

Hmb mkhw nifbxe gwfq WqrwyGhkym - tbys://efg.iczkgb.dk.hz

--

Emile van Sebille
emile at fenx.com

---------







From sismex01 at hebmex.com  Wed Sep 25 19:18:28 2002
From: sismex01 at hebmex.com (sismex01 at hebmex.com)
Date: Wed, 25 Sep 2002 18:18:28 -0500
Subject: List/Tuple bug or feature?
Message-ID: 

> 
> sismex01 at hebmex.com fed this fish to the penguins on Tuesday 24 
> September 2002 03:12 pm:
> 
> > It's one of python's features :-)
> > 
> > For when you wanna write a long string, SQL for example:
> > 
> > Query = "SELECT what, when, where, why "
> >         "FROM t1, t2, t2 "
> >         "WHERE t1.id = t2.id_t1 and t3.id_t2 = t2.id and t1.id_t2 =
> >         t3.id " "AND t1.answer = 'OK'"
> >
>         What's wrong with...
> 
> query = """select what, when, where, why
>         from t1, t2, t3
>         where t1.id = t2.id_t1
>                 and t3_id2 = t2.id ...etc """
> 

Hey, don't kill the messenger, I'm just explaining what
happened regarding the auto-concatenation of string
constants. If you don't like, don't use it.

But then, you did ask.

>>> query = """select what, when, where, why
               from t1, t2, t3
               where t1.id = t2.id_t1
                 and t3_id2 = t2.id ...etc """
>>> query
'select what, when, where, why\n               from t1, t2, t3\n
where t1.id = t2.id_t1\n                 and t3_id2 = t2.id ...etc '
>>> 

...an unsightly amount of useless whitespace.

-gus






Advertencia: 
La informacion contenida en este mensaje es confidencial y restringida y
esta destinada unicamente para el uso de la persona arriba indicada, Esta
comunicacion representa la opinion personal del remitente y no refleja
necesariamente la opinion de la Compa?ia. Se le notifica que esta
estrictamente prohibida cualquier difusion, distribucion o copia de este
mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error,
o si hay problemas en la transmision, favor de comunicarse con el remitente.


Todo el correo electr?nico enviado para o desde esta direcci?n ser?
procesado por el sistema de correo corporativo de HEB. Tal correo
electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien
ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan
las normas de seguridad de la empresa.



From phr-n2002b at NOSPAMnightsong.com  Sun Sep 15 04:13:09 2002
From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin)
Date: 15 Sep 2002 01:13:09 -0700
Subject: How to represent sets
References:  
Message-ID: <7xn0qjacx6.fsf@ruckus.brouhaha.com>

"James J. Besemer"  writes:
> For dense sets isomorphic with integers, the long integer
> implementation probably will be superior.

Using immutable long integers to represent mutable sets doesn't make
much sense.  Better to use arrays like the ones implemented by the
array module.


From peter at engcorp.com  Tue Sep 10 10:27:57 2002
From: peter at engcorp.com (Peter Hansen)
Date: Tue, 10 Sep 2002 10:27:57 -0400
Subject: run-mailcap in python?
References:   <3d7de60b$1@news.sentex.net> 
Message-ID: <3D7E016D.2646AD9F@engcorp.com>

Thomas Guettler wrote:
> 
> Peter Hansen schrieb:
> > import  os
> > if os.name == 'posix':
> >     def startfile(name):
> >         os.system('run-mailcap "%s"' % name)
> >     os.startfile = startfile
> 
> Yes, ugly but it works. Thank you!

In Pythonia, "ugly" is sometimes spelled "pragmatic".  

-Peter


From ataylor at ucsd.edu  Thu Sep 26 15:28:29 2002
From: ataylor at ucsd.edu (Adam Taylor)
Date: 26 Sep 2002 12:28:29 -0700
Subject: Getting started
References: <3D911306.7080609@ucsd.edu> 
Message-ID: 

> My read of page 5 is he equates his internal use of "weakly checked" 
> with "weakly typed" and further suggest that the latter term is commonly 
> used "in the literature," which it does seem to be.

This sounds like the same thing as I said, or damn close.  Am I
missing something?

> I think your read of Cardelli overall is correct -- that Python, like 
> Lisp, would be classified as "untyped" because it has no static type 
> system.  

Yes.  It seems to me that Table 1 in Cardelli:

          Typed   Untyped
Safe      ML      LISP
Unsafe    C       Assembler

Might be better like this:

          Statically typed   Dynamically typed    Untyped
Safe      ML                 LISP
Unsafe    C                                       Assembler

(Python would also be in the (Safe,Dynamically typed) position.)

Although safety and strongly-checked are not the same thing, this
table is also correct:

                      Statically typed   Dynamically typed   Untyped
Strongly checked      ML                 LISP
Weakly checked        C                                      Assembler

> A literal reading furthermore defines "weakly typed" only in 
> terms of static checking.

I don't understand what you mean by this.  Cardelli never uses the
term "weakly typed" himself, he only uses it that one time, to say
that it's the term most people use for the concept that he prefers to
call "weakly checked".

> Interestingly, a google search on the term revealed that about 25% of 
> the meaningful hits equated "weakly typed" and "dynamically typed" (the 
> latter of which is what Cardelli calls "untyped").  The other 75% 
> generally characterized strong vs. weak type systems in terms of "type 
> safety", i.e., a mechanism for preventing  "type errors," regardless of 
> whether the checking is done statically or dynamically.  [The list of 
> references appears in a prior post to this thread.]

So 75% of people, when they talk about strongly-typed vs. weakly-typed
languages, are refering to the strongly-checked vs. weakly-checked
axis in the table above, whereas 25% of people are refering to the
statically-typed vs. dynamically-typed vs. untyped axis.  These
numbers (75% and 25%) seem far enough from 100% and 0% that everyone
would be better off not using the terms "strongly typed" and "weakly
typed", and using "strongly checked", "weakly checked", "statically
typed", "dynamically typed", or "untyped", as appropriate.  Or at
least when people start talking about "strongly typed" vs "weakly
typed" languages, that first thing to get straight is which axis
they're talking about.

Adam

-----
"James J. Besemer"  wrote in message news:...
> Adam Taylor wrote:
> 
> > This last is available at:
> > http://research.microsoft.com/Users/luca/Papers/TypeSystems.pdf 
> 
> I believe your interpretation is accurate for the most part.
> 
> > Cardelli doesn't use the term "weakly typed" himself, but on page 5 he
> > seems to be say that "weakly typed" is the commonly used term for what
> > he calls "weakly checked".  C is weakly checked, in his terminology, and
> > that's why it's unsafe. 
> 
> 
> My read of page 5 is he equates his internal use of "weakly checked" 
> with "weakly typed" and further suggest that the latter term is commonly 
> used "in the literature," which it does seem to be.
> 
> > But people on this thread seem to be using "weakly typed" to mean
> > roughly the same thing as Cardelli's "untyped".  Which is fine, and
> > pretty close to Cardelli's terminology.  But clearly the terms "untyped"
> > (=="weakly typed" on this thread) and "weakly checked" (=="weakly typed"
> > in common usage) are very different things. 
> 
> 
> Well, some people here use the term casually and incorrectly, as a 
> measure of quality of a language's object model, which I am sure you'll 
> agree is completely inconsistent with most uses of the term, including 
> Cardelli's.
> 
> Interestingly, a google search on the term revealed that about 25% of 
> the meaningful hits equated "weakly typed" and "dynamically typed" (the 
> latter of which is what Cardelli calls "untyped").  The other 75% 
> generally characterized strong vs. weak type systems in terms of "type 
> safety", i.e., a mechanism for preventing  "type errors," regardless of 
> whether the checking is done statically or dynamically.  [The list of 
> references appears in a prior post to this thread.]
> 
> I think your read of Cardelli overall is correct -- that Python, like 
> Lisp, would be classified as "untyped" because it has no static type 
> system.  A literal reading furthermore defines "weakly typed" only in 
> terms of static checking.
> 
> However, I submit that his use is inconsistent with the more common use 
> of the term.  Too, I think this is actually a minor oversight in 
> Cardelli's paper.  His focus overall was static systems and I think he 
> simply didn't give enough consideration to dynamically typed languages. 
>  E.g., he says "untyped" languages such as Lisp can be "safe" but he 
> defines "weakly typed" only in terms of languages that do static type 
> checking.  I would argue that in the first place he misclasifies Lisp as 
> "untyped".  I suspect he took the naive view of Lisp, in which 
> everything is a list, when in fact a rather wide variety of "objects" 
> actually exist in a typical, mature Lisp system.  Of course, Python and 
> Smalltalk are better examples, in that they both have robust object type 
> systems and are in principle very secure from a type checking sense. 
>  (Of course, there are probably things you can do with the compiler and 
> debug class objects that violate type safety, making them both unsafe in 
> general.)
> 
> The primary distinction between safe and unsafe, strong and weak type 
> systems revolves around the notion of whether or not "type errors" can 
> be prevented by the type system.  The distinction between typed and 
> untyped is less interesting, except to use "untyped" as a way to 
> eliminate a class of languages from further discussion.  Within typed, 
> there should be two sub-classes, based on whether type checking is 
> primarily static or dynamic.  This is more interesting and useful, and 
> is consistent with "the literature" as far as I can determine.  
> 
> I furthermore have a conjecture that much of Cardelli's work on 
> "judgments" would apply equally well to static and to dynamic systems. 
>  The important criterion is that the type system be secure and that the 
> total collection of function x arguments definitions be unambiguous (at 
> least during the sequence of computation of interest).  Whether the 
> checks take place at compile time or at runtime I don't think materially 
> affects his theories.  But I could be overlooking something in this regard.
> 
> In any case, my own use of the term "weakly typed" and associated terms 
> (strongly typed, type safety, etc.) in this thread have been consistent 
> with "the literature" (though slightly inconsistent with Cardelli), in 
> that I class Python to be "strongly typed" using "dynamic checking".   
> That seems to be the consensus here.  Only confusion has been about 
> "weakly typed," and hopefully we're close to exhausting that topic..
> 
> --jb


From martin at v.loewis.de  Mon Sep 16 01:43:54 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 16 Sep 2002 07:43:54 +0200
Subject: couldnt find __dic__
References: <7153651c.0209151958.4099ac3e@posting.google.com>
Message-ID: 

quiteblack at yahoo.com (black) writes:

> my book told me all dictionaries have __dic__ method but I searched
> each dictionaries and find nothing, where is it ???

Your book is wrong; it is "__dict__" not "__dic__" (however, your book
might be right and you just did not read it carefully).

Regards,
Martin


From martin at v.loewis.de  Sat Sep  7 03:46:32 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 07 Sep 2002 09:46:32 +0200
Subject: Converting python object reference to int and back
References: <3D79AC95.1000000@NOSPAMbitbuilder.com>
Message-ID: 

Ahmad Baitalmal  writes:

> How can I get an id (pointer/reference) from a python object and then
> get that object back using that integer?

To get an integer, use the id function. To get the object back, create
a dictionary mapping the ids to the real objects.

Regards,
Martin


From dwelch91 at nospam.attbi.com  Sun Sep 22 21:55:48 2002
From: dwelch91 at nospam.attbi.com (djw)
Date: Mon, 23 Sep 2002 01:55:48 GMT
Subject: PyQt setup on Linux Mandrake 8.2
References: <3D8B4898.20808@nospam.attbi.com> <3d8e7141$1@news.nz.asiaonline.net>
Message-ID: <3D8E74A4.7000404@nospam.attbi.com>

Thanks to you and the others, I finally got this to work. My remaining 
question/problem/puzzlement is what to do about the fact I now have two 
Python 2.2 installs on my system. Mandrake installed everything during 
its setup into /usr and everything I built/installed went into 
/usr/local. I was going to rip out the version that Mandrake layed down 
in /usr and just use the /usr/local copy, but when I ran the package 
manager and told it to uninstall all the various py* pieces, the list of 
dependencies it wanted to also delete was scary (stuff like filesystem 
modules). Unfortunately, when I try to install new py modules, they all 
want to install into /usr instead of /usr/local, since /usr/bin/python 
is ahead of /usr/local/bin/python on $PATH, causing sys.prefix to point 
to /usr, I suppose.

So, this leaves me wondering... its not possible to install Mandrake 
without Python (as evidenced by the dependencies), but the location it 
is installed at is "wrong" by default - so, what is the "proper" way to 
handle this situation? (It would seem nice to install Linux without 
Python and compile and install it afterwards). I can't tell from your 
list of commands where python is located, but I assume its in /usr? 
Also, I noticed that the copy of python that was installed by the system 
lacked Python.h, whereas the copy I compiled and installed had this 
file. Are you supposed to "overlay" the system copy in /usr with the 
extra files that things like sip/pyqt need (i.e., Python.h)?


Don


Colin Brown wrote:
> "dwelch"  wrote in message
> news:3D8B4898.20808 at nospam.attbi.com...
> 
>>I would like to setup PyQt 3.4 on my Mandrake 8.2 box.
>>----snip----
>>
> 
> 
> Hi Don
> 
> I few months ago I installed PyQt under Mandrake Linux 8.2 for i586
> and ended up doing the following:
> ----------------------------------------------------------------------------
> 
> Put tmake_1.8.tar.gz into /usr/local
> Put sip-3.3.2.tar.gz into /usr/local
> Put PyQt_3.3.2.tar.gz into /usr/local
> 
> gunzip tmake_1.8.tar.gz
> tar -xvf tmake_1.8.tar
> gunzip sip-3.3.2.tar.gz
> tar -xvf sip-3.3.2.tar.gz
> gunzip PyQt_3.3.2.tar.gz
> tar -xvf PyQt_3.3.2.tar.gz
> 
> TMAKEPATH=/usr/local/tmake_1.8/lib/linux-g++
> export TMAKEPATH
> 
> cd /usr/local/sip-3.3.2
> python build.py -q /usr/lib/qt2 -i /usr/lib/qt2/include -g
> /usr/local/tmake_1.8/bin/tmake -l qt-mt
> make
> make install
> 
> cd /usr/local/PyQt_3.3.2
> python build.py -q /usr/lib/qt2 -g /usr/local/tmake_1.8/bin/tmake -l qt-mt
> make
> make install
> 
> ----------------------------------------------------------------------------
> 
> I hope you find this useful.
> 
> There was a compile error that have yet to follow up on to do with glu but
> apart from that I ended up with a pyuic that works okay with output from
> Qt_Designer except for the table and custom widgets. When I get time I
> will follow up on these.
> 
> Cheers
> Colin Brown
> PyNZ
> 
> 
> 
> 




From gumuz at looze.net  Tue Sep  3 08:56:21 2002
From: gumuz at looze.net (Gumuz)
Date: Tue, 3 Sep 2002 14:56:21 +0200
Subject: Design question.... parent/child class
Message-ID: <3d74b021$0$234$4d4ebb8e@news.nl.uu.net>

hi all,

i have a SessionManager class, which contains a list of Session
objects(instantiated from a Session class). I have a design problem.

Each session object has a small 'queue' of messages for the specific
session. How can a session send a message to another session without having
some kind of parent-reference to the SessionManager object?

i am a bit puzzled, or is this parent-reference not such a bad idea after
all?


thanx,

Guyon




From t_therkelsen at hotmail.com  Sun Sep  8 15:03:25 2002
From: t_therkelsen at hotmail.com (Troels Therkelsen)
Date: 08 Sep 2002 19:03:25 GMT
Subject: transform a list of lists in a lit of strtings???
References: 
Message-ID: 

jubafre at brturbo.com wrote:
> I have a list of lists like this:
> 
> labels=[['D1'], ['D2'], ['D3']]
> 
> and i want to transform ia a list of strings
> 
> labels2==[ 'D1' ,  'D2' ,  'D3' ] <<<<<<<----------- how i can get it????
> 
> 	
> Juliano Freitas
> www.gebrasil.hpg.com.br 

labels2 = map(lambda x: x[0], labels)

or

labels2 = [ x[0] for x in labels ]


Whichever suits your fancy and/or programming style.

Regards,

Troels Therkelsen


From noone at nowhere.com  Thu Sep  5 22:46:45 2002
From: noone at nowhere.com (c)
Date: Thu, 05 Sep 2002 22:46:45 -0400
Subject: Windows NT login script
Message-ID: <3D781715.5070505@nowhere.com>

I am a newbie to Python and I'm wondering how difficult it would be to 
write a Windows NT/2000 login script using Python?

Can anyone think of a good way to do it?



From aahz at pythoncraft.com  Thu Sep 12 01:29:07 2002
From: aahz at pythoncraft.com (Aahz)
Date: 12 Sep 2002 01:29:07 -0400
Subject: Destructor never called ???
References: <76710511.0209111450.40999dd8@posting.google.com> 
Message-ID: 

In article ,
Tim Roberts   wrote:
>
>However, Python is a garbage-collected system.  Unlike in COM, an object is
>NOT destroyed as soon as its reference count goes to 0.  Your object will
>only be destroyed if the garbage collector happens to run, and decides that
>it might be a convenient time to actually free up the space your object
>occupies.

Wrong.  CPython uses reference counting backed by GC.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Project Vote Smart: http://www.vote-smart.org/


From mmaddox at hcsmail.com  Fri Sep  6 18:58:57 2002
From: mmaddox at hcsmail.com (mmaddox at hcsmail.com)
Date: Fri, 6 Sep 2002 18:58:57 -0400 (EDT)
Subject: Larry Wall's comment on python...
Message-ID: <200209062258.g86MwvVm096127@mail.hcsmail.com>

> So does the fact that C++ forces you to use { } as block delimiters
irritate
> the Libertarian in you?

Of course it does. I need a parser that can decipher the pure randomness
of my own code. Basically, I'd like to run an SHA-512 algorithm against a
poorly-typed text file describing my program. Then, I'd just compile the
message digest.

Of course, most of my current code has one big block, main(), and I just
cut-and-paste the rest. 

--
Michael F. Maddox
Senior Software Engineer
Hayes
Tallahassee, FL, USA




From sebastian at wangnick.de  Sun Sep 22 08:08:55 2002
From: sebastian at wangnick.de (Sebastian Wangnick)
Date: Sun, 22 Sep 2002 14:08:55 +0200
Subject: Trying the impossible?
References: <30292041.0209210032.6e07d9f3@posting.google.com>
Message-ID: 

Dear all,

yesterday I recompiled Tcl/Tk (8.4.0) and pythoncore/python/_tkinter (2.2.1)
in debug mode with VC 6.0. Now, when trying my script, I'm getting the
following error:
    PyThreadState_Get: no current thread
This is happening when NTDLL tries to call my_wndproc via calldll.

It seems to me that the following is happening: Within Tkapp_MainLoop,
before calling Tcl_DoOneEvent, the code saves the current thread state
within tcl_tstate and then releases the interpreter_lock, setting the
_PyThreadState_current to NULL. Whenever Tcl calls back to Python, the
ENTER_PYTHON macro re-acquires the interpreter_lock and restores the thread
state. However, in my script this is not performed, as it is Windows calling
my script, and calldll doesn't know that it has to reacquire the interpreter
lock, nor where to find the thread state!

I undef'd WITH_THREAD in pyConfig.h and recompiled, and then my script
works.

I'm uncertain how to best make calldll thread-safe under these
circumstances. Maybe the author can help?

Regards,
Sebastian

"Sebastian Wangnick"  wrote in message
news:30292041.0209210032.6e07d9f3 at posting.google.com...
> Dear all,
>
> I'm trying to overload, using dynwin/calldll under Windows, the
> Tkinter drawing routines to perform some additional drawing on top of
> Tk.
>
> My first attempt was to bind to "", but this binding seemingly
> is triggered before Tk performs its drawing, so my stuff was erased by
> Tk :(
>
> Now I'm trying to overload the WindowProc itself. To test the
> mechanism, I started by simply passing everything on to
> CallWindowProc:
>
> from Tkinter import *
> import dynwin
> import dynwin.gencb
> import dynwin.windll
> import dynwin.winwin
> user32 = dynwin.windll.module ('user32')
>
> def my_winproc (hwnd, message, wparam, lparam):
>     return user32.CallWindowProc (tk_winproc,
>         hwnd, message, wparam, lparam)
> my_winproc_cb = dynwin.gencb.generated_callback ('llll', my_winproc)
>
> def map (event):
>     global tk_winproc
>     hwnd = frame.winfo_id()
>     tk_winproc = user32.GetWindowLong (hwnd,
>         dynwin.winwin.GWL_WNDPROC)
>     user32.SetWindowLong (hwnd, dynwin.winwin.GWL_WNDPROC,
>         my_winproc_cb.address)
>
> root = Tk()
> frame = Frame(root,width=100,height=100)
> frame.pack(fill=BOTH,expand=1)
> frame.bind("",map,"+")
> root.mainloop()
>
> However, when starting this it crashes with 'The instruction at
> "0x1e0381fa" referenced memory at "0x00000008". The memory could not
> be "read".'
>
> Any idea what I'm doing wrong? I'm using XP, btw.
>
> Regards,
> Sebastian




From aleax at aleax.it  Wed Sep 18 11:37:22 2002
From: aleax at aleax.it (Alex Martelli)
Date: Wed, 18 Sep 2002 15:37:22 GMT
Subject: Python comment stripper
References: <16Nh9.248$Wc6.17087796@newssvr13.news.prodigy.com> <3d8807b1$1@news.sentex.net> 
Message-ID: 

Dennis Reinhardt wrote:

>> This doesn't seem like a good reason to me.  Why not just use .pyc files
>> all the time and be done with it?
> 
> I am looking to package Python programs as EXE files for upload/download
> over the internet.  The "good reason" is faster upload/download over
> dialup lines, not hard disk space.

Makes sense.  Let's see, what about a one-(logical)-liner (warning, 
untested!):

open(outfile, 'w').writelines( [ 
    tok[1] for tok in tokenize.generate_tokens(open(infile).readline) 
           if tok[0] != tokenize.COMMENT ] )

Probably best rewritten as a loop of a few lines, but, I think the
key idea holds -- tokenize.generate_tokens seems to be the best way.


Module gzip is probably a good idea to help you reduce size, too.
I.e., besides stripping comments, you might also use gzip for
compression -- perhaps not quite as good as the compression you
might get from bzip2, but the latter is not part of the standard
Python distribution.  What are you using now for compression?


Alex



From dsavitsk at e-coli.net  Tue Sep  3 20:42:30 2002
From: dsavitsk at e-coli.net (dsavitsk)
Date: Wed, 04 Sep 2002 00:42:30 GMT
Subject: winsound.Beep() frequencies
References: <3ab719f7.0209031229.33667461@posting.google.com>
Message-ID: 

i believe a supplied value of 4000 plays a frequency of 4000Hz.  you should
consult a table of frequency to pitch to convert.  typically A in the 4th
piano octave is 440Hz, and you should be able to derive the rest from that
(or search on google).

-d

"Stuart"  wrote in message
news:3ab719f7.0209031229.33667461 at posting.google.com...
> While looking at the python documentation, I noticed that there are no
> frequency/pitch tables for using with the winsound module.  Does
> anyone know whether this documentation exists, and/or what the
> corresponding frequencies to pitches are?
>
> Thanks,
> Stuart




From richie at entrian.com  Tue Sep 24 08:32:26 2002
From: richie at entrian.com (Richie Hindle)
Date: Tue, 24 Sep 2002 13:32:26 +0100
Subject: convention for Pickler file extension
References: <918bc22f.0209230208.4eaca702@posting.google.com>  
Message-ID: 

> I call files *.pickle

Me too.

Are there any non-medieval platforms that don't let you have arbitrary
length file extensions?

-- 
Richie Hindle
richie at entrian.com



From gerhard.haering at opus-gmbh.net  Mon Sep  2 08:53:19 2002
From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: 2 Sep 2002 12:53:19 GMT
Subject: Must have Python modules?
References: <_THc9.42153$vY2.1039887@e3500-atl2.usenetserver.com>   <3D735D9C.9060607@mxm.dk>
Message-ID: 

In article <3D735D9C.9060607 at mxm.dk>, Max M wrote:
> Robert Oschler wrote:
> 
>> I want to know what the other favorites are "out there".
> 
> win32all (if os in windows), mx*, PIL, reportlab, Nummeric

The same set for me, minus ReportLab (not yet) Plus wxPython and pyPgSQL.

-- Gerhard


From black at flamingo.ru  Fri Sep 20 07:24:24 2002
From: black at flamingo.ru (Vasiliy A. Chernoivan)
Date: Fri, 20 Sep 2002 17:24:24 +0600
Subject: M$SQL connections from linux
Message-ID: <1032528860.599940@news.etel.ru>

Hello all
Is there some module for python which performs the task?
Is it possible at allto access data under M$SQL from linux machine?

Every comment will be highly appreciated
Thanks
                Vasiliy.




From radfaraf at NOSPAMoptonline.net  Mon Sep 30 21:31:49 2002
From: radfaraf at NOSPAMoptonline.net (kingfool)
Date: Tue, 01 Oct 2002 01:31:49 GMT
Subject: Keeping track of variables.
Message-ID: 

Is there an editor I can use that will help me find the first instance a 
variable was used across an entire program of multiple files? Reason I ask 
is because I'm going through and adding features to a program as a learning 
experience. Coming from C++ as my only programming language I find it a bit 
confusing to not know when something was declared/used first, which can 
reveal a bit more about what the variable is for.


From jpmieville at bluewin.ch  Thu Sep 19 15:08:52 2002
From: jpmieville at bluewin.ch (Jean-Paul Mi=?ISO-8859-1?B?6Q==?=ville)
Date: Thu, 19 Sep 2002 21:08:52 +0200
Subject: Problem with urllib
References:  
Message-ID: 

Yes,

I use :
Python 2.2.1 (#134, Apr  9 2002, 21:16:52)  [CW CARBON GUSI2 THREADS GC]
Type "copyright", "credits" or "license" for more information.
MacPython IDE 1.0.1

I don't know if this problem is related to MacPython.



> From: Jeff Davis 
> Organization: RoadRunner - West
> Newsgroups: comp.lang.python
> Date: Thu, 19 Sep 2002 04:26:49 GMT
> Subject: Re: Problem with urllib
> 
> 
> I can't reproduce the error either way (interactive or otherwise). Are you
> use that you're using the same python interpreter version for both?
> 
> Regards,
> Jeff
> 
> Jean-Paul Mi?ville wrote:
> 
>> I don't understand why with some URL I have got [Errno 57] Socket is not
>> connected.
>> 
>> The code is :
>> 
>> import urllib2
>> 
>> page = urllib2.urlopen(' http://www.python.org/doc/NonEnglish.html')
>> print page.read()
>> 
>> If I do the same thing with python interactive, I can't reproduce the
>> error.
>> 
>> Thanks in advance,
>> Jean-Paul
> 



From aahz at pythoncraft.com  Sun Sep 29 11:10:39 2002
From: aahz at pythoncraft.com (Aahz)
Date: 29 Sep 2002 11:10:39 -0400
Subject: ANN: Tim Peters' FixedPoint on SourceForge
References: 
Message-ID: 

In article ,
dougfort  wrote:
>
>This project makes Tim Peters' FixedPoint math class available to the community
>as a SourceForge project. 
>
>Check out http://fixedpoint.sourceforge.net

Should I change the link on my web site to point at this?
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Project Vote Smart: http://www.vote-smart.org/


From mcfletch at rogers.com  Tue Sep 10 10:30:14 2002
From: mcfletch at rogers.com (Mike C. Fletcher)
Date: Tue, 10 Sep 2002 10:30:14 -0400
Subject: dynamism
References:  
Message-ID: <3D7E01F6.6030407@rogers.com>

I'm coming in kinda late in this thread... Here's my understanding 
(which might be erroneous):

	It is possible for new-style classes to declare that they have only a 
limited number of instance attributes (via the __slots__ declaration or 
C equivalent) in order to enforce policy or allow for optimisation. 
Derivatives of these classes, however, which do not themselves declare 
__slots__ and which don't use any getattr* setattr* or descriptor 
(property) hooks to prevent the operations, have standard Python 
semantics (i.e. they have a dict object in which instance attributes are 
stored, and you may add/remove keys from this dict with attribute's 
semantics).

So, while it's probably true that "all" of those derivative classes do 
not allow you to add attributes, most will allow it, and AFAIK, all of 
the standard built-in types (list, tuple, object, string, etc.) do 
nothing to prevent their _sub-classes_ from having new attributes 
(though they will likely reject adding attributes to instances of the 
base class).

Don't forget your smiley :) ,
Mike

Duncan Booth wrote:
...
>>[Duncan Booth]
>>
>>>New style classes (which are those with 'object' or other builtin
>>>classes as a base class) do not all allow you to add arbitrary
>>
>                                    ^^^
...
> Read what I wrote? The word 'all' was supposed to be a clue.

_______________________________________
   Mike C. Fletcher
   Designer, VR Plumber, Coder
   http://members.rogers.com/mcfletch/





From jubafre at brturbo.com  Mon Sep 23 00:49:01 2002
From: jubafre at brturbo.com (jubafre at brturbo.com)
Date: Mon, 23 Sep 2002 01:49:01 -0300 (GMT-03:00)
Subject: match or sub problem?
Message-ID: <-2119489446.1032756541985.JavaMail.nobody@webmail1>

I have this list of strings:
final=['20 0x9', '30 0xa', 'B4 0x8', '30 0xb', 'F0', ' 1', ' 3', ' 5']

and i want to erase the nodes with whitespaces in the begining,
i use  "match" but doesn?t work and "sub", i think the problem is in the "sub", why?

final2=[]
for i in range(len(final)):
    p=re.compile(" ")
    t1=p.match(final[i])
    t=sub(p, "", final[i])
    print t
    final2.append(t)
print final2

None
None
None
None
None
<_sre.SRE_Match object at 0x01420DF0>
<_sre.SRE_Match object at 0x01421B00>
<_sre.SRE_Match object at 0x014211D0>	

p.match find just last 3  nodes with whitespaces in the begining, but the sub replace
al the nodes, like that: ['200x9', '300xa', 'B40x8', '300xb', 'F0', '1', '3', '5']

i want just the last 3 nodes replaced
 ['20 0x9', '30 0xa', 'B4 0x8', '30 0xb', 'F0', '1', '3', '5']

Juliano Freitas
www.gebrasil.hpg.com.br 

From manuel at hendel.net  Tue Sep 17 04:23:36 2002
From: manuel at hendel.net (Manuel Hendel)
Date: Tue, 17 Sep 2002 10:23:36 +0200
Subject: don't understand error message
Message-ID: <20020917082336.GD23629@partagas.as.de.cw.net>

I do the following,

domains = []

for line in lines:
    line = string.strip(line)[1:-1]
    fields = string.split(line, "|")
    if fields[3] not in domains:
        domains.append(fields[3])

error:

Traceback (most recent call last):
  File "./pop3create.py", line 16, in ?
    if fields[3] not in domains:
IndexError: list index out of range

Thanks,
    Manuel

-- 
When a man stops trying to prove he is a man, he is a man. 
-D. Talmadge Gosnell 



From peter at engcorp.com  Tue Sep 10 08:31:28 2002
From: peter at engcorp.com (Peter Hansen)
Date: Tue, 10 Sep 2002 08:31:28 -0400
Subject: run-mailcap in python?
References:  
Message-ID: <3d7de60b$1@news.sentex.net>

Thomas Guettler wrote:
> Thomas Guettler schrieb:
> 
>> Hi!
>>
>> On Unix there is a script called run-mailcap, which
>> opens the corresponding programm with the given file:
>>
>> run-mailcap foo.html
>> --> Default browser starts
> 
> 
> [cut]
> 
>> run("foo.html")
>>  --> Browser starts
> 
> 
> I just discoverd os.startfile(), but it is unfortunately
> only available on win32.
> 
> A Unix version would be nice.

import  os
if os.name == 'posix':
     def startfile(name):
         os.system('run-mailcap "%s"' % name)
     os.startfile = startfile

?

-Peter



From Oschler at earthlink.net  Wed Sep  4 08:59:31 2002
From: Oschler at earthlink.net (Robert Oschler)
Date: Wed, 4 Sep 2002 08:59:31 -0400
Subject: Why Python?
References:   <3D75EA07.D5EB1F5A@info.unicaen.fr>
Message-ID: <4vnd9.2$2L.307@e3500-atl2.usenetserver.com>

"Jerzy Karczmarczuk"  wrote in message
news:3D75EA07.D5EB1F5A at info.unicaen.fr...
> RPM1 wrote:
>
> You know, I am a peaceful, animal-friendly guy who thinks that corridas
> are a pure barbarism. But I refused myself the temptation to go and see
> one, because I am afraid that, all philosophy apart, I may discover
> that - after all - perhaps I adore the public slaughter of bulls?
>

Don't bother messing with corridas, do you adore the current stock market?
:)  Sorry, that one was just too tempting to pass over.

thx






From pyth at devel.trillke.net  Wed Sep 25 18:03:15 2002
From: pyth at devel.trillke.net (holger krekel)
Date: Thu, 26 Sep 2002 00:03:15 +0200
Subject: a python puzzle
In-Reply-To: ; from sabren@manifestation.com on Wed, Sep 25, 2002 at 05:42:40PM -0400
References: 
Message-ID: <20020926000315.K30315@prim.han.de>

Michal Wallace wrote:
> Here's a python puzzle. Solve it and you win a prize. :)
> 
> """
> Ha'f ahoy ad ayfa wdqr srxhekdpyr! H phmm zhby
> fhv odeajf dc cryy pys jdfahez ad ajy chrfa kyrfde
> ad fdmby ajhf irwkadzrxo. Ixe wdq chzqry ha dqa?
> 
> Fheiy wdq jxby axgye ow ijxmmyezy xet tyirwkayt
> ajy fyirya oyffxzy, H phmm ybye zhby wdq ajy
> irwkadzrxo-oxghez fdqriy idty ad xoxuy wdqr
> crhyetf!
> """
> hokdra fwf, farhez, rxetdo
> ihkjyr = mhfa(farhez.myaayrf[:26])
> rxetdo.fjqccmy(ihkjyr)
> ihkjyr = "".ldhe(ihkjyr)
> ihkjyr += ihkjyr.qkkyr()
> oxk = {}
> cdr kmxhe, irwka he uhk(farhez.myaayrf, ihkjyr):
>     oxk[kmxhe] = irwka
> cdr mhey he dkye(fwf.xrzb[1]):
>     krhea "".ldhe([oxk.zya(ij,ij) cdr ij he mhey])[:-1]


OK.  something like 

def decrypt(yourstring):
    dedict = {'F': 'S', 'I': 'C', 'H': 'I', 'a': 't', 'c': 'f', 'b': 'v', 'e': 'n',
    'd': 'o', 'f': 's', 'i': 'c', 'h': 'i', 'k': 'p', 'j': 'h', 'm': 'l',
    'l': 'j', 'o': 'm', 'q': 'u', 'p': 'w', 's': 'b', 'u': 'z', 't': 'd',
    'w': 'y', 'v': 'x', 'y': 'e', 'x': 'a', 'z': 'g', 'g': 'k'}
    return "".join([dedict.get(i,i) for i in yourstring])

returns 

    """
    It's time to test your brainpower! I will give
    six months of free web hosting to the first person
    to solve this cryptogram. Can you figure it out?

    Since you have taken my challenge and decrypted
    the secret message, I will even give you the
    cryptogram-making source code to amaze your
    friends!
    """
    import sys, string, random
    cipher = list(string.letters[:26])
    random.shuffle(cipher)
    cipher = "".join(cipher)
    cipher += cipher.upper()
    map = {}
    for plain, crypt in zip(string.letters, cipher):
        map[plain] = crypt
    for line in open(sys.argv[1]):
        print "".join([map.get(ch,ch) for ch in line])[:-1]


but i don't know if i need free webhosting :-)

regards,

    holger



From loewis at informatik.hu-berlin.de  Fri Sep  6 10:20:45 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=)
Date: 06 Sep 2002 16:20:45 +0200
Subject: Difference between static method and a function as a class attribute?
References: 
Message-ID: 

Gon?alo Rodrigues  writes:

> What are the differences, if any, between 1 and 2?

In 1, test.funtest will be an unbound method; in 2, it will be a
function.

> And if there are any differences do they really matter, that is, does
> anybody has any test cases where 1 and 2 are not interchangeable?

Sure:

def m():
    print "called ::m"
class t1(object):
    method = m

class t2(object):
    def m():
        print "called t2::m"

    method = staticmethod(m)

t2.method()
t1.method()

gives

called t2::m
Traceback (most recent call last):
  File "a.py", line 13, in ?
    t1.method()
TypeError: unbound method m() must be called with t1 instance as first argument (got nothing instead)

Regards,
Martin


From joconnor at cybermesa.com  Mon Sep  9 12:29:08 2002
From: joconnor at cybermesa.com (Fearless Freep)
Date: 9 Sep 2002 09:29:08 -0700
Subject: None or 0
References:   <3d7a2b6b.92959728@news.cybermesa.com> 
Message-ID: <7d3dc526.0209090829.2caf4b6b@posting.google.com>

John Baxter  wrote in message news:...
> In article <3d7a2b6b.92959728 at news.cybermesa.com>,
>  joconnor at cybermesa.com (Jay O'Connor) wrote:
> 
> > >Go into (English-speaking) classrooms, and you're going to hear chants 
> > >of "5 and 1 is 6" not "5 and 1 is 1".
> > 
> > Because in that contexts "and" means "plus" and in this context "and"
> > means "logical and"
> 
> Agreed and understood.  But not helpful to the programming for everyone 
> cause.

Not really.  People also understand "and" meaning a logical and as
well.  "I want the shirt that is read and size 4" or whatever.  "And"
just means that you want to combine two things, whether numbers or
conditions.  It's an ambigious concept  that people use all the time
and let the context indicate what is meant.

Of course, when we try to build that ambiguity into computer languages
and allow context to determine meaning, we usually get into trouble :)

Then again, we keep a lot of lawyers employed for the same reason when
such ambiguity causes problems in human language.

I don't think "and" as a "logical and" and not as "plus" is really a
problem in Python for non-programmers to deal with

Take care,
Jay


From loewis at informatik.hu-berlin.de  Mon Sep  9 05:22:46 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=)
Date: 09 Sep 2002 11:22:46 +0200
Subject: Howto debug self?
References: 
Message-ID: 

Oliver Eichler  writes:

> Is it possible to debug self with pdb? I mean it in the sense of getting a 
> list of vars and their values. 

If you print dir(self), you will get the names instance attributes. If
you print self.__dict__, you will get the instance dictionary.

HTH,
Martin


From kroc at blueyonder.co.uk  Fri Sep 27 05:42:38 2002
From: kroc at blueyonder.co.uk (Keith O'Connell)
Date: Fri, 27 Sep 2002 09:42:38 GMT
Subject: How do you pronounce "__" (double underscore)?
References: <525eaba.0209260956.72bf6786@posting.google.com>
Message-ID: <87wup793aq.fsf@smtp.blueyonder.co.uk>

>>>>> "Pat" == Pat Notz  writes:

         @ = "at"
         ! = "bang"
         . = "dot"
         * = "star"

    Pat> Is there a short (one or two syllable) pronounciation for
    Pat> "__" (double underscore).  "Underscore underscore" and
    Pat> "double underscore" are kind of long.  Somthing like "splat"?
    Pat> Anyone?

        "Skid"
                        It's a skid mark!

-- 
Keith.
 [Debian Woody & Python 2.1.3]


From member at dbforums.com  Fri Sep 13 05:37:36 2002
From: member at dbforums.com (hpyhpy)
Date: Fri, 13 Sep 2002 09:37:36 +0000
Subject: Dynamic loading of c modules,question.
Message-ID: <1810446.1031909856@dbforums.com>

hi,everybody:

I'm puzzled about SWIG.

On sco openserver5,I try swig's example:

/****************************/
example.c

/* File : example.c */

/* A global variable */
double Foo = 3.0;

/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
int g;
g = y;
while (x > 0) {
g = x;
x = y % x;
y = g;
}
return g;
}
/****************************/
example.i

/* File : example.i */
%module example

extern int    gcd(int x, int y);
extern double Foo;
/****************************/
And I do :
#gcc -c example.c
#swig -python example.i
#gcc -c example_wrap.c -I/usr/local/include/python2.2/
#gcc -G -Wl example.o example_wrap.o -o _examplecmodule.so

Then it has these files:
example.c
example.i
example.o
example_wrap.c
example_wrap.doc
example_wrap.o
_examplecmodule.so

So I wonder where is the "example.py"???
So I can't "import example"

Traceback (most recent call last):
File "", line 1, in ?
ImportError: No module named example

*_*   *_*   *_*

Who can tell me why,please help me,I'm a tyro^_^
Thank!

--
Posted via http://dbforums.com



From sholden at holdenweb.com  Wed Sep 18 12:32:59 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Wed, 18 Sep 2002 12:32:59 -0400
Subject: timeoutsocket module help
References: 
Message-ID: 

"Sheila King"  wrote ...
> OK, I'm doing DNS lookups in a script I've written, to determine whether
> certain IP addresses are listed in DNS BL lists (for blocking spammers).
>
> Have been using the code I've written for a long time now (months) without
> significant problems. However, someone has made the point to me, that my
> code should technically have a default timeout on the socket that tries to
> do the DNS lookup. And they are right, so I'm trying to modify my code.
>
> So, I'm using Tim O'Malley's timeoutsocket module, or trying to. But I am
> not having any success with this. In the following C&P from an interactive
> session, it took 6 or 7 seconds to return the socket error, which is the
> result I would expect in the case that the host name is not in the DNS
list
> (and in this case it is not, so this is a correct result). The problem is,
> that I set the default time out (I thought???) to 0.02 seconds, but the
> lookup went waaaayyyy past that and basically seemed to ignore the
> instruction.
>
> >>> import sys
> >>> import socket
> >>>
sys.path.append(r'j:\web\thinkspotwebsite\xthinkspot\emailfilter_test')
> >>> import timeoutsocket
> >>> timeoutsocket.setDefaultSocketTimeout(0.02)
> >>> socket.gethostbyname('226.200.3.4.bl.spamcop.net')
> Traceback (most recent call last):
>   File "", line 1, in ?
>     socket.gethostbyname('226.200.3.4.bl.spamcop.net')
> gaierror: (7, 'getaddrinfo failed')
> >>>
>
> Now, I will note, that the comments in the timeoutsocket module indicate
> that it works for TCP connections, and I'm not sure that TCP is being used
> in the gethostbyname function, as it is my understanding that DNS should
> usually be done by UDP instead. So, maybe in this case, using O'Malley's
> timeoutsocket module is totally inappropriate and won't work.
>
> In any case, I'm hoping to get some clues here.
>
You are correct in noting that the timeoutsocket module won't help if you
use UDP, which by default is used for DNS. I found it was actually quite
easy to effect my own timeouts and do my own DNS lookups -- in my case,
looking for MX records, but there's no reason why you shouldn't extend it to
others. The dnslib module is an immense help here.

Here's some sample code that uses it, and uses select.select() to apply a
fifteen-second timeout to the DNS transaction. I'm afraid the code is
missing a lot of context:

def MXlist(qname, server):
    """Return a list of MX exchangers for a given domain.

    This code is based on the dnslib library, and  is complicated
    by the necessity to handle UDP errors where no response is
    generated by (or at least received from) the remote host."""
    global mxdict       # Cacheing dictionary
    if mxdict.has_key(qname):
        lf.log("[[[ Domain %s MX hosts were cached" % (qname, ))
        return mxdict[qname]
    protocol = 'udp'    # This is bogus: not used anywhere!
    port = 53
    opcode = dnsopcode.QUERY
    rd = 1              # server should recurse
    qtype = dnstype.MX
    m = dnslib.Mpacker()
    m.addHeader(0, 0, opcode, 0, 0, rd, 0, 0, 0, 1, 0, 0, 0)
    m.addQuestion(qname, qtype, dnsclass.IN)
    request = m.getbuf()
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.setblocking(0) # We need a non-blocking socket
    s.connect((server, port))
    r, w, e = select.select([s], [s], [s], 15)
    if [r, w, e] == [[], [], []]:
        lf.debug("!!! Connect timed out in MXlist")
        return []
    s.send(request)
    r, w, e = select.select([s], [s], [s], 15)
    if [r, w, e] == [[], [], []]:
        lf.debug("!!! Send timed out in MXlist")
        return []
    r,w,e = select.select([s], [], [], 15.0)
    if r:
        reply = s.recv(2048)
    else:
        s.close()
        raise Timeout("Recv timed out in MXlist")
    u = dnslib.Munpacker(reply)
    (id, qr, opcode, aa, tc, rd, ra, z, rcode,
        qdcount, ancount, nscount, arcount) = u.getHeader()
    for i in range(qdcount):
        qname, qtype, qclass = u.getQuestion()
    MX = []
    for i in range(ancount):
        name, type, klass, ttl, rdlength = u.getRRheader()
        MX.append([u.get16bit(), u.getname()])
    MX.sort()
    servers = []
    for mx in MX:
        servers.append(string.lower(mx[1]))
    s.close()
    mxdict[qname] = servers
    lf.log("[[[ %d candidate mail exchangers for %s: %s" %
                (len(servers), qname, string.join(servers, ", ")))
    return servers

Hope this is enough to get you going.

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------





From nospam at bigfoot.com  Tue Sep 24 18:38:30 2002
From: nospam at bigfoot.com (Gillou)
Date: Wed, 25 Sep 2002 00:38:30 +0200
Subject: List/Tuple bug or feature?
References: <8765wv6o0d.fsf@nospam.eml.cc>
Message-ID: 

"Mahesh Padmanabhan"  a ?crit dans le message de news:
8765wv6o0d.fsf at nospam.eml.cc...
>
> Hi,
>
> I spent a lot of frustrating hours tracking this down and I am
> confused as to why I see this behavior.
>
> >>> x = ('a' 'b')
> >>> x
> 'ab'
>
> >>> x = ['a' 'b']
> >>> x
> ['ab']
>

It's a feature that may be helpful for making long strings without '\n' in
it (i.e. long regexps with comments).

 longstring = (
  'this is long ' # the first
...
  'this is long '
  'this is long ' # the hundredth
  'this is long ')

Have a look at the tutorial (don't remember where exactly)

--Gilles





From aglyportREMOvethispart at nospam.yahoo.com  Tue Sep  3 23:33:14 2002
From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph)
Date: Tue, 03 Sep 2002 20:33:14 -0700
Subject: Memory fault - core dumped   while compiling 2.2.1 on SCO
Message-ID: <3D757EFA.9050401@nospam.yahoo.com>

gcc: file path prefix `dynamic' never used
cc -G -KPIC -Ki486 -belf -Wl,-Bexport 
build/temp.sco_sv-3.2-i386-2.2/timemodule.o -L/usr/local/lib -lm -o 
build/lib.sco_sv-3.2-i386-2.2/time.so
/bin/sh: 19686 Memory fault - core dumped
gmake: *** [sharedmods] Error 139
Tue Sep  3 19:56:22 PDT 2002 bongo:/u5/src/Python-2.2.1 $

I removed build/lib.sco_sv-3.2-i386-2.2/time.so
and tried again: got the same result.

Any ideas?



From cotabas at earthlink.net  Tue Sep  3 21:47:55 2002
From: cotabas at earthlink.net (CotaBas)
Date: Wed, 04 Sep 2002 01:47:55 GMT
Subject: Newby Question: os.rename
References:  
Message-ID: 

>
> "Kevin Bass"  wrote in message
> news:AcGc9.68214$Xa.3523883 at twister.southeast.rr.com...
> > I am attempting to create an archive function within my program. This
> > function should create a directory with a timestamp name (such as
> > /home/oracle/data/20020831) on the fly, list the contents of a current
> > directory then place the contain from the previous directory into the
> newly
> > created directory.
> >
> > The newly created directory with the timestamp name is being created and
> the
> > list of files from the current directory has been retrieved but my
problem
> > comes when moving the files to the newly created directory. I am trying
to
> > achieve this tasks with os.rename but find it difficult to get the
command
> > to recognize the new directory and place the files into it.
> >
> > I have attempted to get os.rename to recognize the 'archloc' variable
that
> > contains the name of the newly created directory but that did not work.
I
> > also tried to join the newly created directory with the file names then
> send
> > it through os.rename and that did not work either.
> > What am I doing wrong? Thanks!! (My code is listed below)
> >
> >
> > def archive_data(archive):
> >
> >    the_date = strftime("%Y%m%d")
> >    archloc = ('/home/oracle/data/' + the_date)
> >    os.mkdir(archloc)
> >
> >    if archive == 'yes':
> >       for file in os.listdir('/home/oracle/data'):
> >          file2 = os.path.join(archloc, file)
> >          #print file2
> >    os.rename(r'/home/oracle/data/' + file, file2)
> >
> > Kevin
> >
> >
> >
> >
>
> I have figured it out. Thanks!
>
>
>

LOL if you wait long enough people solve there own problems....








From gerhard.haering at opus-gmbh.net  Tue Sep 17 14:28:34 2002
From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: 17 Sep 2002 18:28:34 GMT
Subject: CGI question
References: 
Message-ID: 

In article , John D. Boy wrote:
> Hello there!
> 
> I am working on a simple CGI script to use as a framework for a website
> of mine. Basically, I want it to work as follows: When somebody accesses
> the site, a CGI (called e.g. index.py) is run. It takes an html-template
> and fills it with content from another file, called e.g. index.dat, and
> returns the completed html-document. When I want to present another
> page, I want the url to look like this: http://my.domain.name/?page. In
> that case, index.py would fill the same template with the content of a
> file called e.g. page.dat. 
> 
> Now, my problem is to find out what follows behind the question mark in
> my CGI script. Unless the key has a value
> (http://my.domain.name/?key=value), it is not in the cgi.FieldStorage
> dictionary. Is it simply impossible, or am I not using the right
> function calls? 

You need to configure your webserver to rewrite URLs from your desired form to
the "/scriptname?key=value form" . I believe the relevant Apache module is
called mod_rewrite.

-- Gerhard


From rsrchstr at msn.com  Sun Sep 29 19:40:24 2002
From: rsrchstr at msn.com (mike henley)
Date: Mon, 30 Sep 2002 00:40:24 +0100
Subject: idea for a much needed application
References: <576c1752.0209291326.56dcdf31@posting.google.com> 
Message-ID: 

"TGOS"  wrote in message
news:pasepuc0r73mh5vlcsu1l7erl4e2b17qvi at 4ax.com...
>
> On 29 Sep 2002 14:26:05 -0700 rsrchstr at hotmail.com (mike henley) wrote
> in comp.lang.java.programmer:
>
> > I remember a while ago reading about tim burners-lee and how his
> > vision of the WorldWideWeb as a medium where all can freely and easily
> > publish information [...]
> > Hosts are either expensive or limit you in terms of what
> > languages, modules, applications, and OSs you can use.
>
> To publish information, all you need is writing it into a HTML file and
> a server that hands out the HTML file when getting asked for it.
> You
> don't need any special languages, modules or applications on the server
> to publish your information, other than the ones already present on a
> web-server.

"other than the ones already present on a web-server", exactly! i want to be
ably to use whatever language, modules or applications i choose, and over
the year use others, freely. if i choose perl, php, or even python, ruby or
tcl, then i want to be able to do that. if i want to use mysql or something
else that i prefer, then i want to have the freedom to do that. i do not
wish to be restricted by the "ones already present on a web-server". i do
not want to end up in a catch 22 situation, should i choose a good deal on a
host, and then choose applications within the limits of what it allows me,
or choose applications, and try to find a host that'll provide a good deal.


>
> Despite that, he has not said that you can publish information without
> having banners on the page placed their by your webhost. It's very easy
> to get free webspace if all you want to do is to keep some text online.

Agree, if that's all you want, but beyond keeping some text online, it's
difficult.

>
> Despite that, my webhost does not limit me in language, module or
> application, as long as it's not a permanent background process and does
> not keep any ports permanently open or permanently stays connect to a
> server (IRC bot and the like). In every other case, as long as I can get
> it running on the server and it doesn't swallow so much CPU time, that
> other customers suffer, I'm free to use it. This means I can even
> compile my own script interpreter on the server and use if I like.
> Therefor it's not free of course.
>
> > They also limit you in terms of space,
>
> He said you can "freely and easily publish information", he didn't say
> "infinite information". Limit yourself to information not already
> provided somewhere else. If it is already provided somewhere else, link
> there. That's how the WWW works, my friend.

my post is not about tim-burners lee or what he said.

>
> How are they going to finance their service, if everyone can eat up all
> space alone, leaving nothing for the rest?

my post is also not about the economics or politics of hosting; this sounds
much like the open source vs proprietary software arguments.

>
> > bandwidth used per period,
>
> Same as above.
>
> > number of executions of CGIs...
>
> Never heard of anything like that.

i never heard of it before i carefully read the terms and conditions of some
popular hosts.

>
> > I wish i can just use my own computer, with whatever technologies I
> > choose, keeping my content that i build up over time safe here on my
> > own machine,
>
> Actually my webhost makes a backup on a weekly basis of all data on the
> server. I have never made any backup of 90% of all my data so far. So
> it's a lot less safe on my own PC. Leaving aside that my own PC runs
> Windows, which is certainly a less safe OS than Solaris IMHO.
>
> Also keep in mind that my PC is for working, and I can't use it for
> working if it permanently has to fulfill HTTP requests of some surfers,
> that not just eat up plenty of my RAM, waste plenty of my CPU time, but
> also eat up nearly all my Internet bandwidth, so I can't even take a
> look at the latest news online anymore.
>
> > but unless you have a broadband connection this is not
> > possible. It may be possible using a dynamic DNS provider,
>
> Later below you wrote that you are on dial-up. How does a dynamic DNS
> provider compensate the fact, that your connection is way too slow,
> because you have no broadband? That makes no sense.
>
> Also I think there are still free DynDNS provider, they only ask you to
> "donate" some money and if nobody donates, they will go off-line again.
> But you are not forced to pay them.
>
> > most importantly, there's no way for others to know when you get
> > online.
>
> IRC, ICQ, AIM... the list is endless.

Yes, that is what my post is about, combining instant messaging presence
with dynamic DNS.

>
>  
>
> > So instead  of giving others a URL I can just give them an IM
> > username they can add to their client, and when i go online,
> > through my humble dial-up connection that changes IP whenever i
> > log in, they'll be aware of my presence, and be able to connect
> > to a server i host on my machine.
>
> Allow users to see your IP address when you are connected to an IRC
> network or to ICQ for example, then they can enter your IP address into
> their browser address bar and will get a webpage if you run a webserver
> and are not behind a firewall that blocks port 80.
>

Perhaps it can be possible to do a little application to automate this.

>  
>
> > Perhaps it can use existing open-source platforms, such as
> > jabber or gnutella,
>
> > The more automated it is, and the easier it is, the better.
>
> Use an IRC bot on your system,

I'll try that. I still think it can probably be easy to do an application
that combines dynamic DNS with instant messaging presence, say on popular
networks such asw AIM and MSN, as an add-on to say trillian or jabber, so it
would be much easier than IRC. (IRC is messy)




From mark at mceahern.com  Fri Sep 20 13:06:01 2002
From: mark at mceahern.com (Mark McEahern)
Date: Fri, 20 Sep 2002 12:06:01 -0500
Subject: average?
Message-ID: 

I know I can average a sequence like this:

  def average(seq):
    return reduce(operator.add(seq) / len(seq))

Yes, I see that will raise ZeroDivisionError if seq == [].  Aside from that,

1.  Is there anything else dumb about the above?
2.  Am I missing a builtin cousin of min, max that would do this for me?

Oops, maybe the answer to 2 is:

  import Numeric
  Numeric.average(seq)

I guess I just answered my own question.

Cheers,

// m




From psage at ncaustin.com  Mon Sep 23 23:57:06 2002
From: psage at ncaustin.com (Paul Sage)
Date: Mon, 23 Sep 2002 22:57:06 -0500
Subject: Outlook 2002 and Python
Message-ID: <03F53405C6ED434A986221919785A6A78C9339@nca-postal.ncaustin.com>

What:  I saw an idea for a way to create a good SPAM filter for email.  

How: I would like to try to implement the algorithm in Python.

Why:  I am trying to get familiar with Python, as I will be using it at
work quite a bit, and would like to keep my skills honed.

Where:  Windows XP and Outlook 2002

Okay, so smart people would say, "just go use Visual Studio or Visual
Basic," I suppose.  I don't know those two languages either, and they
might be the right tools for the job.  However, that would defeat the
point of trying something in Python.  Doing something else probably
wouldn't be as useful to me personally.

Does anyone know how and where in the world I would even start to try to
write some kind of addin for Outlook 2002 in Python?   I don't even know
how to start the project currently, and I am turning here first. 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From bobx at linuxmail.org  Sun Sep 15 15:16:22 2002
From: bobx at linuxmail.org (Bob X)
Date: Sun, 15 Sep 2002 19:16:22 GMT
Subject: [ANN] PySQLite 0.3.0 released
References: 
Message-ID: 

sismex01 at hebmex.com wrote:

> 
> 
> Yeesh! You had to quote the whole message just to
> add two words?
> 
> :-(
> 
> -gus

My bust on that one. I usually do a  like I did above. Sorry bout dat.

On that note...your two paragraph sig is okay right?  ; )

Bob



From phr-n2002b at NOSPAMnightsong.com  Mon Sep 16 03:22:18 2002
From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin)
Date: 16 Sep 2002 00:22:18 -0700
Subject: Source code
References:    <37fh9.112911$pX1.4044383@news2.tin.it>
Message-ID: <7xk7lml7px.fsf@ruckus.brouhaha.com>

Alex Martelli  writes:
> > You'll have to give your customers a sealed computer and no permission
> > to install additional software, or communicate with the internet, if
> > you want to reliably prevent them from analysing your program.
> 
> Incidentally, the latter option can be feasible in certain situations: some 
> key parts of your program's functionality might reside on a computer you
> control, accessible to the rest of the application (installed more 
> traditionally on users-controlled computers) only as a black box via the 
> net.  XML-RPC, SOAP, and other distributed-computing approaches
> such as Corba, make implementing this particularly easy these days.

It doesn't have to be via the net: you can literally deliver a sealed
computer to the customer, with the sealing enforced by contracts and
inspections (this is quite normal, e.g. some financial applications
are delivered as a rack-mount box that you install in your machine
room) or by tamper resistant hardware (for higher security
applications).  For VERY high security, of course you can't let
hostile parties touch the hardware.  Nonetheless, the pay TV industry
deploys millions of sealed computers (smart cards) every year to
customers, every single one of which is considered an attacker.  While
that industry had spectacular early security failures, these days it's
a fairly solved problem and they limit losses to acceptable levels.

It doesn't sound like the OP was asking for this type of solution though.


From Padraig at Linux.ie  Wed Sep 11 08:25:17 2002
From: Padraig at Linux.ie (Padraig Brady)
Date: Wed, 11 Sep 2002 12:25:17 GMT
Subject: regular expression for space seperated quoted string
References:  
Message-ID: 

Eric Brunel wrote:
> Padraig Brady wrote:
> 
> 
>>Hi, I'm trying to split a string that is seperated
>>by spaces and also contains double quoted words which
>>can contain spaces:
>>
>>For e.g. using: re.split('[ ]*"?([^"]*)"?[ ]*', s1)
>>on this string: s1='1 "2" "thre e"'
>>gives:          ['', '1 ', '', '2', '', 'thre e', '']
>>
>>Problem with this is the '' entries, but this isn't too bad.
>>
>>However using the above re with: s2='1 2 "th ree"'
>>I get:                           ['', '1 2 ', '', 'th ree', '']
>>
>>any ideas?
> 
> 
> What about:
> 
>>>>p = r'[^ \t\n\v\f"]+|"[^"]*"'
>>>>re.findall(p, '1 2 3')
>>>
> ['1', '2', '3']
> 
>>>>re.findall(p, '1 2 "three"')
>>>
> ['1', '2', '"three"']
> 
>>>>re.findall(p, '1 "2" "thr ee"')
>>>
> ['1', '"2"', '"thr ee"']
> 
>>>>re.findall(p, '"yeah it seems to be working!" yeah it seems to...')
>>>
> ['"yeah it seems to be working!"', 'yeah', 'it', 'seems', 'to...']
> 
> It leaves the double-quotes around the values, but they can be removed 
> quite simply...
> 
> I also tried to use look-ahead and look-behind features in re's, but it 
> doesn't have the expected result:
> 
> 
>>>>re.findall(r'(?<=")[^"]*(?=")|[^ \t\n\v\f"]+',
>>>
>         '"yeah it seems to be working!" yeah it seems to...')
> ['yeah it seems to be working!', 'yeah', 'it', 'seems', 'to...']
> 
>>>>re.findall(r'(?<=")[^"]*(?=")|[^ \t\n\v\f"]+', '1 2 3')
>>>
> ['1', '2', '3']
> 
>>>>re.findall(r'(?<=")[^"]*(?=")|[^ \t\n\v\f"]+', '1 "2" "thr ee"')
>>>
> ['1', '2', ' ', 'thr ee']
> 
> The " " between 2 and three is also matched...
> 
> HTH

thanks. Yes findall is probably more appropriate:
Also there is a canonical perl soultion for this,
search for split in: http://www.perldoc.com/perl5.6/faq/perlfaq4.html

P?draig.



From buzzard at urubu.freeserve.co.uk  Thu Sep 26 20:58:58 2002
From: buzzard at urubu.freeserve.co.uk (Duncan Smith)
Date: Fri, 27 Sep 2002 01:58:58 +0100
Subject: This is driving me insane!
References:  
Message-ID: 

> It isn't.  self.errorlog is a list containing self.grouptotals.

I should have said it contains a reference to the same list referenced by
self.grouptotals, to be more accurate.  Creating the copy means the
reference contained in self.errorlog is to a different list than that
referenced by self.grouptotals.

Duncan




From jubafre at brturbo.com  Fri Sep 13 15:34:10 2002
From: jubafre at brturbo.com (jubafre at brturbo.com)
Date: Fri, 13 Sep 2002 16:34:10 -0300 (GMT-03:00)
Subject: transform list of int in a list of string??
Message-ID: <-2032200682.1031945650320.JavaMail.nobody@webmail1>

my program have other modules imported, like re and sre and i put a convertion int to str but doesn?t work
t=str(x[i])
Traceback (most recent call last):
  File "C:\Documents and Settings\jubafre\Desktop\montador\teste.py", line 78, in ?
    t=str(x[i])
TypeError: 'list' object is not callable

Why i can?t transform a int number in string in my program???
I tryed with import string, and can?t too, 
but if i start a new python shell it works, why??

python shell
>>> x=[1,2,3,4,]
>>> s=[]
>>> for i in range(len(x)):
	t=str(x[i])
	s.append(t)
>>> print s
['1', '2', '3', '4']



Juliano Freitas
www.gebrasil.hpg.com.br

From wlfraed at ix.netcom.com  Mon Sep 23 20:35:34 2002
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Mon, 23 Sep 2002 17:35:34 -0700
Subject: writing in a file as binary mode????
References: 
Message-ID: 

jubafre at brturbo.com fed this fish to the penguins on Monday 23 
September 2002 12:40 pm:

> i open the a file for writing in a binary mode, but doesnt work
> 
> final3=['0020 0000x9', '0030 0000xa', '00B4 0000x8', '0030 0000xb',
> '00F0', '0001', '0003', '0005'] destino=raw_input("Digite o nome do

        Pardon the KNode garbage wrapping...

        All those are just character strings, not binary data.

        First step would be to make that data binary...

        ... = [ 0x0020, 0x0000, 0x0030, ... 0x0005 ]


> arquivo .mem: ") f = open(destino,'wb')
> f.write('\x03AHM ')
> for i in final3:
>     f.write(i+' ')

        You won't be able to concatenate a space to what is now integer binary.



--
 > ============================================================== <
 >   wlfraed at ix.netcom.com  | Wulfraed  Dennis Lee Bieber  KD6MOG <
 >      wulfraed at dm.net     |       Bestiaria Support Staff       <
 > ============================================================== <
 >        Bestiaria Home Page: http://www.beastie.dm.net/         <
 >            Home Page: http://www.dm.net/~wulfraed/             <


From wurmy at earthlink.net  Tue Sep 10 00:22:10 2002
From: wurmy at earthlink.net (Hans Nowak)
Date: Tue, 10 Sep 2002 04:22:10 GMT
Subject: Python 2.3
References: <3d7cfc19_5@news.newsgroups.com>
Message-ID: <3D7D7410.4070000@earthlink.net>

JB wrote:
> Will rational numbers be implemented in Python 2.3? And when 
> is the first beta due?

There's a PEP, but it doesn't look like this will be in 2.3:

   http://www.python.org/peps/pep-0239.html

I don't know what the status of this PEP is, BTW... it's not deferred or 
rejected, which suggests this is still under consideration.

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html



From sholden at holdenweb.com  Mon Sep 16 08:12:26 2002
From: sholden at holdenweb.com (Steve Holden)
Date: Mon, 16 Sep 2002 08:12:26 -0400
Subject: Problem with HTTPS request
References:      
Message-ID: 

"Gerhard H?ring"  wrote ...
> Steve Holden wrote in comp.lang.python:
> > "Gerhard H?ring"  wrote ...
> > [complaints about crappy looking posts because of people using OE]
> > Gerhard:
> >
> > You're showing distinct signs of having too much time on your hands :-)
>
> Unlikely.
>
:-)
> > Can't you fix your brain instead so it will let you ignore other
> > people's mailer problems?
>
> Problems don't go away by ignoring them. People are so used to the
> postings in crappy form (I'm only talking about form, not content)
> offloaded by people like you that they need to be alerted to this from
> time to time.
>
"People like me". Aha, so now I've become a member of an abused minority?

> > an-unreconstructed-OE-user-myself-ly y'rs  - steve
>
> I wonder why some programmers who insist on proper form of source code
> don't care at all about the email/news messages they send to the
> public, even though they know better.
>
> And sorry, the Microsoft way of defining crap as standard won't work
> with me.
>

Well, I don't think we disagree on the importance of presentation and
compliance with standards. I simply think you have to allow some leeway to
people who either a) may not know any better, or b) may not have a choice
about the mailer they use at work, for example.

Basically you're pissing in the wind. Microsoft *like* crap. Especially
*expensive* crap.

but-feel-free-to-continue-ly y'rs  -s teve
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------





From edream at tds.net  Mon Sep  2 13:45:35 2002
From: edream at tds.net (Edward K. Ream)
Date: Mon, 02 Sep 2002 17:45:35 GMT
Subject: Does IDLE handle unicode?
References: 
Message-ID: <3tNc9.2631$Ak.1173546@kent.svc.tds.net>

Thanks very much to all who so helpfully replied.  Sorry I didn't find this
on the FAQ.

Edward




From skip at pobox.com  Wed Sep 11 13:23:16 2002
From: skip at pobox.com (Skip Montanaro)
Date: Wed, 11 Sep 2002 12:23:16 -0500
Subject: Large file support and stat vs stat64 in extension modules
In-Reply-To: 
References: 
        
        
Message-ID: <15743.31748.559786.593812@12-248-11-90.client.attbi.com>

    >> Did you #include ?

    Ben> Yes, but perhaps I'm not including something else.  Here is a short
    Ben> program (test.c):

    ...

Dunno what else might be causing it.  I modified your program slightly:

    #define __USE_FILE_OFFSET64
    #include 
    #include 
    #include 

    main()
    {
      struct stat st;
      if (stat("/home/ben/work/big/bigfile", &st) != 0)
          perror("Error");
      else printf("OK\n");
    }

and ran it through gcc -E.  I expected the stat() call to be transformed,
but it wasn't.  Apparently, I don't have large file support builtin.  In
fact, I saw

    extern int stat (__const char *__restrict __file,
                     struct stat *__restrict __buf) ;

    extern int fstat (int __fd, struct stat *__buf) ;

in the output, suggesting that by the time that little bit of code in
sys/stat.h was executed __USE_FILE_OFFSET64 had been #undef'd.

-- 
Skip Montanaro
skip at pobox.com
consulting: http://manatee.mojam.com/~skip/resume.html



From skip at pobox.com  Mon Sep 30 11:55:04 2002
From: skip at pobox.com (Skip Montanaro)
Date: Mon, 30 Sep 2002 10:55:04 -0500
Subject: Python PAM module
In-Reply-To: 
References: 
Message-ID: <15768.29656.796965.23059@12-248-11-90.client.attbi.com>

    Larry> Hello, I am wondering if anyone can point me to the location of
    Larry> the Python PAM module. My google searches turn up references to
    Larry> www/ftp.pangalactic.org, but this site seems down.

You might get lucky with a little effort and locate it at Alexa's Wayback
Machine:

    http://www.archive.org/

-- 
Skip Montanaro - skip at pobox.com
"Airplanes don't fly until the paperwork equals the weight of the
aircraft. Same with i18N." - from the "Perl, Unicode and i18N FAQ"



From andrew.thompson at ashecastle.com  Thu Sep 19 05:11:13 2002
From: andrew.thompson at ashecastle.com (Andrew Thompson)
Date: Thu, 19 Sep 2002 10:11:13 +0100
Subject: lists in dictonaries ?
In-Reply-To: <20020919074722.GB77021@partagas.as.de.cw.net>
Message-ID: <007401c25fbc$81ed2d10$4802a8c0@blair>

You can put any python objects into a python dictionary, even the
dictionary itself...

For example :

aList=[1,2,3,4]
anotherList=[4,5,6,7]

aDictionary={}

aDictionary['foo']=[aList,anotherList]

Then...

aDictionary['foo'][0] answers aList

aDictionary['foo'][1] answers anotherList


Andrew

-----Original Message-----
From: python-list-admin at python.org [mailto:python-list-admin at python.org]
On Behalf Of Manuel Hendel
Sent: 19 September 2002 08:47
To: Python List
Subject: lists in dictonaries ?

Is it possible to put lists in dictionaries? And is it also possible
to put multiple lists in a dictionary for one key?

Thanks,
    Manuel

-- 
I married beneath me. All women do. 
-Lady Nancy Astor, first woman member of the British Parliment  

-- 
http://mail.python.org/mailman/listinfo/python-list




From thoa0025 at mail.usyd.edu.au  Fri Sep 13 19:24:55 2002
From: thoa0025 at mail.usyd.edu.au (:B nerdy)
Date: Fri, 13 Sep 2002 23:24:55 GMT
Subject: html template system?
Message-ID: 

what are good templating systems avaliable for python?

ive been at http://zebra.sourceforge.org and the documentation is kinda sus.
zope DocumentTemplate is included with zope. but i want a smaller footprint
system.

what are my options? cheers




From gerson.kurz at t-online.de  Wed Sep 25 12:36:35 2002
From: gerson.kurz at t-online.de (Gerson Kurz)
Date: Wed, 25 Sep 2002 16:36:35 GMT
Subject: Outlook 2002 and Python
References:  
Message-ID: <3d91e570.13288093@news.t-online.de>

On Tue, 24 Sep 2002 04:37:52 GMT, Mark Hammond
 wrote:
>You would need to use the new Universal Gateway code (see 
>win32com\test\test_pycomtest.py) and create a server that implements 
>IDTExtensibility2.  From there, you should be able to use any of the VB 
>samples to move forward - all the params passed are standard COM 
>objects, so you should be able to do whatever you want.  You would also 
>need to get your head around COM events and how to connect to them from 
>Python, as addins are very much event based.

Maybe take a look at my 

http://p-nand-q.com/pynospam.htm

Its a C++ extension for outlook that embedds python (well, a fixed
python script anyway). Source included.

I like my pop3filter approach better: 

http://p-nand-q.com/e/pop3filter.html


From peter at engcorp.com  Sun Sep  1 01:28:49 2002
From: peter at engcorp.com (Peter Hansen)
Date: Sun, 01 Sep 2002 01:28:49 -0400
Subject: urllib bug?
References: 
Message-ID: <3D71A591.13B87F4A@engcorp.com>

Steve Clift wrote:
> 
> Is this *really* a urllib bug, or am I missing something blindingly obvious?
[snip failing example]
> Fails the same way with 2.1. Works OK with 1.5.2 and (IIRC) 2.0.

Works fine here, under Windows 98 SE:

Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> urllib.urlopen('http://www.python.org')
>
>>> f = urllib.urlopen('http://www.python.org')
>>> f
>

-Peter


From nas at python.ca  Thu Sep 26 11:37:13 2002
From: nas at python.ca (Neil Schemenauer)
Date: Thu, 26 Sep 2002 08:37:13 -0700
Subject: off topic -- spam assassin
In-Reply-To: <200209261407.g8QE76Wo028975@ratthing-b246.strakt.com>
References: <200209261407.g8QE76Wo028975@ratthing-b246.strakt.com>
Message-ID: <20020926153713.GA16671@glacier.arctrix.com>

Laura Creighton wrote:
> What's new for our side of the arms race?  

There is a lot of interest in Bayesian analysis right now.  The error
rates are impressively low.  Search for "bogofilter" or "spambayes".
I'm currently using "neilfilter.py" from the spambayes project with good
results.

  Neil



From franke at ableton.com  Tue Sep  3 16:52:20 2002
From: franke at ableton.com (Stefan Franke)
Date: Tue, 03 Sep 2002 22:52:20 +0200
Subject: Better tracebacks for exec and execfile
References: <3i99nusjbgpiepva9pkuv3mtl7equ7h88h@4ax.com> <87elcbm1ze.fsf@andreasen.org>
Message-ID: 

On 03 Sep 2002 19:12:21 +0200, "Erwin S. Andreasen"  wrote:

>compile won't let you specify a start line number: for that I simply
>added "\n" * start_line to the start of the evaluated string :)

Now this is clever! And thought much too straight-forward
to have it figured out by myself .

Thanks,
Stefan



From gerrit.muller at philips.com  Wed Sep 11 07:06:56 2002
From: gerrit.muller at philips.com (Gerrit Muller)
Date: Wed, 11 Sep 2002 13:06:56 +0200
Subject: function pointer
References:  
Message-ID: <3D7F23D0.F9E4E61A@philips.com>

<...snip...>

> and even better python has bound methods:
> 
> >>> class a:
>          def f(self, arg):
>              print arg
> 
> >>> a1=a()
> >>> a1.f
> >
> >>>
> 
> you can pass these functions and methods around and apply them
> as you wish. Very powerful.
> 
>     holger
Thank you for this hint. I did not know this. Although I don't see any
immediate applications it looks quite cool!

regards Gerrit
-- 
--------------------------------------------------------------------
Gerrit Muller                Philips Research Laboratories Eindhoven
Building:   WDC 2 - 007              Prof. Holstlaan 4
Phone: +31 40 27 45242               5656 AA  Eindhoven
Fax:   +31 40 27 45033               The Netherlands
mailto:gerrit.muller at philips.com
http://www.extra.research.philips.com/natlab/sysarch/index.html


From a-steinhoff at web.de  Sun Sep  1 14:56:13 2002
From: a-steinhoff at web.de (Armin Steinhoff)
Date: Sun, 01 Sep 2002 20:56:13 +0200
Subject: Psyco works with QNX6 ...
Message-ID: <3D7262CD.332A5D9A@web.de>

Hello,

 'Psyco' works also with QNX6!! See the performance tests below ....

# Python program without Psyco:
def hanoi(n):
        han_move("a", "c", "b", n)

def han_move(frm, to, also, n):
        if (n < 2):
                return frm, to
        else:
                return han_move(frm, also, to, n - 1), \
                                han_move(frm, to, also, 1), \
                                han_move(also, to, frm, n - 1)

i = 0
while i<10000:
        hanoi (8)
        i = i+1

# time python hanoi.py
   19.10s real    18.92s user     0.00s system
                  ^^^^^
----------------------------------------------------------------------------------------------------
# Python program with PSYCO:

#import the specialization compiler
import psyco   

def hanoi(n):
        han_move("a", "c", "b", n)

def han_move(frm, to, also, n):
        if (n < 2):
                return frm, to
        else:
                return han_move(frm, also, to, n - 1), \
                                han_move(frm, to, also, 1), \
                                han_move(also, to, frm, n - 1)

# specialize han_move
psyco.bind(han_move)

i = 0
while i<10000:
        hanoi (8)
        i = i+1

RESULT:

# time python psy_hanoi.py
    2.17s real     1.87s user     0.02s system
                   ^^^^
Python + PSYCO is 10 times FASTER !  Its nearly C speed ...


Regards

Armin


From fperez528 at yahoo.com  Mon Sep 30 21:14:19 2002
From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=)
Date: Mon, 30 Sep 2002 19:14:19 -0600
Subject: Reloading a module
References: 
Message-ID: 

Tom wrote:

> 
> I'm developing some python mini applets on a Mac (using os 9 and the
> 2.1.1 Python IDE), and I've found it impossible to delete and/or reload
> a module after making changes to the code during the
> debugging/verification process. Is there an easy and/or effective way to
> do this? If I execute:
> 
> del mymodule
> 
> and then execute a print dir(mymodule), it shows up as nonexistent.
> Then, when I execute:
> 
> import mymodule
> 
> followed by a print dir(mymodule), the changes do not show up.

In [1]: reload?
Type:           builtin_function_or_method
Base Class:     
String Form:    
Namespace:      Python builtin
Docstring:
    reload(module) -> module

    Reload the module.  The module must have been successfully imported 
before.

cheers,

f.


From claird at starbase.neosoft.com  Tue Sep 17 15:01:58 2002
From: claird at starbase.neosoft.com (Cameron Laird)
Date: 17 Sep 2002 14:01:58 -0500
Subject: Python GUI/graphics package recommendation?
References:  
Message-ID: 

In article ,
Kevin Altis  wrote:
>I don't think it is very nice to make your aunt do your programming for you
>, but she can see if the instructions below are easy enough to give
>PythonCard a try.
>
>http://pythoncard.sourceforge.net/installation.html
>
>There are some walkthroughs to help you along once you have everything up
>and running.
>
>ka
>
>"David Ehrens"  wrote in message
>news:Xns9288738D9E9EEnospamanytime at 216.148.227.77...
>> I am using Python 2.2 on Win32 for an AI class and would like to
>> be able to display a graphical representation of an agent-based
>> game I am developing. I have seen a number of GUI and graphics
>> packages for Python, and would appreciate some recommendations
>> since I really don't have the time to install, learn, and try all
>> of them.
>>
>> My main criteria are: (1) my great aunt should be able to install
>> it and immediately use it; (2) it should work with Win32; (3) it
>> should do menus and graphics.
>>
>> If it happens to be the #1 tool of its kind, that would be nice
>> too.
			.
			.
			.
Start with Tkinter, I'd think; it's part of the standard
Python installation, and it certainly "do[es] menus and
graphics", for at least a couple of senses of that phrase.
-- 

Cameron Laird 
Business:  http://www.Phaseit.net
Personal:  http://phaseit.net/claird/home.html


From bobx at linuxmail.org  Mon Sep 16 21:14:22 2002
From: bobx at linuxmail.org (Bob X)
Date: Tue, 17 Sep 2002 01:14:22 GMT
Subject: Python equivalent to perldoc?
Message-ID: 

In Perl you can run "perldoc warnings" and get the definition of what 
"warnings" does. Is there a equivalent in Python?



From lpgray at uop.com  Wed Sep 18 15:28:26 2002
From: lpgray at uop.com (Lee Gray)
Date: 18 Sep 2002 12:28:26 -0700
Subject: Python GUI app to impress the boss?
References: <96904b50.0209171305.6d65f574@posting.google.com> 
Message-ID: <96904b50.0209181128.63cd71f9@posting.google.com>

Chris Liechti  wrote in message news:...
> lpgray at uop.com (Lee Gray) wrote in 
> news:96904b50.0209171305.6d65f574 at posting.google.com:
> > My boss is pretty open-minded, but also needs to see something working
> > to be convinced Python is even a viable platform (he had never heard
> > of it).  Otherwise, .Net is a given, whether it's any good or not,
> > since corporate is MS all the way.
> 
> with python you have to choice of diffrent GUI libs. if you consider 
> wxWindows you can play around with the wxPython demo application that comes 
> with the download. on the other hand when you support win32 only the 
> win32all package has support for all the windows APIs and it has some 
> samples that get installed.
> 
> chris

I've been playing with wxWindows and Boa Constructor. wxWindows is
pretty darn cool and will make a good demo for him.  Boa looks good
but is still a bit rough (naturally, being alpha), but I'm looking
forward to future releases.

Thanks,
Lee


From huaiyu at gauss.almadan.ibm.com  Thu Sep 12 18:01:37 2002
From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu)
Date: Thu, 12 Sep 2002 22:01:37 +0000 (UTC)
Subject: Restricting methods in derived classes
References: 
Message-ID: 

Mark McEahern  wrote:
>[Huaiyu Zhu]
>> What I'm looking for is a way to say which methods from dict are inherited
>> in MyClass at the time the class is defined, without incuring a cost when
>> the methods are called.  Is this possible?
>
>Would something like this work?
>
>$ python
>Python 2.2.1 (#1, Jun 25 2002, 10:55:46)
>[GCC 2.95.3-5 (cygwin special)] on cygwin
>Type "help", "copyright", "credits" or "license" for more information.
>>>> class foo(dict):
>...     def not_defined(self, *args, **kwargs):
>...             raise NotImplementedError
>...     update = not_defined
>...
>>>> f = foo()
>>>> f['a'] = 1
>>>> f
>{'a': 1}
>>>> d = {'a': 2}
>>>> f.update(d)
>Traceback (most recent call last):
>  File "", line 1, in ?
>  File "", line 3, in not_defined
>NotImplementedError

I was hoping for a way to confirm wanted methods, because there are more
methods that I don't want.  But the above is good enough for preventing
obvious mistakes.  Thank you.

Huaiyu


From just at xs4all.nl  Thu Sep 12 03:02:34 2002
From: just at xs4all.nl (Just)
Date: Thu, 12 Sep 2002 09:02:34 +0200
Subject: iterators and generators, is this the Python Way???
References: <3D7FF921.2040305@one.net>
Message-ID: 

In article <3D7FF921.2040305 at one.net>,
 Michael Schneider  wrote:

> class FastFile:
>     def __init__(self, filename):
>         """ Read in entire file into memory"""
>         f = open(filename, 'r')
>         fileContents = f.read();
>         self.lines = fileContents.split('\n')
>         f.close()
>    
>     def  __iter__(self):
>         return self.fastFileGen()
> 
>     def fastFileGen(self):
>         for line in self.lines:
>                 yield line

I would write the __iter__ like so:

    def  __iter__(self):
        for line in self.lines:
                yield line

Same effect, less code...

Just


From kathuw at swbell.net  Thu Sep 26 01:27:31 2002
From: kathuw at swbell.net (Kat & Huw)
Date: Thu, 26 Sep 2002 00:27:31 -0500
Subject: curses troubles
Message-ID: <002a01c2651d$69dc56e0$0100a8c0@mshome.net>

Ok, problem.

I'm trying to take user entered data input and store it as a var.

inside an __init__ I have curses set up a window, and display some 
options. Then I use:
while 1:
    self.k = self.stdscr.ch()
    if self.k == ord('G'): do_this()
    elif self.k == ord('P'): do_another()
    elif self.k == ord('Q'): break

Now, when running this, if I hit either G or P, the applications closes as if I'd hit Q

any idea what I'm doing wrong here?

yours,
Huw
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From loewis at informatik.hu-berlin.de  Thu Sep 19 13:27:53 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=)
Date: 19 Sep 2002 19:27:53 +0200
Subject: debugging "Too many open files"
References:   
Message-ID: 

Alex Polite  writes:

> > I recommend you list /proc//fd/
> Thanks. This tells me that some of my processes have a LOT of files
> open, most of them pointing to /dev/hdc. Is this normal?

Depends on what you mean by "pointing to". It is extremely rare that a
process opens /dev/hdc, since that requires superuser permissions; I
know of no case where a program opens /dev/hdc more than once.

So by "pointing to", you probably meant something else. Care to
provide precise data? What did you do, how did the computer respond,
how do you interpret this response?

Regards,
Martin


From loewis at informatik.hu-berlin.de  Tue Sep 10 05:37:38 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=)
Date: 10 Sep 2002 11:37:38 +0200
Subject: Computing directory sizes problem
References:   
Message-ID: 

nmichael at yahoo.com (Neophytos Michael) writes:

> Python version is 2.2.1.  Windows localized version I am not sure. 
> The laptop was purchased in the US so it must be the defaul US
> version.  The filenames in question are mp3 files whose names are made
> up from greek characters (at least I see them as greek when listing
> the files with file explorer).  Any advice on how to adjust my system
> locale would be appreciated.

I can see that this makes problems. Unfortunately, you did not report
the Windows version:
- On XP, navigate to
   Control Panel, Regional And Language Options,
   Advanced, Language for Non-Unicode Programs.
  Set language to Greek. You may also set your location to Greek, but
  that might be irrelevant.
- On W2k, navigate to
   Control Panel, Regional And Language Options,
   General.
  Choose Greek.

In the long run, Python should support Unicode file names independent
of the system locale; this will happen in Python 2.3. If you want to
experiment, you can use the patch in

http://python.org/sf/594001

You'll need CVS Python for that, and MSVC. With those changes,
invoking os.path.walk with a Unicode directory name should give you
Unicode file names again, which you then can pass to os.stat.

Regards,
Martin


From imbosol at vt.edu  Mon Sep  2 15:08:47 2002
From: imbosol at vt.edu (Carl Banks)
Date: Mon, 2 Sep 2002 15:08:47 -0400
Subject: Making regex suck less
References: <3d725881.345921@news.t-online.de>   <1030962064.628232@ampungk.ozonline.com.au>
Message-ID: 

John La Rooy wrote:
> Carl Banks wrote:
>> Gerhard H?ring wrote:
>> 
>>>>which means the real time is not spent in the compile() function, but
>>>>in the match or find function. So basically, couldn't one come up with
>>>>a *human readable* syntax for re, and compile that instead?
>>>
>>>That's equally powerful? Most probably not.
>> 
>> Why not?  It won't be as fast, but it should be able to do anything a
>> regexp can do, and would be much more versatile.
> 
> I think the main problem is that *human readable* doesn't map really 
> well onto regular expressions.

Ridiculous.  If you can map human readable code into machine language,
then you can map human readable code into regular expressions.

Cryptic as they are, regular expressions are still systematic; thus it
is possible to systematically convert the cryptic regexp syntax into
more readable and consistent syntax.


> What would the equivalent of r"(.)(.)(.)\3\2\1"
> This means a "palindrome of 6 characters"
> But it is unlikely that the human readable processor would understand 
> that (isn't it??)

Nope.  You don't appear to appreciate the power of computers to
translate human readable text into comlicated internal data, and are
evidently forgetting that interpretters such as Python that do a much
more difficult translation of readable text.


> It would be more likely to look like this (I haven't put too much 
> thought into this)

No kidding.


> "anything,anything,anything,same_as_3rd,same_as_2nd,same_as_1st"
> or would you like to suggest something else?

How about:

pattern = Group(Any()) + Group(Any()) + Group(Any()) \
          + GroupRef(3) + GroupRef(2) + GroupRef(1)

There's no reason it has to be re.compile with a string.


[snip]
> 
> Sure there are some cases where the re is loaded with meta characters...

That's the idea, chief.  For a simple regexp like you gave above, it
would be overkill to use a human readable syntax.  And it would still
be overkill for many regexps more complicated that that.

But eventually, the regexps will become complicated enough that a more
human readable syntax is preferrable.  Not to mention that a human
readable syntax will be more versatile, when that is needed.


> hmmm
> OK is this about writing maintainable code or people not wanting to 
> learn all the ins and outs of re's?

Nope.  For me, this is about understanding that complicated regexps
could benefit from a more readable and consistent syntax, and that the
more consistent syntax could add a lot of power and versatility to
regexps.


-- 
CARL BANKS
http://www.aerojockey.com


From nospam at horvath.com  Sat Sep 28 16:32:24 2002
From: nospam at horvath.com (Bob Horvath)
Date: Sat, 28 Sep 2002 20:32:24 GMT
Subject: combining mailbox and email modules
References:    <1fj6jb2.62mx08f47amsN%fgranger@alussinan.org> 
Message-ID: 

James J. Besemer wrote:
> 
> Fran?ois Granger wrote:
> 
>> Bob Horvath  wrote:
>>
>>  
>>
>>> The problem is that it looks good to me.  I've played around with it, 
>>> and if I take out the MIME gunk (It actually is a Klez virus), it 
>>> parses ok.
>>>   
>>
>>
>> I have had difficulties with the handling of multipart message with the
>> email package. I did not found a solution yet.
>>
> My experience is that a lot of Spam violates Mime rules.  Often they 
> omit the end marker, I guess relying on EOF to terminate the message. 
> Then the python packages can't parse any of the remaining messages.
> 
> --jb
> 

I was assuming the mailbox package handled splitting things in to 
messages correctly.  The HeaderParser class seemed to solve it for 
me, but then I wasn't interested inparsing the body.



From kingprad at mail.com  Fri Sep 13 09:07:27 2002
From: kingprad at mail.com (Carl)
Date: 13 Sep 2002 06:07:27 -0700
Subject: [newbie] Buying an introductory/reference text
References: 
Message-ID: <668b76ce.0209130507.2a6ea225@posting.google.com>

There are quite a few online books to teach the basic syntax /
structure of python coding, such as How To Think Like a Computer
Scientist (just search for it).

The absolute best reference manual and guide is the Python Bible. I'm
at work and don't remember the authors' names. It's a big book that
introduces you to every major module with example code
(non-trivial...stuff like a threaded web crawler in about 20 lines).
Awesome reference manual - I use it every single time I sit down to
code, because the ease of learning something new makes me keep trying
new things in my code. It's $40, and worth every dollar.

Carl


From duncan at NOSPAMrcp.co.uk  Fri Sep  6 08:42:40 2002
From: duncan at NOSPAMrcp.co.uk (Duncan Booth)
Date: Fri, 6 Sep 2002 12:42:40 +0000 (UTC)
Subject: Dictionary...
References: <7ir8g7xqqk.fsf@enark.csis.hku.hk>
Message-ID: 

Isaac To  wrote in
news:7ir8g7xqqk.fsf at enark.csis.hku.hk: 

> After all, Python dictionaries are implemented by height balancing
> tree, so internally the needed data can be retrieved efficiently. 

I think you must be using a different implementation of Python than the 
rest of us. :-)

Python dictionaries are implemented using hash tables and have no implied 
order. Try creating a dictionary using complex numbers as keys if you don't 
believe me, then try sorting the keys of that dictionary.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?


From jb at cascade-sys.com  Sun Sep 29 03:35:38 2002
From: jb at cascade-sys.com (James J. Besemer)
Date: Sun, 29 Sep 2002 00:35:38 -0700
Subject: Getting started
References: 
Message-ID: <3D96AD4A.8080202@cascade-sys.com>

David LeBlanc wrote:

>In fact, the names of some Lisp funtions came from the machine registers of
>the same name: car (current address register) and cdr (current data
>register) are the only ones I recall offhand.
>

Yup.  It was from IBM's 709/7094 computer.

Some Lisps had a 3rd, "CSR" but I don't recall the name of the register. 
 Status?  Subroutine?

Being able to branch in yet a third direction did not add as much 
utility as the first two.  And it didn't translate as well to most other 
architectures.  

It was nevertheless implemented in one CDC Lisp I am aware of, where 60 
bit words and 18 bit addresses left plenty of room for 3 addresses (with 
bits left over) in a cell.

--jb

-- 
James J. Besemer		503-280-0838 voice
2727 NE Skidmore St.		503-280-0375 fax
Portland, Oregon 97211-6557	mailto:jb at cascade-sys.com
				http://cascade-sys.com	







From martin at v.loewis.de  Tue Sep 10 02:58:47 2002
From: martin at v.loewis.de (Martin v. Loewis)
Date: 10 Sep 2002 08:58:47 +0200
Subject: how to build wxPython w/ Sun's C++ compiler?
References:   
Message-ID: 

Skip Montanaro  writes:

> As for patches, it seems to me that distutils needs a generic way to
> override such settings (CC, CFLAGS, LDFLAGS, etc) via command line
> arguments, environment variables or ConfigParser files.  

This is true.

> It's not clear which way would be most Pythonic.

It would be Pythonic to honor the system conventions transparently. So
on Unix, environment variables should be considered; I don't know what
the conventions on other systems are (or whether the problem exists in
the first place). On Windows, you want a choice of using MSVC or gcc
or Borland C or ... This is already supported in a command line
switch, selecting the appropriate compiler class.

Regards,
Martin


From aleax at aleax.it  Fri Sep 20 05:34:31 2002
From: aleax at aleax.it (Alex Martelli)
Date: Fri, 20 Sep 2002 09:34:31 GMT
Subject: monetary applications [was: Python GUI app to impress the bos s?]
References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <7xk7lhb943.fsf@ruckus.brouhaha.com> <9Qzi9.117104$ub2.2497933@news1.tin.it> <7xd6r9uj2i.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin wrote:

> Alex Martelli  writes:
>> Using double binary floating-point, the result of 0.70 x 1.05 is
>> 0.73499999999999998667732370449812151491641998291015625; the result
>> should have been 0.735 (which would be rounded up to $0.74) but instead
>> the rounded result would be $0.73.
> 
> Interesting.
> 
>> Should your business get tax-audited, inspectors may take a dim view
>> of your shaving a cent off the sales tax due on each and every item
>> you sell to the public at $0.70 -- "I found it hard to imagine" how
>> rounding effects might affect the result (when the law specifies
>> rounding to the nearest cent and always rounding half cents up) may
>> not be an acceptable defense.
> 
> I don't think they ask or care whether you round up or down on
> individual 70 cent items.  They want to know the total value of the
> stuff you sold, and then the tax you pay is X percent of that total,
> for whatever your local value of X is.

And they have no problems with letting you claim to your customers
that their sales tax is M cents when it's really N cents, N != M ...?

Wow -- your jurisdiction must be far laxer than ones I've dealt with.

Around here, if you assert the tax is M, and thus have the customer
pay an extra M, it HAD BETTER be M -- doing otherwise could be
constituted as fraud (depending on circumstances).

Say that you publish the erroneous information that each phone
call is $0.70 plus $0.03 sales tax for a total of $0.73.  Sales
tax is actually $0.04.  Now, a customer makes 100 calls.  Do
you charge them $74 explaining that 100 times 73 cents is 74
dollars?  Or do you charge $73 and eat the dollar loss yourself?
And even then, your tax books won't balance without fiddling --
even if the unbalance is against your interests, as in this case,
it's _still_ illegal (at least around here)... double-entry tax
book-keeping is supposed to balance to the last cent.

But what you said were that you had a hard time imagining any
commercially significant computation being off by a whole penny
(which, I imagine, means a whole cent) by using IEEE double
(binary floating point).  Surely this one example IS enough to
jog your imagination?  Surely it would not be a _mistake_ for
the rest of the program to sum up net-of-tax amounts and taxes
separately, item by item, rather than summing up just the
net-of-tax amounts and then recomputing overall tax based on
that -- then, the overall amount of tax computed and paid to
the authorities might be off by 1 cent per phone call billed,
which can sum up to quite a pretty sum (smacks of the "salami
slice fraud" to me, in fact).


Alex



From mfranklin1 at gatwick.westerngeco.slb.com  Wed Sep 18 12:20:02 2002
From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin)
Date: Wed, 18 Sep 2002 16:20:02 +0000
Subject: Tkinter:select directory dialog?
In-Reply-To: <20020918105332.00910.00007029@mb-ch.aol.com>
References: <20020918105332.00910.00007029@mb-ch.aol.com>
Message-ID: <200209181620.02942.mfranklin1@gatwick.westerngeco.slb.com>

On Wednesday 18 Sep 2002 2:53 pm, Park997 wrote:
> Hi,
> I have written an application that reads in several data files located in a
> single directory. Currently the directory is hard coded in a module as a
> string variable. On other computers, the data may be located in other
> directories. Is there a Tkinter dialog for choosing a directory, but not
> picking a file to open or write to? An entry field could be OK, but that
> would involve typing in a path, and probably validity checking, etc. A nice
> graphical "choose a directory"  Dialog would help. Does such a thing exist?
>
> Thanks,
>
> Wendell Cropper

from tkCommonDialog import Dialog
class Chooser(Dialog):
    command = "tk_chooseDirectory"
    def _fixresult(self, widget, result):
        if result:
            self.options["initialdir"] = result
        self.directory = result # compatibility
        return result

def askdirectory(**options):
    return apply(Chooser, (), options).show()






-- 
### Python Powered Signature
I started writting this email on 
Wed Sep 18 16:18:44 2002




From member at dbforums.com  Mon Sep 16 21:22:23 2002
From: member at dbforums.com (hpyhpy)
Date: Tue, 17 Sep 2002 01:22:23 +0000
Subject: Anyone can tell me why?
References: <1815200.1031973626@dbforums.com> <1817360.1032087013@dbforums.com> 
Message-ID: <1822798.1032225743@dbforums.com>

Originally posted by Andy Salnikov
> "hpyhpy"  wrote in message
> news:1817360.1032087013 at dbforums.com"]news:1817360.1032087013 at dbforum-
> s.co-
> m[/url]...
> > But I try,change the filename as "example.so","_example.so",
> > "examplemodule.so",#_#,same error......have other advise?^_^
>
> 1. You run python from directory different from where your .so
>    lives in. Python finds everything in the well-defined places, which
>    includes local directory. From python prompt type:
>
> >>> import sys
> >>> print sys.path
>
>   to see the list of directories where python can find a module. Do
>   not
>   put your module outside of any directory in this path.
>
> 2. Your python was built without support for dynamic loading. Don't
>    know how to check this. Ask the person who installed/configured
>    your python.
>
> 3. Shared library was not build correctly. I'm not familiar with SCO
>    but usually with gcc I do 'gcc -shared object.o -o whatever.so' and
>    that
>    works.
>
> 4. Whatever else....
>
>   Andy.


Yeah,thank you for these advise.

I suppose it may associate with the second point you said,I download
python 2.xx,as GNU,./configure,./make,it can't install on sco,so I use
python 1.5 .

And swig is same thing,last I use v1.1.Somebody tell me I shall check
the compiler and python and swig should be same----Oh,I can't believe :

When compile python ,system use GCC,and compile swig,it use CC(sco
with it self).

I change it and ok^_^

--
Posted via http://dbforums.com



From sismex01 at hebmex.com  Thu Sep 19 10:09:19 2002
From: sismex01 at hebmex.com (sismex01 at hebmex.com)
Date: Thu, 19 Sep 2002 09:09:19 -0500
Subject: strong/weak - dynamic/static [Was: Getting started]
Message-ID: 

> 
> Sorry to go off at a tangent ...
> 
> "Lance"  writes:
> 
> > Hi All,
> > 
> > Last night I attended a Weak typing, C++ Templates, and 
> > Python talk by Bruce Eckel. It was great, my introduction
> > to Python.
> > 
> > I'm sold on Python and weak typing. I want to write a 
> > graphics module that will link to a C application,
> > permitting scatter plots, bar charts, log scales, etc.
> > I suppose the Python Imaging Library will be used for this
> > purpose.
> 

Sorry pal, someone must have sold you some ranch land
in Florida also. ;-)

Python is definitely NOT weakly typed, it's dynamicly-strong
typed. A variable, being only a "reference to *any* object"
may refer to any object, but that object (see the difference?)
may not change it's functionality or type during runtime.

So, being strong typed, you cannot "cast" an object to another
type of object, like in C, you can do some strange contortions
to get what you want (forcing the compiler to do what you need,
when doing it in ... assembler, for example, would be quite
direct. Obtain the first byte from a double number,
for example:

	unsigned char c = *(char*)(&somefloat);

Now, look at this variable "unsigned char c". It can never,
ever, during the execution of your program, become anything else.
Why? Because it's storage was staticly allocated during
runtime, it doesn't hold a "reference to an unsigned_char object",
it actually *is* the address of the byte where an unsigned-char
is held;  although it obtained it's value through some ugly
type contortions.

So, you see, in C (a strong, static typed language) I obtained
a char from a floating-point number; not the string representation,
just the first byte.

On the other hand, in Python, we have:

>>> num = 3.1315

"num" contains a reference to the floating point object 3.1415,
which exists "somewhere in memory" (although you mustn't care
about that).

If you do the following:

>>> num = "3.1415"

Now, "num" has a reference to an entirely different object,
a string which contains "3.1415", which is only a string,
it doesn't matter if it "looks" like a number.

If you should do something like:

>>> num += 10
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects

See? Python won't let you do operations on an object which
correspond to a different object type. This is what it means
for "strong typing". But, since you can change a variable's
binding at runtime, it's dynamicly typed.

On the other hand, say, VBScript (yuck), you can do the
following:

DIM a,b
a = "Howdy!"
b = 3.1415

You have two variables, "a" which is a string, and "b" which
is a floating-point number. You can do operations such as:

a = a & b

"&" is a string concatenation operator, it's used to concatenate
strings; but since you're passing a floating-point number,
it automagically converts it to string and then concatenates
it. This is what weakly-typed languages to, they convert
objects to different types depending on the operation you're
trying to do with them.

VBScript is weak typed; Perl is notoriously weak typed
(everything's a string to Perl). Other scripting languages
are weak typed.


This question comes up every now and then, I think I'll
save this post, and repost it when the need comes. :-)

> A quick google search suggests that Bruce Eckel really claims that
> python is weakly typed (at least more weakly typed than C++).

This is Phalse (i.e., "very false"). An object in C++ can be
cast to a different type, same as with Java; in Python you
can do no such contortions (there's no need though).

The need in C++ and Java to have type casts comes from the
fact that variable's are staticly typed, so you can't bind
them to a different type of object than what they were
declared with, so you need to fix it up, by saying to the
program "you're receiving a X pointer, but it's not really
pointing to an X, but to a Y, and you're Y, so everythin's
OK."


HTH

-gus





Advertencia: 
La informacion contenida en este mensaje es confidencial y restringida y
esta destinada unicamente para el uso de la persona arriba indicada, Esta
comunicacion representa la opinion personal del remitente y no refleja
necesariamente la opinion de la Compa?ia. Se le notifica que esta
estrictamente prohibida cualquier difusion, distribucion o copia de este
mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error,
o si hay problemas en la transmision, favor de comunicarse con el remitente.


Todo el correo electr?nico enviado para o desde esta direcci?n ser?
procesado por el sistema de correo corporativo de HEB. Tal correo
electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien
ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan
las normas de seguridad de la empresa.



From skip at pobox.com  Wed Sep 11 16:40:51 2002
From: skip at pobox.com (Skip Montanaro)
Date: Wed, 11 Sep 2002 15:40:51 -0500
Subject: "str.contains(part)" or alternatives?
In-Reply-To: 
References: 
Message-ID: <15743.43603.971831.920711@12-248-11-90.client.attbi.com>

    >>> try:
    ...     s.index('ll')
    ...     do_something_if_found()
    ... except ValueError:
    ...     do_something_if_not_found()

    Stefan> This has the problem that a ValueError raised in
    Stefan> do_something_if_found() may give the false impression that the
    Stefan> substring isn't contained in the string s. 

I try to minimize the amount of code executed in try blocks.  Use this
instead:

    try:
        s.index('ll')
    except ValueError:
        do_something_if_not_found()
    else:
        do_something_if_found()

Also note that in 2.3 the semantics of the 'in' operator will change to make
this sort of test more natural:

    % python
    Python 2.3a0 (#86, Sep  4 2002, 21:13:00) 
    [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 'll' in 'hello'
    True

-- 
Skip Montanaro
skip at pobox.com
consulting: http://manatee.mojam.com/~skip/resume.html



From whisper at oz.net  Mon Sep 16 01:47:03 2002
From: whisper at oz.net (David LeBlanc)
Date: Sun, 15 Sep 2002 22:47:03 -0700
Subject: couldnt find __dic__
In-Reply-To: <7153651c.0209151958.4099ac3e@posting.google.com>
Message-ID: 

try __dict__ maybe?

More information might be useful. New style classes with slots don't have
__dicts__ as far as I know.

David LeBlanc
Seattle, WA USA

> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of black
> Sent: Sunday, September 15, 2002 20:59
> To: python-list at python.org
> Subject: couldnt find __dic__
>
>
> my book told me all dictionaries have __dic__ method but I searched
> each dictionaries and find nothing, where is it ???
> --
> http://mail.python.org/mailman/listinfo/python-list




From nevwill at altavista.net  Wed Sep  4 19:27:35 2002
From: nevwill at altavista.net (neville)
Date: 4 Sep 2002 16:27:35 -0700
Subject: Please help..
Message-ID: 

Hi,
I'm new to programming and python and I'm having trouble defining
functions.I have worked through 2 books and many tutorials and still
don't understand it.As this appears to be fundamental to python could
some-one please offer some suggestion.I have included a small program
that works, but how do I write it correctly.
from Tkinter import *
from time import *
t1=localtime()
n=asctime(t1)
t2=(2002,6,13,0,0,0,3,163,0)#13/6/2002
t3=(2002,6,14,0,0,0,4,164,0)#14/6/2002
ts=mktime(t1)-mktime(t2) #non smoking 
tr=mktime(t1)-mktime(t3) #for rent
d1=int(tr/((60*60)*24)) #convert to days
dr=d1%14 #rent due fortnigtly
if dr<7:
    c="The rent is due this Friday !"
elif dr==7:
    c="The rent is due today !!"
elif dr>7:
    c="The rent is due next week !"

d=int(ts/((60*60)*24))
a="Non-smoking for... %d" %d
m=(d/2)*50 #$50 saved every 2 days
b="Cash is... $%d" %m
root=Tk()
frame=Frame(root,bg="white")
frame.pack()
n=Label(frame,bg="white",fg="deeppink",text=n)
w=Label(frame,bg="white",fg="blue",text=a)
s=Label(frame,bg="white",fg="blue",text=c)
t=Label(frame,bg="white",fg="blue",text=b)
n.pack(padx=50,pady=10)
s.pack()
w.pack()
t.pack()
root.title("No Smoking!!!!")
root.mainloop()
I hope you can understand this and help me,
thanks, Neville


From eugene at ulka.com  Tue Sep 17 20:11:00 2002
From: eugene at ulka.com (Eugene Pervago)
Date: 17 Sep 2002 17:11:00 -0700
Subject: Loading modules from several directories
Message-ID: 

Trying to reuse the code I found a problem (with Python or me) where
if I have for example, a foo package in two separate directories
(where foo/ contains common files and foo/project_a/ contains
project-specific files) I can't load from both.

If I put the common path first in the sys.path it tries to load the
project-specific stuff from there too. If I try putting the
project-specific one first it can't find the common stuff.

Anyone know of a good solution for this problem?

Thanks,
Eugene Pervago


From skip at pobox.com  Thu Sep 12 15:55:05 2002
From: skip at pobox.com (Skip Montanaro)
Date: Thu, 12 Sep 2002 14:55:05 -0500
Subject: Cursed newlines and readline()
In-Reply-To: <6u5g9.11312$Da3.1133980@kent.svc.tds.net>
References: <6u5g9.11312$Da3.1133980@kent.svc.tds.net>
Message-ID: <15744.61721.37284.447554@12-248-11-90.client.attbi.com>

    Edward> According to one of Leo's Linux users, the Python's readline()
    Edward> routine on Linux delivers "\r\n" line end strings verbatim,
    Edward> while the windows versions force the string to use the Unix
    Edward> convention of using only "\n". 

In 2.3 you can open files with the "U" flag and get "universal newline"
support: 

% python
Python 2.3a0 (#86, Sep  4 2002, 21:13:00) 
[GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("crlf.txt")
>>> line = f.readline()
>>> line
'This is an example of what I have come to call the "cursed newline" problem,\r\n'
>>> f = open("crlf.txt", "rU")
>>> line = f.readline()
>>> line
'This is an example of what I have come to call the "cursed newline" problem,\n'

-- 
Skip Montanaro
skip at pobox.com
consulting: http://manatee.mojam.com/~skip/resume.html



From robin at jessikat.fsnet.co.uk  Wed Sep  4 10:50:00 2002
From: robin at jessikat.fsnet.co.uk (Robin Becker)
Date: Wed, 4 Sep 2002 15:50:00 +0100
Subject: jython memory usage
Message-ID: 

A colleague has been running tests of reportlab under jython-2.1 several
of the tests use prodigious amounts of memory (one even failed). We're
using win2k+j2sdk1.4.0_01 as the jython engine.

Anyone know what sorts of things cause x10 memory usage? I find one
particular test needs more that 1Gb and then falls over for lack of
memory. 
-- 
Robin Becker


From markus.vonehr at ipm.fhg.de  Tue Sep  3 10:11:58 2002
From: markus.vonehr at ipm.fhg.de (Markus von Ehr)
Date: Tue, 03 Sep 2002 16:11:58 +0200
Subject: hackicon, tkicon
References: <3D749F85.962D8D39@ipm.fhg.de> 
Message-ID: <3D74C32E.9FB8BD47@ipm.fhg.de>

Hi Eric,

I just had a look at my python2.2 installation:
there is the tk83.dll in. Can I change it to tk84.dll?

Thanks,

Markus


Eric Brunel schrieb:
> 
> Markus von Ehr wrote:
> 
> > Hi,
> >
> > is there already a hackicon or tkicon module for
> > python 2.2 ?
> > The modules are useful for changing the window icon on win32.
> >
> > Thanks for any hints,
> >
> > Markus
> 
> IIRC, this is no more needed with Tcl/Tk 8.4: the standard methods
> iconbitmap and/or iconwindow should work on Windows. See:
> 
> http://www.tcl.tk/man/tcl8.4/TkCmd/wm.htm#M18
> 
> But I haven't actually tested it...
> 
> HTH
> --
> - Eric Brunel  -
> PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com


From claird at starbase.neosoft.com  Tue Sep 24 17:56:11 2002
From: claird at starbase.neosoft.com (Cameron Laird)
Date: 24 Sep 2002 16:56:11 -0500
Subject: Reloading code without shutting down the app
References: <3nipma.itu.ln@cvs>
Message-ID: <93C6452FB23609A5.1A11EB70FD313CA7.B0E6371E22A16155@lp.airnews.net>

In article <3nipma.itu.ln at cvs>,
Max Ischenko   wrote:
			.
			.
			.
>Does python have some ways to reload source code of already running
>modules? For example, when consumer recv. a SIGHUP it would delete
>currently used objects/classes/modules, import all again, creates objects
>and continues to process the data from the Queue.
>
>Is it possible? And how?
			.
			.
			.
The easy part is importing new stuff; read up on
eval and exec.

It takes more subtlety to "delete currently used
objects/classes/modules".  Easiest is to rewrite
your existing work slightly so it has enough self-
knowledge either to allow itself to be overwritten,
or to announce that it should be deleted.  Can you
make those changes?
-- 

Cameron Laird 
Business:  http://www.Phaseit.net
Personal:  http://phaseit.net/claird/home.html


From klamidad at wanadoo.es  Tue Sep 10 20:58:48 2002
From: klamidad at wanadoo.es (klamidad)
Date: Wed, 11 Sep 2002 02:58:48 +0200
Subject: Lambda?!
References: 
Message-ID: 

Bo M. Maryniuck wrote:

> Python 2.0 (#1, Jan 19 2001, 17:54:27)
> [GCC 2.95.2 19991024 (release)] on linux2
> Type "copyright", "credits" or "license" for more information.
>>>> def foo(a):
> ...     return "<%s>" % a
> ...
>>>> map(lambda bar: foo(bar).upper(), ['test', 'other test'])
> ['', '']
> 
> 
> Hura-a!
> 
> 
> Python 2.0 (#1, Jan 19 2001, 17:54:27)
> [GCC 2.95.2 19991024 (release)] on linux2
> Type "copyright", "credits" or "license" for more information.
>>>> class foo:
> ...     def bar(self, a):
> ...             return "<%s>" % a
> ...     def spam(self):
> ...             return map(lambda rope: self.bar(rope).upper(),
> ['test', 'other test']) ...
>>>> f = foo()
>>>> f.spam()
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 5, in spam
>   File "", line 5, in 
> NameError: There is no variable named 'self'
> 
> 
> Huh?!
> 
> 

Python 2.1.3 (#1, Jul 29 2002, 22:34:51) 
[GCC 2.95.4 20011002 (Debian prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> class foo:
...     def bar(self, a):
...             return "<%s>" % a
...     def spam(self):
...             return map(lambda rope: self.bar(rope).upper(), 
['test', 'other test'])
... 
:4: SyntaxWarning: local name 'self' in 'spam' shadows use of 
'self' as global in nested scope 'lambda'
>>> f = foo()
>>> f.spam()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 5, in spam
  File "", line 5, in 
NameError: global name 'self' is not defined

'self' local in 'spam' <---> 'self' global in 'lambda'

Python 2.1.3 (#1, Jul 29 2002, 22:34:51) 
[GCC 2.95.4 20011002 (Debian prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> class foo:
...     def bar(self, a):
...             return "<%s>" % a
...     def spam(self):
...             return map(lambda rope,slf=self: slf.bar(rope).upper(), 
['test', 'other test'])
... 
>>> f = foo()
>>> f.spam()
['', '']

Ahh!

 


From bokr at oz.net  Tue Sep  3 20:55:57 2002
From: bokr at oz.net (Bengt Richter)
Date: 4 Sep 2002 00:55:57 GMT
Subject: winsound.Beep() frequencies
References: <3ab719f7.0209031229.33667461@posting.google.com>
Message-ID: 

On 3 Sep 2002 13:29:23 -0700, megabytemonster at hotmail.com (Stuart) wrote:

>While looking at the python documentation, I noticed that there are no
>frequency/pitch tables for using with the winsound module.  Does
>anyone know whether this documentation exists, and/or what the
>corresponding frequencies to pitches are?
>
Well, 440 hz is an A, I believe. And an octave is a factor of 2.
But I believe the best sounding scale will not have 12 equal ratios
of 2**(1/12).

Google is your friend...

    http://ccrma-www.stanford.edu/CCRMA/Courses/220a/unjung/wellScale.html

(this table does appear to be based on equal ratios).

... which is easy to compute with Python:

 >>> notes = 'A Bb B C Db D Eb E F Gb G Ab'.split()
 >>> notes
 ['A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab']
 >>> def noteFreq(name, oct):
 ...     return (27.5*2**oct)*2.0**(notes.index(name)/12.)
 ...
 >>> noteFreq('A',4)
 440.0
 >>> noteFreq('F',2)
 174.61411571650194
 >>> noteFreq('C',4)
 523.25113060119725
 >>> noteFreq('A',0)
 27.5
 >>> noteFreq('Ab',7)
 6644.875161279122


Here's more. Careful, it's easy to get interested ;-)

    http://www.organicdesign.org/peterson/tuning/

Regards,
Bengt Richter


From idjhh at hanmail.net  Sat Sep 14 23:52:50 2002
From: idjhh at hanmail.net (idjhh)
Date: 14 Sep 2002 20:52:50 -0700
Subject: registry question (_winreg)
Message-ID: 

hi ^^
i write this code today , but it is not running -_-;
i don`w find error position
see my code and then please advise me ^^
purpose of this program is to show window startprogram list ^^


=================================================================
import _winreg
root_key=_winreg.HKEY_LOCAL_MACHINE
sub_key=_winreg.OpenKey(root_key,"Software\\Microsoft\\Windows\\CurrentVersion\\Run")
number_value=_winreg.QueryInfoKey(sub_key)[1]
i=1
reg_name_list=[]
reg_data_list=[]
while i <= number_value :
    value_name=_winreg.EnumValue(sub_key,i)[0]
    value_data=_winreg.EnumValue(sub_key,i)[1]
    reg_name_list.append(value_name)
    reg_data_list.append(value_data)
    i=i+1

_winreg.CloseKey(sub_key)

==================================================================


From peter at engcorp.com  Tue Sep  3 23:29:15 2002
From: peter at engcorp.com (Peter Hansen)
Date: Tue, 03 Sep 2002 23:29:15 -0400
Subject: Design question.... parent/child class
References: <3d74b021$0$234$4d4ebb8e@news.nl.uu.net> <3d74b283$1@news.sentex.net> <3d74d0c9$0$225$4d4ebb8e@news.nl.uu.net>
Message-ID: <3d757def@news.sentex.net>

Gumuz wrote:
> I'm sorry, I don't think I understand it correctly.
> 
> Do you mean i should create a third Interface class just to communicate to
> the other class? Isn't that then just the same but with an extra class?

That's basically what I meant, but I wasn't really suggesting that
you needed to do that right now, just pointing it out as a possibility 
to consider.  It's not something you'd do if your code is still simple,
but *depending* on what SessionManager does in addition to this message
passing, it might be a necessary step to reduce complexity in the future.

As for "isn't it just the same?" I would say no, not if you end up
significantly increasing "cohesion" in the SessionManager class as
a result.  Learn about "coupling" and "cohesion" (probably many many
pages on the web that give tutorials on these terms) and you'll
understand where I was coming from.  (But I repeat, I'm *not* suggesting
you need to do that right now, if ever.)

-Peter



From malan at club-internet.fr  Thu Sep 19 18:09:53 2002
From: malan at club-internet.fr (Alan Marchand)
Date: Fri, 20 Sep 2002 00:09:53 +0200
Subject: sorry for this stupid question about struct module
Message-ID: <3d8a4ae7$0$280$7a628cd7@news.club-internet.fr>

Hi all,

I tryed this :

e:\temp>python.exe
Python 2.2.1 ( #34, Apr 9 2002, ...................)
...........
>>> import struct
>>> x = struct.pack( '>I', 10 )
>>> print repr( x )
'\x00\x00\x00\n'                       # why not !

How can I obtain the result a expect : '\x00\x00\x00\0A' ?

Remark :
This, to send a message to a IBM Mainframe in order to start an IMS
transaction ( via IMS CONNECT ).





From borcis at removethis.infomaniak.andthis.ch  Thu Sep 19 11:31:23 2002
From: borcis at removethis.infomaniak.andthis.ch (Boris)
Date: Thu, 19 Sep 2002 17:31:23 +0200
Subject: Iraq's offer to readmit arms inspectors
References:   <3D86FF01.FE0CECC5@geneva-link.ch> <3d87069c.34652637@news.rcn.com> <3D871316.AA1E8FFC@geneva-link.ch> <3d882cd4.9181792@news.rcn.com> <3f74f974.0209180713.27889f74@posting.google.com>  <3d88c258$0$707$5402220f@news.sunrise.ch>  <3d89be92$0$707$5402220f@news.sunrise.ch> 
Message-ID: <3d89ee85$0$712$5402220f@news.sunrise.ch>

Malev : [after accusing me of an opaque vice on the basis of an
              incompetent interpretation of the headers of his copy
             of my post]
>
> >by this channel. This really has nothing to do with me.  You should
> >abstain from reading technical small print if it's beyond your ability
> >to interpret it adequately.
>
> Pompous patronizing fool.

I prefer that to being the unrepenting "innocent" liar that you are, further
compounding his crime by hiding wholly unjustified conclusions under
allusive
language; just like the American president, if I may say so.

I'd also like to warn you that citing my prose by cutting it the way you do,
is inviting supernatural catastrophes on yourself and your environment :)

OTOH, I can also withdraw the last sentence of the part that you find
offending,
provided you'll display enough standards to give a similar attention to a
similar
message of my own choosing :

python >>> filter(lambda W : W not in "ILLITERATE","BULLSHIT")

What do you think it means ?

Boris




From DennisR at dair.com  Wed Sep 18 00:48:27 2002
From: DennisR at dair.com (Dennis Reinhardt)
Date: Wed, 18 Sep 2002 04:48:27 GMT
Subject: Python GUI app to impress the boss?
References: <96904b50.0209171305.6d65f574@posting.google.com>   
Message-ID: 

> > is in serious production use at tens of THOUSANDS of
> > sites.

> I read that all the time (and believe it), but that's not going to impress
> my boss, much. He's still going to want something demonstrated up close
and
> personal.

Would he be impressed by a user interface that powers 2.1 BILLION web
documents? (ref: alltheweb.com)

I am about 2 weeks away from releasing HTUIL, an integrated client for
Windows, hosting Python, Perl, and/or native PLD2 displaying in a standard
web browser.  See www.dair.com/hellopy.exe for a "hello" program written in
Python and distributed as a standalone EXE on Windows.

--

Dennis Reinhardt

http://www.dair.com




From bokr at oz.net  Mon Sep 16 18:10:26 2002
From: bokr at oz.net (Bengt Richter)
Date: 16 Sep 2002 22:10:26 GMT
Subject: "str.contains(part)" or alternatives?
References:    <3d8013e8$0$309$39cecf19@nnrp1.twtelecom.net>
Message-ID: 

On Wed, 11 Sep 2002 21:18:23 -0700, Greg Fortune  wrote:

>> 
>>> I think the current proposal is to move to
>>> 
>>>     if ll in s:
>>> 
>>> for this construct. Happy?
>> 
>> I would like .contains more, but at least the proposal is _much_ better
>> than "if s.find(part) != -1". :-)
>> 
>> "if part in s" disturbs the pattern "if item in sequence" somewhat but
>> that has already been weakened by "if key in dict" (that I like,
>> nonetheless).
>> 
>> Stefan
>
>
>Why not simply use .count(part) > 0 ?  I didn't catch the first part of the 
>conversation, but if I'm looking for a contains, I just do.
>
>if(search_me.count(substr) > 0):
>        print 'found'
>else:
>        print 'not found'
>
>
Mostly it won't matter, but in cases like

    search_me = 'a'*10000000
    substr = 'a'

it will 'way suboptimal in comparison with find or index.

Regards,
Bengt Richter


From franke at ableton.com  Mon Sep  2 16:26:18 2002
From: franke at ableton.com (Stefan Franke)
Date: Mon, 02 Sep 2002 22:26:18 +0200
Subject: Regex for String Literals
Message-ID: <47i7nu8q5b3e5merhe7s19qvgsf244nkfq@4ax.com>

Does someone know a regular expression that matches all
kinds of Python string literals (along with their  finer points 
WRT line breaks, unicode..)?

Stefan



From chris_mk at hotmail.com  Fri Sep 13 19:29:07 2002
From: chris_mk at hotmail.com (Christopher)
Date: 13 Sep 2002 16:29:07 -0700
Subject: transform list of int in a list of string??
References: <-1483717605.1031940885180.JavaMail.nobody@webmail2.brturbo.com> 
Message-ID: 

I think you meant:
y = [str(n) for n in x]

Chris

Skip Montanaro  wrote in message news:...
> juliano> How can i transform a list of integer numbers in a list of
>     juliano> string numbers, like that: 
> 
>     juliano> x=[1,2,3,4] to y=['1', '2'...]????????
> 
> Try 
> 
>     y = map(str, x)
> 
> or
> 
>     y = [int(n) for n in x]


From rajarshi at presidency.com  Wed Sep 18 11:40:51 2002
From: rajarshi at presidency.com (Rajarshi Guha)
Date: Wed, 18 Sep 2002 11:40:51 -0400
Subject: isFloat: Without Exception-Handling
References: 
Message-ID: 

On Wed, 18 Sep 2002 11:41:47 -0400, Thomas Guettler wrote:

> Hi!
> 
> Is there a way to write the following method without using exceptions?
> 
> def isFloat(string):
>      is_float=1
>      try:
>          float(string)
>      except:
>          is_float=0
>      return is_float
> 
> print isFloat("asdf") # --> 0
> print isFloat("0.1")  # --> 1


def isFloat(string):
  if type(string) == type(1.0):
    return 1
  else
    return 0

This should do what you want without exceptions


From aleax at aleax.it  Fri Sep 20 05:15:26 2002
From: aleax at aleax.it (Alex Martelli)
Date: Fri, 20 Sep 2002 09:15:26 GMT
Subject: Destructor never called ???
References: 
Message-ID: 

Tim Peters wrote:
        ...
> __del__s will be invoked.  It's only the cases where Python can't possibly
> guess a safe order in which to call destructors where both __del__ and
> collection are inhibited.

I think it's a bit more than that: Python *COULD" "possibly guess a
safe order" when there is only exactly ONE object with a __del__ that
is part of the cycle -- namely, destroy that one object first.  It
doesn't seem to even TRY (note: I'm not saying it SHOULD -- but
"can't possibly" might be a bit too strong as a description of what
is actually going on).


Alex



From abuse at nospam.riot.com.au  Wed Sep 25 23:58:48 2002
From: abuse at nospam.riot.com.au (Glen Murphy)
Date: Thu, 26 Sep 2002 13:58:48 +1000
Subject: object changing itself to another object
Message-ID: 

I'm creating a program that takes user input, and passes it to an object -
however, I want that object itself, and not the parent to change where that
input goes. In the highly simplified example below, I would like the output
to be "Obj1","Obj2","Obj1" - but not suprisingly, I just get Obj1, Obj1,
Obj1


### code begin  ###

class Obj1:
    def key1(self):
        # do obj1 specific stuff
        self = Obj2()
        print "Obj1"

class Obj2:
    def key1(self):
        # do obj1 specific stuff
        self = Obj1()
        print "Obj2"

a = Obj1()

# simulate user keypresses
a.key1()
a.key1()
a.key1()

### code end ###

I know I could achieve the result I want by doing horribly complicated trees
of ifs and such, but I'd like my code to be nice and expandable (in this
example, to easily add new Objs). I've looked through the Python FAQ, Google
Groups and Various O'Reilly books, but I don't really know the terminology
for what I'm looking for, so I haven't found anything so far, so does anyone
have any pointers?

Any help would be greatly appreciated,
Cheers,
Glen

--
Glen Murphy, http://glenmurphy.com/




From roy at panix.com  Wed Sep  4 07:30:57 2002
From: roy at panix.com (Roy Smith)
Date: Wed, 04 Sep 2002 07:30:57 -0400
Subject: Why Python?
References:  
Message-ID: 

"Benjamin"  wrote
>> i talked to a friend of mine, he told me that i should try php..

Learning new stuff is never a bad thing, but I'm not sure php is where I 
would go next.  While I've never used it myself, my impression is that 
it's really just a niche tool for creating dynamic web pages rather than 
a real programming language.  There is a lot to programming beyond the 
web, and I think you'd do better learning some more general-purpose 
tools and languages.

"RPM1"  wrote:
> I think you should try coding in C.  It's used everywhere for
> everything.  It's faster than about any other language.
> Most other languages are written in C.  C is highly marketable.
> 
> But best of all...
> 
> You'll learn to *really* appreciate other languages like Python,
> Java, ...

I agree that learning C is a good next step if your plan is to do 
programming for a living.  For better or worse, it is the lingua franca 
of the programming industry today, and has been for the past 15 or 20 
years.  And, yes, it will give you a taste of a very different 
programming environment from Python.

After that, my guess would be at least two of C++, Perl, and Java.  
Exactly what you want to do will determine which.  If you goal is to get 
into e-commerce and the web, Java is probably a must.
 
Python is an cool language, but the unfortunate truth is that there just 
aren't that many paying jobs for people who know Python and nothing 
else.  Hopefully that will change over the next 5 years, but it's not 
assured to happen, and in any case will be a slow process.  In the 
meantime, hedge your bets.


From syver-en+usenet at online.no  Fri Sep 13 09:45:34 2002
From: syver-en+usenet at online.no (Syver Enstad)
Date: Fri, 13 Sep 2002 13:45:34 GMT
Subject: Calling Python from C# - please help
References: <6de16ac9.0209130508.5d1b56c6@posting.google.com> 
Message-ID: 

loewis at informatik.hu-berlin.de (Martin v. L?wis) writes:

> adila001 at yahoo.com (AdrianC) writes:
> 
> > I am using Python 2.1 and I am tring to use my Python COM component.
> 
> > From VB6 everything is OK, but in .NET i don't know how to set the
> > reference to my COM.
> 
> I've never used the COM bridge in .NET, but I believe you need to
> create a type library first.

Although you don't have to make a typelibrary, your C# code will be
nicer if you do so (else you will have to use the dispatch interface
to work with the object).

-- 

Vennlig hilsen 

Syver Enstad


From bfarwick at juno.com  Thu Sep 26 05:32:41 2002
From: bfarwick at juno.com (brrrent)
Date: 26 Sep 2002 02:32:41 -0700
Subject: cursor positioning and color
References:  <1b6dca50.0209231022.6fae7f6d@posting.google.com> <30770aa4.0209232242.1e91d9d5@posting.google.com>
Message-ID: <1b6dca50.0209260132.6d1d333a@posting.google.com>

bogusdrop at myself.com (TuxTrax) wrote in message news:<30770aa4.0209232242.1e91d9d5 at posting.google.com>...
> bfarwick at juno.com (brrrent) wrote in message news:<1b6dca50.0209231022.6fae7f6d at posting.google.com>...
> > TuxTrax at fortress.tuxnet.net (TuxTrax) wrote in message news:...
> > > Being new to python, I would like to know how one goes about such 
> > > tasks as precise cursor positioning and output to screen in color.
> > > 
> > 
> > Hi Mathew,
> > 
> > Curses is the way to go when using Linux/Unix.
> > 
> > Wconio is the way to go when using Microsoft.
> > You can find in the Vaults of Parnassus.  If you have any trouble
> > locating it, let me know, I can email it to you.  Small library, works
> > well.
> > 
> > All the best,
> > 
> > brrrent
> 
> Thanks Brent. Appreciate it. Am I to understand that there are no
> python libraries that do this as a standard part of the python
> distribution?

Mathew,

A linux or unix distribution without curses is just about unheard of.
About the only chance of finding a linux installation without curses
would be in a standalone firewall box.

WConio is a "tiny" download and very worth it.  Works like a champ. 
One heck of a lot easier to grasp than curses.  Many thanks to Mr.
Gonnerman for such a useful library.  If you write a python WConio
app, why not just send WConio along with the python code.  As I said,
it's "tiny".

brent

 
> That would be preferable, as it would eliminate the requirement of
> making
> the user have curses on their system before they can use the code.
> 
> Cheers,
> 
> Mathew


From jb at cascade-sys.com  Fri Sep 20 20:15:46 2002
From: jb at cascade-sys.com (James J. Besemer)
Date: Fri, 20 Sep 2002 17:15:46 -0700
Subject: Getting started
References:   
Message-ID: <3D8BBA32.1070700@cascade-sys.com>

Alex Martelli wrote:

>$a = "2.3";
>$b = 45;
>print $a+$b;
>
>emitting 47.3 is pretty close to what I consider "weak typing".  
>

I don't see why you call this "weak typing".  In Perl, the "+" operator 
is defined to work with strings or numbers.  It may seem more confusing 
at first if you expect "+" also to be the string concatenation operator, 
which it is not.  In the above example,

    print $a . $b;

will print the string "2.345".

This all is no different in principle from Python's:

    a = 2.3
    b = 45L
    print a + b

and getting 47.3.  The "+" operator is defined for floats and also for 
longs.  Since they're all "numbers" it would seem really strange if they 
did not interact naturally like this.  But fundamentally they're 
distinct types as "type( 2.3 )" and "type( 45L )" illustrate.

Perhaps an even better example is the "*" operator:

        print  2  * 5     # integer x integer -> integer
        print [2] * 5     # list x integer -> list
        print "2" * 5     # string x integer -> string

This all makes sense even though radically different results and result 
types are produced each time.  It's not "weakly typed" but rather 
strong, dynamic typing.  The outcome is completely determined by the 
operator and the types of the operands and there is no way to break the 
rules.  Since we know Python is strongly typed then it follows that your 
Perl example must be also.

Anyway, why should "2" + 5 == "7" be all that much stranger than "2" * 5 
== "22222"?  If the operation is unambiguous and useful what rule would 
it break?  Personally, I think Python would be improved slightly by 
adding this conversion.  It's convenient and there's ample precedent in 
other languages (Awk, Snobol, Icon, Perl, etc.).  But I am sure that 
notion will provoke howls of protest from the True Believers.

There are a lot of reasons why Python is better than Perl but strongly 
vs. weakly typed is not one of them.  I don't see a material difference 
in the "strength," per se, of typing between Perl and Python.  They're 
both "strong" and "dynamic", though Python's type model is better 
thought out, particularly since object/type unification.  

Getting back to the original question, the quintessential example of 
"weak typing" is in old C or Fortran where you can define a function to 
take, say, a string argument but are allowed instead pass in a real or a 
pointer to a struct and get garbled results or even corrupt the program:

    printf( "%s\n", 2.5 );        // possible program fault

Another example is all too familiar to MFC programmers:

    CEdit* edit = (CEdit*)GetDialogItem( ID_FOO );

GetDialogItem() essentially returns a raw pointer.  The programmer is 
required to explicitly cast the pointer into the proper type, the same 
type as the dialog item identified by the numeric ID.  However, if the 
dialog item itself changes, say, from an Edit box to a List box then the 
cast becomes wrong, some operations on edit may fail catestrophically, 
and -- worst of all -- the compiler cannot detect and diagnose this 
error for you.
  
These types of errors are not possible in Python or Perl, which 
illustrates that they're both "strong".  

Curiously, in Python

    print "%s" % 2.5

prints the string "2.5" instead of, say, raising an exception.  So 
there's some small precedent for treating numbers as strings in a string 
"context" even in Python.

I'll go out on a limb and say that most "dynamic typed" languages are 
also "strong" by necessity.  If the user isn't keeping track of the 
types then the system HAS to.  An exception I can think of would be an 
ancient dialect of Lisp where integers also were machine addresses and 
thus callable without restriction.  E.g., if a function name evaluated 
to a number the interpreter performed a subroutine call to that address 
instead of, say, applying a lambda.  It was the mechanism through which 
system builtins were accessed.  However,  nothing prevented a user from 
"calling" an arbitrary integer and leaping off into never never land.  

"Strong typing" (the "static" kind) is also the norm in Pascal and C++. 
 I like to think of strong typing as the norm in ANSI C but there is 
still optional and thus may be considered "weak".  Furthermore, C 
programmers are on the "honor" system across module boundaries, as 
there's no link time checking.  There even are ways to cheat in C++, so 
some might still class it as a "weakly typed" language.  Of course, with 
discipline, it's possible to avoid the pitfalls and always use the 
strong typing facilities of C and with effort enjoy most of the benefit.

>I
>find it very hard to produce substantial, large programs using
>weakly-typed languages. 
>
Given my definition of "weakly typed," I agree it's more difficult than 
in strongly typed languages.

On the other hand, isn't it the case that much of Python is implemented 
in C, which is weakly typed?  So "weakly typed" makes it harder but not 
impossible, at least not for some.

> Python is strongly, albeit dynamically, typed,   
>
FWIW, so is Perl.

>Unfortunately, some seminal material of a few
>decades ago confused terminology (I vaguely remember something
>about it in some early article about Scheme, for example).
>
I think you're right.  I originally learned a different taxonomy for 
many of these concepts.  

--jb

-- 
James J. Besemer		503-280-0838 voice
2727 NE Skidmore St.		503-280-0375 fax
Portland, Oregon 97211-6557	mailto:jb at cascade-sys.com
				http://cascade-sys.com	







From donn at drizzle.com  Fri Sep  6 23:02:37 2002
From: donn at drizzle.com (Donn Cave)
Date: Sat, 07 Sep 2002 03:02:37 -0000
Subject: Multiple Python Apps on Linux
References: None 
Message-ID: <1031367756.99553@yasure>

Quoth "Robert Oschler" :
| If I run several single-threaded Python apps simultaneously, each launched
| as their own process running on Linux, are they truly independent or will
| Python's "global library lock flag" come into play like it does for a single
| Python app that is multi-threaded?

They're independent, even if forked from a Python parent process, on
any platform.  The lock applies to threads only, that is, threads that
share a common address space.

	Donn Cave, donn at drizzle.com


From sismex01 at hebmex.com  Tue Sep 24 09:49:27 2002
From: sismex01 at hebmex.com (sismex01 at hebmex.com)
Date: Tue, 24 Sep 2002 08:49:27 -0500
Subject: confused with lambda~
Message-ID: 

> that describe in reference documentation is too short,
> I couldnt even understand what it trying to say.
> any explanation please ?

Lambdas are complicated to understand, but it's easier
if you think of them as a single-expression inline
function (not inline in the code-generation sense
of the word, but of the definition sense).

See, "def" is a statement, and defines a word in the
local namespace to be a function, and "lambda" returns
a reference to a function. Kinda hard to understand :-)

So, the equivalence would be something like this:

Using def:
>>> def square(a): return a*a

Using lambda:
>>> square = lambda a:a*a

lambda's syntax is "lambda :", quite
simple really, but what makes them hard is the concept
of an "unbound" function. Another example:

Using def:
>>> def SumOverProduct(a,b): return (a+b)/(a*b)

Using lambda:
>>> SumOverProduct = lambda a,b: (a+b)/(a*b)

You may use anything Python in the argument list, including
the *args and **kw forms. One thing you have to look out
for is the form where local variables are propagated to
the lambda's namespace (it's a function, remember?) using
default arguments:

def some_func(...):
	... code ...
	L = lambda a, b=SomeLocalVar, c=Another: operations(a, b, c)
	... more code ...

In previous versions of Python, there was no way to access
variables outside the lambda's namespace unless it was
by propagating them via default arguments, in more recent
versions it's possible to do away with this practice,
if you know what you're doing :-)

Well... what more can I say. It's a complex subject,
I really recommend you practice them if you want to use
them, until you get the hang of using them to make your
programs more clear.

Notice: USE them, don't ABUSE them; they either make a
program much more clearer, or they make them a program
hideously obtuse and obscure, and difficult to read
and understand (we all know who the culprits might be
so I won't say names). ;-)

Good luck, practice, play around with them, and then
store them somewhere safe where they won't do much
harm. :-)

-gus

Advertencia: 
La informacion contenida en este mensaje es confidencial y restringida y
esta destinada unicamente para el uso de la persona arriba indicada, Esta
comunicacion representa la opinion personal del remitente y no refleja
necesariamente la opinion de la Compa?ia. Se le notifica que esta
estrictamente prohibida cualquier difusion, distribucion o copia de este
mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error,
o si hay problemas en la transmision, favor de comunicarse con el remitente.


Todo el correo electr?nico enviado para o desde esta direcci?n ser?
procesado por el sistema de correo corporativo de HEB. Tal correo
electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien
ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan
las normas de seguridad de la empresa.



From tundra at tundraware.com  Sun Sep  1 21:00:02 2002
From: tundra at tundraware.com (Tim Daneliuk)
Date: Mon, 02 Sep 2002 01:00:02 GMT
Subject: [ANN] 'tdir' version 1.67 Released
Message-ID: <02duka.pbc2.ln@boundary.tundraware.com>

'tdir' 1.67 is released and available at:

        http://www.tundraware.com/Software/tdir/

'tdir' is an advanced command-line directory and file display utility
written in Python, which runs on both *nix systems like FreeBSD and
Linux, as well as Win32.

'tdir' displays directories and files distinctly and separately.
By default, 'tdir' sorts files by their 'extension' and the
character which delimits those extensions is user-selectable.
'tdir' can also be used to display just the directory tree rooted
anywhere in the file system.

Output and column width are user-selectable as well and the
program writes to stdout, thereby allowing redirection to files
and devices.

Update to the FreeBSD port has also been submitted and should be available
shortly.

-- 
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com



From gerhard.haering at opus-gmbh.net  Wed Sep  4 12:01:25 2002
From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=)
Date: 4 Sep 2002 16:01:25 GMT
Subject: embeddable ide?
References: 
Message-ID: 

Stevek wrote:
> We're planning on making extensive use of Python to provide our users with a
> powerful scripting mechanism.  I've successfully embedded and extended
> Python but now I want to give the user a decent development environment for
> writing their scripts.
> 
> I know there are several IDEs available for Python development, but I'm
> looking for one that can be used from within another application (embedded).
> 
> Any suggestions would be appreciated.

If you're not using the same toolkit as the Python IDE, then I think this
will get very difficult, if not impossible.

If you're only targetting Windows, then I think PythonWin will be possible.

Anything that uses Scintilla will be a candidate. Perhaps it's wise to
outsource this task, like the producers of WingIDE?

-- Gerhard


From jetman516 at hotmail.com  Thu Sep 12 18:13:11 2002
From: jetman516 at hotmail.com (The Jetman)
Date: 12 Sep 2002 15:13:11 -0700
Subject: [newbie] Buying an introductory/reference text
References: 
Message-ID: 

Brad Fonseca  wrote in message news:...
> Greetings!
> 
> I'm looking for a few opinions on the above subject.  I'm a computer 
> science student who has had some introductory lectures on Python and I've 
> done some very basic mucking around with.  I'm looking for a clear 
> reference and/or introductory text.  Any suggestions would be nice.  I have 
> looked at http://www.python.org/cgi-bin/moinmoin/IntroductoryBooks but 
> there appears to be a number of good books to choose from there.
> 
> Regards,

Can't go wrong w/ Programming Python 2ndEd by Lutz from O'Reilly.  Here's 
a sample chapter.  If you can only afford a single book, this mite be it....Jet

http://www.oreilly.com/catalog/python2/chapter/ch15.html


From max at alcyone.com  Fri Sep  6 16:09:03 2002
From: max at alcyone.com (Erik Max Francis)
Date: Fri, 06 Sep 2002 13:09:03 -0700
Subject: Larry Wall's comment on python...
References: 
Message-ID: <3D790B5F.BDD8810C@alcyone.com>

Rod Stephenson wrote:

> "Python is cool to look at small bits of, but I think the "outline"
> syntax breaks down with larger chunks of code. I'm with Aristotle on
> the structure of discourse--a story should have a beginning, and
> middle, and an end. So should blocks"
> 
> I'm not quite sure what he's trying to get at here - I guess that for
> a long heavily indented chunk of code, you could lose track of the
> overall structure, but I don't write code this way.
> 
> Any comments?

I'm not really sure what he's getting at, either.  It sounds like he's
suggesting that using indentation for setting off blocks is confusing,
but this is a standard objection to Python that most people have
(especially those with experience in other languages), and my experience
is most people immediately drop this objection after using it for a
little while.

But at some level, what would you expect him to say?

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ There is nothing so subject to the inconstancy of fortune as war.
\__/ Miguel de Cervantes
    Church / http://www.alcyone.com/pyos/church/
 A lambda calculus explorer in Python.


From johnroth at ameritech.net  Thu Sep 26 23:20:13 2002
From: johnroth at ameritech.net (John Roth)
Date: Thu, 26 Sep 2002 23:20:13 -0400
Subject: Tab stops. was: Re: Larry Wall's comment on python...
References: 
Message-ID: 

 wrote in message
news:mailman.1033049075.18932.python-list at python.org...
> >
> > sismex01 at hebmex.com wrote:
> >
> > >>Ironically, Guido originally ruled (in the style guide, IIRC)
> > >>that thou shalt use tabs and tabs are 8 spaces, "as god
> > >>intentended them to be."
> > >
> > >Yeesh! Why in God's name would he say such a dumb thing?
> > >I mean, even ancient mechanical typewriters have movable
> > >tab settings. Rigid, 8-char tabs is just so... neolithical.
> > >
> >
> > Once upon a time, a large class of computers, and their attendant
> > peripherals, OSs and utility programs universally implemented tabs
> > hard-wired at 8 stops.  In some circles this heritage extended
> > back 30 or 40 years.  Unix originally followed this convention,
> > as did IIRC all Dec computers and that of most other "minicomputer"
> > vendors.
> > Ed and the original VI editors only had fixed tab stops consistent
> > with terminal drivers and all the unit record equipment at the time.
> > IIRC, even Emacs originally only had tab stops at every 8 columns.
> > The original PC also followed this convention, though not all
> > applications did.  I don't know for sure but I bet $1 that Linux
> > tty drivers today also are hard wired at 8 char tab stops.
> >
>
> Thanks for a beautiful reply.
>
> Well, I might not be an old fart :-), but I *was* kinda present
> at that time, I started work in highschool hacking on CP/M machines,
> writing drivers for diverse printers and terminals for some apps
> (ahh, customizable terminal control... we lost that during the
> PC era, everybody wanted CGA, MDA or Hercules).
>
> AND, I distinctly remember that most printers could customize
> their tab stops via escape codes, same as some (not all) terminals;
> I worked a lot on some Xoroc terminals, and lots on a Northstar
> Advantage (ahh, beautiful hardware... *snif*) and they also had
> customizable tabstops.

Well, you got in rather late. The entire tab stop thing began
with mechanical and electromechanical equipment, like TTYs.
All of these had customizable tab stops, set by actual hardware
tabs (little pieces of metal). The thing about them is that typists
set them when they were doing reports, and otherwise ignored
them. Once they started getting added to the earliest computers,
it was simply not feasible to manually set up the output typewriter
for each and every program.

So some genius simply set the stops every 8 characters
and left them there. The drivers used the fixed stops in
order to optimize their output stream, and all the utilities
simply assumed that the output was set up this way.

Time and technology moved on, but by then the assumptions
were built into way too many programs to fix, and there was
never a concensus about how to fix it, anyway.

> Hmmm... maybe, what I'm getting at is, why did terminal-designers
> everywhere toss out years of research in typewriter technology
> (at the time) and ignore customizable tab-stops?  It's simply not
> sane, I think.

As I said, it was very sane. Nobody wanted to change
manual tab stops. Program setable tab stops came later.
Much later, and too late for there to be a coherent solution.

As an interesting side note, much the same issue came up
with the old vacuum tube computers (1950s vintage.) They
used existing plugboard tab equipement as card readers,
punches and printers. People very quickly standardized
on one set of plug boards, stuck them in the machine and
forgot about them. Much easier than to create a special set
of plug boards for each job, although I suspect some analysts
tried.

John Roth




From markus68 at bigfoot.de  Wed Sep 11 15:25:32 2002
From: markus68 at bigfoot.de (Markus)
Date: Wed, 11 Sep 2002 21:25:32 +0200
Subject: deleting the first and the last character of a string
References: <20020911105818.GC2054@partagas.as.de.cw.net> 
Message-ID: 

Sean 'Shaleh' Perry wrote:

>> Is there anything which says delete the first or last
>> character of a string? I checked the string module on the web, but I
>> couldn't find anything.
>>
> 
>>>> s = '|f|o|o|'
>>>> s.strip('|')

>>> s[1:-1]
'f|o|o'

-Markus


From jknapka at earthlink.net  Fri Sep  6 17:23:56 2002
From: jknapka at earthlink.net (Joseph A. Knapka)
Date: Fri, 06 Sep 2002 21:23:56 GMT
Subject: Larry Wall's comment on python...
References: 
Message-ID: <3D791CED.807E744B@earthlink.net>

Rod Stephenson wrote:
> 
> Slashdot has a list of questions posed to Larry Wall (perl). When
> asked his thoughts on other scripting languages, he makes the
> following observation about python
> 
> "Python is cool to look at small bits of, but I think the "outline"
> syntax breaks down with larger chunks of code. I'm with Aristotle on
> the structure of discourse--a story should have a beginning, and
> middle, and an end. So should blocks"
> 
> I'm not quite sure what he's trying to get at here - I guess that for
> a long heavily indented chunk of code, you could lose track of the
> overall structure,

...whereas with Perl, you can lose track of the overall structure
in a single line, brackets or no.

-- Joe
  "I'd rather chew my leg off than maintain Java code, which
   sucks, 'cause I have a lot of Java code to maintain and
   the leg surgery is starting to get expensive." - Me


From a-steinhoff at web.de  Sat Sep 21 06:48:06 2002
From: a-steinhoff at web.de (Armin Steinhoff)
Date: 21 Sep 2002 03:48:06 -0700
Subject: Python threading?
References:  
Message-ID: 

Trent Mick  wrote in message news:...
> [Robert Oschler wrote]
> > How can I tell if the version of Python I am running is thread-enabled?
> 
> Run Lib/test/test_thread.py with your Python build. If you are on any
> common platform then Python, unless specifically crippled, is
> thread-enabled.
> 
> > Also, what is a reasonable number of threads to expect to be able to run
> > before context switching overhead becomes a problem (I'm using a PIII 500
> > Mhz with 512MB ram if that helps).
> 
> I have no experience putting that many threads to use.

Check out Stackless Python which supports micro threads (very small
context switching overhead ..)

Armin

> 
> 
> Trent


From toto2001 at hananet.net  Tue Sep 10 09:22:58 2002
From: toto2001 at hananet.net (konghyeogjun)
Date: Tue, 10 Sep 2002 22:22:58 +0900
Subject: default variable value and cmd module
Message-ID: 

This sample using 'cmd' module do not prints default variable value, 5.

import cmd
class x(cmd.Cmd):
    def do_y(self, value = 5):
        print value
z = x()
z.cmdloop()

but, the following sample prints '5'. why don't the sample above prints?

class x:
    def do_y(self, value = 5):
        print value
z = x()
z.do_y()














From aleax at aleax.it  Mon Sep 16 02:46:23 2002
From: aleax at aleax.it (Alex Martelli)
Date: Mon, 16 Sep 2002 06:46:23 GMT
Subject: Source code
References:   
Message-ID: <37fh9.112911$pX1.4044383@news2.tin.it>

Martin v. Loewis wrote:

> Gerhard H?ring  writes:
> 
>> You should perhaps reconsider if and why you need to hide your source
>> code.
> 
> You should also recognize that, if your computer can execute and
> perform a certain algorithm, users can always observe simulate the
> computer operations, thus breaking any protection scheme.
> 
> You'll have to give your customers a sealed computer and no permission
> to install additional software, or communicate with the internet, if
> you want to reliably prevent them from analysing your program.

Incidentally, the latter option can be feasible in certain situations: some 
key parts of your program's functionality might reside on a computer you
control, accessible to the rest of the application (installed more 
traditionally on users-controlled computers) only as a black box via the 
net.  XML-RPC, SOAP, and other distributed-computing approaches
such as Corba, make implementing this particularly easy these days.

Feasibility depends on how troublesome it is to demand that the
users' computers be net-connected whenever the application may
run, and how time-critical is the round-trip time whenever the
code that runs on the users' computers must delegate some part
of an operation to code running on the computer you control.  In
some application areas these feasibility issues may be killers, in
others they're no trouble at all.  When the latter conditions prevail,
this approach does yield something like a protection scheme that
you can, at least in theory, make "unbreakable" (by satisfying other
conditions, such as statefulness and other ways to make the part
running under your control arbitrarily hard to reverse-engineer).


Alex



From marklists at mceahern.com  Tue Sep 24 12:31:31 2002
From: marklists at mceahern.com (Mark McEahern)
Date: Tue, 24 Sep 2002 11:31:31 -0500
Subject: What is the mechanism behide?
In-Reply-To: 
Message-ID: 

> I'm studying the singleton pattern, there are something I don't
> understand in the sample code below:
[snip]
>     I'm puzzled that what is behide the statement "print x" ?

This is a more straightforward sample to cut your teeth on, imho:

>>> class foo:
...     def __str__(self):
...             print "calling __str__"
...             return "whatever we like"
...     def __repr__(self):
...             print "calling __repr__"
...             return "something different"
...
>>> f = foo()
>>> print f
 calling __str__
whatever we like
>>> print `f`
calling __repr__
something different
>>>

So __str__ simply allows you to override what happens when str() is called
on an instance of your class.  str() is what print calls, I believe.

__repr__ allows you to override what happens when repr() is called.  The
backticks (e.g., ``) are equivalent to repr().

You might want to lookup print, __str__, __repr__, str(), and repr() in the
docs.

I don't have the patience to decode the OnlyOne stuff.  Perhaps someone else
does.

Cheers,

// m




From mcfletch at rogers.com  Thu Sep  5 11:11:03 2002
From: mcfletch at rogers.com (Mike C. Fletcher)
Date: Thu, 05 Sep 2002 11:11:03 -0400
Subject: Why read-only nested scopes?
References:     <20020905.072837.159259470.2038@cybermesa.com> 
Message-ID: <3D777407.4060203@rogers.com>

 >>Why not simply disallow the using of a name already defined in an
 >>enclosing scope? Similar to Smalltalk?
 >
 >
 > That might break compatibility with existing code.

I'll go one further:
	That _would_ break large quantities of existing code.

#consider
def blah( somefile ):
	string = somefile.read()
	return string[1:-1]

is now dependent on string not being imported at a higher level? 
Perfectly predictable code, obviously no relationship to "string" in a 
higher scope, but suddenly raising errors.

#consider
class window:
	pass
def whah( window ):
	window.whah( someglobal, somenumber, something )

Which is now raising errors because the temp variable/argument matches 
the class-name (yes, I know, normally there's a case-diff, but the 
pattern happens with types and the like).

If, for some reason this functionality (assigning to an enclosing scope 
which is not global (does this really occur much? I've never felt such a 
need that I can recall)), figure out a better way, such as:

	global(2) x

(Yes, ugly, but doesn't kill lots of code).  Or:

	global existing x

where the existing form says that an existing x record must be used.

But please sirs, don't kill our code :) ,
Mike

Martin v. L?wis wrote:
> "Jay O'Connor"  writes:
> 
> 
>>Why not simply disallow the using of a name already defined in an
>>enclosing scope? Similar to Smalltalk?
> 
> 
> That might break compatibility with existing code.
> 
> Regards,
> Martin
_______________________________________
   Mike C. Fletcher
   Designer, VR Plumber, Coder
   http://members.rogers.com/mcfletch/





From jggramlich at yahoo.com  Thu Sep  5 14:14:42 2002
From: jggramlich at yahoo.com (Joshua Gramlich)
Date: 5 Sep 2002 11:14:42 -0700
Subject: PyListObject & C Modules
References:    
Message-ID: 

Okay...what I have now:

##############################code
block#################################

#include "Python.h"
#include 

static PyObject *ErrorObject;
#define onError(message) \
    { PyErr_SetString(ErrorObject, message); return NULL; }

PyObject*
get_first_elem(PyObject *unused, PyObject *args)
{
  PyObject *list;
  PyObject *first;
  PyObject *result;

  if(!PyArg_ParseTuple(args, "!O", &list))
    return NULL;

  if(!PyList_Check(list)) {
    PyErr_SetString(PyExc_TypeError, "get_first_elem expects a list");
    return NULL;
  }

  if(PyList_Size(list) == 0){
    PyErr_SetString(PyExc_ValueError, "empty lists not allowed");
    return NULL;
  }

  first = PyList_GetItem(list, 0);
  result = PyList_New(1);
  if (!result) return NULL;
  Py_INCREF(first);

  if (PyList_SetItem(result, 0, first) != 0) {
    Py_DECREF(first);
    Py_DECREF(result);
    result = NULL;
  }
  return result;
}

static struct PyMethodDef slist_methods[] = {
 {"getfstelm",     get_first_elem,     1},
 {NULL,                NULL}
};

void initslist()
{
    PyObject *m, *d;

    m = Py_InitModule("slist", slist_methods);

    d = PyModule_GetDict(m);
    ErrorObject = Py_BuildValue("s", "slist.error");
    PyDict_SetItemString(d, "error", ErrorObject);

    if (PyErr_Occurred())
        Py_FatalError("cannot initialize module slist");
}

##########################end code block############################

I have been reading the tutorial (amongst other things), and yes, I
should
probably have eventually caught the ADDREF bit.  The above compiles
fine and what-not, but when I run it via this:

############### hello.py #####################

stuff = 7,8,8,23,222,12
print(stuff)
pidge = slist.getfstelm(stuff)
print(pidge)

##############################################

I get this:

[d0ora3 ~/work/grid_query/test]$ python hello.py 

(7, 8, 8, 23, 222, 12)
Traceback (most recent call last):
  File "hello.py", line 25, in ?
    pidge = slist.getfstelm(stuff)
TypeError: argument 1 must be impossible, not tuple
[d0ora3 ~/work/grid_query/test]$ 



Now, if "stuff" is changed to "[7,8,8,23,222,12]" then the TypeError
ends with "not list" instead of "not tuple" and so on for ints and
strings.

Thoughts?


From loewis at informatik.hu-berlin.de  Wed Sep  4 12:44:17 2002
From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=)
Date: 04 Sep 2002 18:44:17 +0200
Subject: PyListObject & C Modules
References:   
Message-ID: 

jggramlich at yahoo.com (Joshua Gramlich) writes:

> get_first_elem(PyObject *unused, PyObject *args)
> {
>   if(!PyArg_ParseTuple("!0", &list))
>     return NULL;
> slist.c:10: warning: passing arg 1 of `PyArg_ParseTuple' from
> incompatible pointer type

Right. This should be
   if(!PyArg_ParseTuple(args,"!0", &list))
     return NULL;

Reading the Extending and Embedding tutorial would have helped you to
fix this error on your own.

>   Py_ADDREF(first);
> ./slist.so: symbol Py_ADDREF: referenced symbol not found

Right. It is INCREF, not ADDREF. Reading the tutorial really helps.

You'll also learn that you lead additional boilerplate code to make an
extension module.

Regards,
Martin


From paoloinvernizzi at dmsware.com  Thu Sep  5 03:59:26 2002
From: paoloinvernizzi at dmsware.com (Paolo Invernizzi)
Date: Thu, 05 Sep 2002 07:59:26 GMT
Subject: Servizi Internet
References:  
Message-ID: 

Benjamin wrote:
> by the way, how many people understand italian in
> this nesgroup? ^_^

** a little hand is raised! **



From see_reply_address at something.invalid  Wed Sep 18 19:43:44 2002
From: see_reply_address at something.invalid (Greg Ewing)
Date: Thu, 19 Sep 2002 11:43:44 +1200
Subject: Stackless Python, eventual merge?
References:  <3D854B7D.1060209@one.net>    <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com>   <3D87CE0A.9090609@something.invalid>   
Message-ID: <3D890FB0.4030408@something.invalid>

Martin v. L?wis wrote:

> Depends on your notion of "danger"; I usually associate it with fear
> and uncertainty :-)


Well, I *do* experience fear and uncertainty when
I find that the normally secure and predictable
environment of Python suddenly starts crashing
on me. It takes all the fun out of things.


> If you know it can crash when you do certain things, and you document
> that limitation, there is no danger. There are already ways to crash
> Python, the dlmodule being an example in the core distribution.


The problem in this case is that it's not something
*I* do which is going to cause the crash, it's
something done by the internals of some piece of
C code that I know nothing about. Something which
is not going to be documented, because it's a
perfectly legitimate and unremarkable thing for
C code to do.

So, the only way to find out whether a particular
extension is safe to use in Stackless is to try
it. And that only gives a definite answer when
the answer is "no, it's not safe". If it doesn't
crash, I still can't be confident that it won't
crash at some time in the future.

That's why I say that I would be nervous about
using Stackless. Not to say that would stop me
from using it, but I'd feel nervous while I was
doing it! :-)


> Also, readers should notice that your example requires Stackless to be
> used:


Yes, I understand that, and I acknowledge that it
won't cause any harm to have Stackless in the core
if the Stackless stuff is switched off by default.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg



From 2002 at weholt.org  Wed Sep 25 09:47:49 2002
From: 2002 at weholt.org (Thomas Weholt)
Date: Wed, 25 Sep 2002 13:47:49 GMT
Subject: What function called this function ??
Message-ID: <98jk9.22340$0p1.391334@news2.ulv.nextra.no>

Is it possible, by hacking the traceback/stack/etc, to get information about
the function, that functions class and in what module that function and
class are defined, from inside a function located elsewhere? Something like
a way of answering the question of  "who called me?" without sending the
answer along as a parameter.

Best regards,
Thomas




From notvalid at hotmail.com  Tue Sep 24 13:45:03 2002
From: notvalid at hotmail.com (jano)
Date: Tue, 24 Sep 2002 10:45:03 -0700
Subject: cgi post problem
References:  <9aWj9.39314$V7.10439005@twister.socal.rr.com>
Message-ID: 

"Jeff Davis"  wrote in message
news:9aWj9.39314$V7.10439005 at twister.socal.rr.com...
> Hi,
>
> It looks as though you have a lot of code. It might be helpful to try to
> narrow the problem further by removing a lot of the code unrelated to your
> problem, which appears to be that "keys" does not contain any items. After
> you work that out, then put the other code back in.
>
> My first impression is that you have some "weird" form element names
> because they contain the "/" character. That might be perfectly legal, but
> perhaps the cgi.FieldStorage class does not properly handle such element
> names, or perhaps it considers such names erroneous.
>
> Next, it seems that the line "keys = form.keys()" might be out of
alignment
> with the rest of the code in it's block. Perhaps it's just the way it
> looks after you copied your code into the post.
>
> Regards,
>         Jeff
>
>



Yes, the problem is that keys does not contain any items.  The 'weird' names
are not the problem, because i tried it also with regular 1-word names (no
slashes), with the same results.  Also, the keys=form.keys() line is
properly indented in the code -- it was just a copy/paste problem.  Here is
the code again, with the extraneous stuff stripped out:

#!/usr/local/bin/python

import cgitb; cgitb.enable()
import sys, traceback, cgi

def main():
    try:
        form = cgi.FieldStorage()
        input = form.keys()

        print "Content-type: text/html\n\n"
        print("""
        
        
            
                test
            
            """)
        print "

",keys,"

" print "" except: pass if __name__ == "__main__": main() And the form is:
The script, again, is currently just supposed to return the keys, which I am expecting to be Name, PartNumber, etc., but it returns only an empty list. Any ideas. thanks, jano From rond at ixsys.com Thu Sep 5 11:30:11 2002 From: rond at ixsys.com (Ron Darling) Date: Thu, 5 Sep 2002 10:30:11 -0500 Subject: What database should I use In-Reply-To: Message-ID: >> (though it's it considered obsolete now-a-days). This is only a consideration for the uni-formed or those that have never really used it. MS is still dumping lots of money into it. Just shipped v7.0 will be going into Beta with 8.0 in a couple of months. Amazing String capabilties. As a matter of fact there is now a VFP style .net class that moves a lot of the wonderful commands internal to VFP to .NET. I think the Fox Dev team created. Cursor Technology, Rushmore Speed and many other things have moved there way into not only Access but SQL Server and ADO. Due to the fact that each part of a table is its own file. .DBF is the table. .FPT is the Memo field .CDX is the index. The file size limitation of the OS of 2 gig is at the individual file level. In Access everything is stored in the same file (you could break up but not really meant to) so the 2 gig file size is limited to the app and data which is more than likely in the same file. I have dealt with lots of situations where the .DBF was 1.8 gig, the index was 1.2 gig and the FPT was another 1+ gig size. Indexes are stored in a .CDX file. A .CDX file can have as many as 255 indexes (take into account 2 gig file size). Each open table can have 10 open CDX's so you can have 2550 indexes on a table. Very Robust SQL pass Through for back end databases. There is nothing out there as fast as VFP for pure raw speed. SQL 2000 gets close but not quite there, the advantage to SQL as far speed goes is it does not bog down under load. Load means 25 + heavy users. As far as speed goes I have seen the return of queries on tables as large as 21 million records within seconds and that was pulling data across a 10 meg network with Foxpro For DOS. United We Stand (remember Ross Perot) member/prospect database. Sounds a little dated but the point is its been that way in Fox for a long time. Fox and VFP managed/tracked the military assets to the Persian Gulf and is till in use. Manages the flow of info for Chunnel. It is far more prevalent than most realize. Very good OOP. It seems that VFP is becoming known for the best language that can really implement the "Abstract Factory Pattern" Very good interface. Rich Native Controls (No OCX) and does very well with OCX's. Easy Distribution. (Drop a couple of DLLS into system directory not reg) Rich Debugger. Can access any data ODBC, ADO or ADO.Net can access. Internal XML. Select Result set from SQL into a local cursor then use CURSORTOXML(). With the XMLTOCCURSOR() and CURSORTOXML() commands it is very easy to build thin wire apps. Bind the interface to the cursor. I can try any and all commands from the command prompt and even from within a debugging suspend. Pretty much interrogate the entire system at hand very easily from a suspend. Many options for hanging VFP behind IIS and ISAPI. You can create com objects and run behind other languages even from within SQL Server or visa versa. One of the most robust SOUNDEX/Fuzzy Search add-ons available with the PHDbase Library. You can index memo fields and do 2 - 3 second searches on huge amounts of memo data. Best Table Repair Libraries that I am aware of are available. Error trapping has been far superior to VB and a lot of languages since the Fox 2.0 days (1992). Last but not least http://www.universalthread.com. Great support from all over the world. obsolete...hmmmmm maybe lack of exposure or conflicting marketing problems with MS owning Access, SQL and Fox but certainly not obsolete. -----Original Message----- From: activepython-admin at listserv.ActiveState.com [mailto:activepython-admin at listserv.ActiveState.com]On Behalf Of Sathish Chandrasekaran (S) Sent: Thursday, September 05, 2002 9:24 AM To: printers at sendme.cz; python-list at python.org; tutor at python.org; activepython at listserv.activestate.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: RE: What database should I use In that case MS-access will be better on the size issue. But on the other hand if u want ur application to be flexible and ease of use I would rather suggest FoxPro (though it's it considered obsolete now-a-days). Here Is A Test To Know Whether The Mission Of Your Life Is Over . If You Are Alive It Isn't . Sathish C Infra-Amdocs -----Original Message----- From: A [mailto:printers at sendme.cz] Sent: 05 September 2002 15:21 To: python-list at python.org; tutor at python.org; activepython at listserv.ActiveState.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: What database should I use Hello, I am going to program a small application (in Python and wxPython) which consists about 2000 - 3000 records . Can you please recommend which database is the best for that. I use Windows. Maybe MS Access or FoxPro or MySQL or better? I want to keep the program as small as possible. Thanks Ladislav _______________________________________________ ActivePython mailing list ActivePython at listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython _______________________________________________ ActivePython mailing list ActivePython at listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython From tdelaney at avaya.com Sun Sep 29 20:31:39 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 30 Sep 2002 10:31:39 +1000 Subject: comparing all values of a list to regex Message-ID: > From: Alex Martelli [mailto:aleax at aleax.it] > > Delaney, Timothy wrote: > ... > >> > elif matches != len(alist): > >> > match_list = match_some > >> > > >> > match_list.append(alist) > >> > >> Yes, choosing a list first and then appending to the chosen > >> list is nicer, but you cannot do that within the original > >> specs (for all I know the match_some list might grow > >> unbearably large over time, in this case). > > > > Hmm - why not? Ignoring that the original specs didn't > actually *have* > > that case, > > Not ignoring it, one would think the specs must be to do nothing > special in that case. > > If your program was specified to "append to list1 if the time is > exactly 11:22:33, to list2 if the time is exactly 17:26:35", would > you consider it reasonable to make your program appent to list3 > if it's any other time of day? Well, of course. I thought you were talking about the implementation (since you yourself mentioned the unspecified case) - not the conformance to the specs. Not having that case in the specs is not a cause for simply ignoring it. What you should instead to is get an explicit statement of what is to occur in that case into the specs (e.g. if more than one match is found, but not everything, the line should be ignored). It was an *incomplete* specification, which would require querying by the (usually) system engineer in order to produce complete specifications. If such specs made it to a developer I should bloody hope that they would say "and what should I do in this case?". Tim Delaney From itamar at itamarst.org Mon Sep 30 18:06:33 2002 From: itamar at itamarst.org (Itamar Shtull-Trauring) Date: Mon, 30 Sep 2002 18:06:33 -0400 Subject: ANN: Bannerfish 0.1.1 - banner ad server Message-ID: <20020930180633.2cd106cc.itamar@itamarst.org> Apologies if this appears twice, my ISP's NNTP server doesn't seem to like me. Bannerfish banner ad server ============================= This is the first public announcement of Bannerfish, v.0.1.1, a banner ad server for small to medium sized websites. The latest version of Bannerfish should always be available from: http://itamarst.org/software/bannerfish/ Features ---------- - Supports images and Flash - Embeds ads using javascript, so it should work with any web platform - Weighting and multiple ads per page - Lets customers view banner stats (clicks and views) - Automatic deactivation of ads The goal of Bannerfish is to be a small, simple banner ad server sufficient for the needs of small websites. Requirements -------------- Twisted 0.99.2 or later Python 2.2 Bannerfish has been tested under Debian GNU/Linux, but should work fine under other Unix-like systems and on Windows as well. Author and Licensing ---------------------- Bannerfish was written by Itamar Shtull-Trauring (itamar at itamarst-DOT-org). Bannerfish is licensed under the GPL, but licensing under other terms can be arranged - send me an email. -- Itamar Shtull-Trauring http://itamarst.org/ Available for Python, Twisted, Zope and Java consulting From llothar at web.de Wed Sep 18 09:16:54 2002 From: llothar at web.de (Lothar Scholz) Date: Wed, 18 Sep 2002 15:16:54 +0200 Subject: Will "Python in a Nutshell" be too short? References: Message-ID: On Tue, 17 Sep 2002 19:46:21 +0100, Hamish Lawson wrote: >Many of us were hoping that "Python in a Nutshell" would not only be a >comprehensive reference of pretty much all of the modules in the standard I never understood why people wants another reference to Python other then the standard online documentation. We should concentrate on this rather then on everything else. But currently they seem to be written in stone. The annotated PHP manual is a complete other dimension of documentation with active development. You don't have to write a PEP before changing a sentence. >library that aren't obsolescent or platform-specific, but would also cover >some of the most popular third-party libraries - e.g. DB-API, PIL, >mxDateTime, Numeric, win32all, wxPython, mod_python, ReportLab. Here comes another problem. You can't write a simple 40 page introduction. What we really need are not books for beginners but books for advanced programmers. There is too much garbage in the bookshelfs (even in the python bookshelf) of my favorite shop. Perhaps i'm to frustrated but is education really so low in the python community that you must explain simple method calls or thinks like this ? I would like to see a detailed description about the actions that must be done on every method call by the interpreter with references to the c source code. From see_reply_address at something.invalid Mon Sep 2 00:38:58 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 02 Sep 2002 16:38:58 +1200 Subject: ANN: Pyrex 0.4.4 Message-ID: Pyrex 0.4.4 is now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ New Features: * Tracebacks: Pyrex modules now produce tracebacks that show you where the error occurred in the Pyrex code. * ",".join(x) and the like now work. * Float literals don't require digits on both sides of the point. There are also some other minor improvements and bug fixes. See the CHANGES file in the distribution for a full list. What is Pyrex? -------------- Pyrex is a new 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. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From leif at crysberg.dk Fri Sep 6 10:29:54 2002 From: leif at crysberg.dk (Leif Jensen) Date: Fri, 6 Sep 2002 16:29:54 +0200 (CEST) Subject: What database should I use In-Reply-To: <3D77763F.23080.BFAFA3@localhost> Message-ID: PostgreSQL, no doubt, if you use Linux, WinNT or possible WinXP ! Leif On Thu, 5 Sep 2002, A wrote: > Hello, > I am going to program a small application (in Python and wxPython) which consists about > 2000 - 3000 records . Can you please recommend which database is the best for that. I > use Windows. > Maybe MS Access or FoxPro or MySQL or better? > I want to keep the program as small as possible. > Thanks > Ladislav > > > _______________________________________________ > wx-users mailing list > wx-users at lists.wxwindows.org > http://lists.wxwindows.org/mailman/listinfo/wx-users > From peter at engcorp.com Tue Sep 24 21:19:36 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 24 Sep 2002 21:19:36 -0400 Subject: Non-interpreted Python? References: <3D8F65A4.38124945@engcorp.com> Message-ID: <3d910f20$1@news.sentex.net> Tapio Kelloniemi wrote: > Peter Hansen wrote: > >>There are other approaches, but there's no point describing them until >>you explain *why* you want to do this. What are your requirements? > > I'm using Linux and searching for a good high-level language to use in > my projects. I don't have any special ideas, it depends on language. I > don't like the idea of using any interpreted language, but have heard so > much good about Python. I have used mostly C before and so it would be > best to give up my speed requirements. Python is definitely a "good high-level language" for a vast range of projects. We use it in my company for many things including internal utilities, a factory automated testing system for wireless telecom products, our Intranet (via Zope), and as the primary language (98% of the code) in several of our main products. I think you would be well advised to let go your fear of using an "interpreted" language, since unless you are writing device drivers for a living you are unlikely to experience performance bottlenecks in most situations you'll encounter. On the other hand, there are *significant* advantages which you will NOT find using non-interpreted languages, and these in many cases outweigh the few disadvantages. A common expression around here is that developer time is worth far more than CPU time, and in this respect Python has shown itself capable of significantly increasing productivity in many instances. >>>Or better, if it is possible to compile code into object format and then >>>link with C/C++/whatever code. >> >>Python has excellent facilities for embedding in applications written >>in C/C++. Check the documentation for the relevant sections. > > I have thought of writing some parts of programs in Python (some kind of > library) and then be able to use it in C++/Ruby/anything else, if it is > possible. Excellent idea. Why not take the approach many do, of writing the whole application in Python and then (once it's working) rewriting only those parts which profiling shows have performance problems? -Peter From see_reply_address at something.invalid Tue Sep 24 22:30:57 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 25 Sep 2002 14:30:57 +1200 Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <%8ci9.138477$5r1.5541622@bin5.nnrp.aus1.giganews.com> Message-ID: <3D911FE1.1050801@something.invalid> thp at cs.ucr.edu wrote: > But why use grotesque hacks in the first place? "a ? b : c" is a > well-established syntax for conditional expressions. Why doesn't > Python simply adopt it? I believe because Guido (a) thinks it's ugly and (b) doesn't think it would add enough to the language to be worth including. Personally, I rather like a if b else c but Guido doesn't like that either, unfortunately. Perhaps I'll slip it into Pyrex when no-one's looking...:-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jepler at unpythonic.net Tue Sep 10 16:53:58 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 10 Sep 2002 15:53:58 -0500 Subject: run-mailcap in python? In-Reply-To: <3D7E016D.2646AD9F@engcorp.com> References: <3d7de60b$1@news.sentex.net> <3D7E016D.2646AD9F@engcorp.com> Message-ID: <20020910205355.GD15936@unpythonic.net> On Tue, Sep 10, 2002 at 10:27:57AM -0400, Peter Hansen wrote: > Thomas Guettler wrote: > > > > Peter Hansen schrieb: > > > import os > > > if os.name == 'posix': > > > def startfile(name): > > > os.system('run-mailcap "%s"' % name) > > > os.startfile = startfile > > > > Yes, ugly but it works. Thank you! > > In Pythonia, "ugly" is sometimes spelled "pragmatic". Of course, what if it's arranged for name to equal '"; rm -rf / & echo you're a loser"' ? If an attacker controls the string (eg by supplying it from e-mail or a web page), you're sunk. this should be safe, at least as long as run-mailcap doesn't commit the same kind of error: os.spawnvp(os.P_WAIT, "run-mailcap", ["run-mailcap", name]) Jeff From pinard at iro.umontreal.ca Thu Sep 26 11:36:58 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Thu, 26 Sep 2002 11:36:58 -0400 Subject: RELEASE: Recodec 0.0 Message-ID: Hello to all `recode' pretesters and Python friends. Here is the initial throw for the Recodec program and library. Recodec is the start of a Python prototype for Free Recode. See `Recodec and Free Recode' in the `README' file to know how they relate to one another. The Recodec program and its library, as Free Recode already do, convert files between character sets and usages. They recognise or produce more than 240 different character sets and transliterate files between almost any pair. When exact transliteration are not possible, they get rid of offending characters or fall back on approximations. The `README' is repeated as `http://www.iro.umontreal.ca/~pinard/recodec/', and `http://www.iro.umontreal.ca/~pinard/recodec/Recodec.tar.gz' holds the latest release. This is more a snapshot than a finished release, actually. This is still alpha quality software, which should not be used without caution in a production environment. Pretesters are welcome. Please gently report problems, suggestions or other comments to `mailto:pinard at iro.umontreal.ca'. Recode-related discussions might be held on `mailto:recode-forum at iro.umontreal.ca', this list is opened to its members only. Python specific discussions might go to `mailto:python-list at python.org'. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From gerhard.haering at opus-gmbh.net Wed Sep 4 12:09:33 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 4 Sep 2002 16:09:33 GMT Subject: Please help in calling python fucntion from 'c' References: Message-ID: Terry Reedy wrote: >> [ The information contained in this e-mail is confidential and is > intended for the named recipient only. If you are not the named > recipient, please notify us by telephone on +44 (0)1249 442 430 > immediately, destroy the message and delete it from your computer. > > I will gladly delete it, but expensive call? no. Pretty whacko. It obviously makes certain people feel safer. But if it really has any legally binding effect in any country, I'd like to stay away from that country. Btw. your header "X-DMCA-Complaints-To" makes me hope that the tries to get similar laws passed in the EU will fail. -- Gerhard From anton at vredegoor.doge.nl Fri Sep 27 12:26:07 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 27 Sep 2002 18:26:07 +0200 Subject: watching mutables? References: Message-ID: On Fri, 27 Sep 2002 09:34:55 -0500, "Mark McEahern" wrote: >l = Watched() >l.append(1) Thanks for reacting to my question. However, I am looking for something that calls a defineable function if *any* mutable variable in the current scope changes. Variables should be 'marked' to install this function for them. For example 'watch(m,f)' indicates that function f is called if mutable variable m is changed. I do not want function f to be a method of object m since I want object m to be *any* mutable python object and furthermore I do not want to change the orginal object. The call of function f would be triggered by *any* change of object m. This would make debugging (and some other things I am tinkering with) a lot easier. Is it possible? Regards, Anton. From walterm at parque.homelinux.net Mon Sep 9 23:38:26 2002 From: walterm at parque.homelinux.net (Walter Moreira) Date: Tue, 10 Sep 2002 00:38:26 -0300 Subject: RPy / Win2k In-Reply-To: References: Message-ID: <20020910033826.GB21801@parque.homelinux.net> On Tue, Sep 10, 2002 at 01:09:18AM +0100, Duncan Smith wrote: > ... [About a Windows release of RPy] ... > > Thanks Walter, that's good news. When I spoke to Brian he said that R could > not be built as a shared library under Windows. Does this mean I won't need > to reinstall R? Cheers. Yes, you don't need to compile neither R nor Python. The binary distributions already provide the dll's. I'm trying to make the installer to find automatically the location of the R library. Regards: Walter From jdavis at empires.org Thu Sep 19 02:36:34 2002 From: jdavis at empires.org (Jeff Davis) Date: Thu, 19 Sep 2002 06:36:34 GMT Subject: [Help]: mailbox classes References: Message-ID: Ok, I'll assume your using mbox format, but this is easily adapted for maildir, etc. import mailbox mbox_file = '/path/to/mbox' mbox_fp = open(mbox_file) mbox = mailbox.UnixMailbox(mbox_fp) msg = mbox.next() there, now you have a message object (a rfc822.Message object, to be exact). Now just import the rfc822 module and do whatever you need. You'll probably want to use a loop to process all of the messages. Regards, Jeff > Hi, > > I am trying to extract a message from a unix mailbox file. Python does > provide few classes for easy and uniform access. So it says! After > having read the libiary references, I went nowhere. > > Can anyone give me an example as how to use these mailbox classes and > what is it relationship with email.message classes. > > thanks From Oschler at earthlink.net Fri Sep 6 16:14:08 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Fri, 06 Sep 2002 20:14:08 GMT Subject: Larry Wall's comment on python... References: <3D7958DB.50903@nospam.free.fr> Message-ID: "laotseu" wrote in message news:3D7958DB.50903 at nospam.free.fr... > > Any comments? > > def fun(args): > #BEGIN > if ceci or cela: > #BEGIN > do_this(with_that) > [snip a lot of code] > #END > #END > > laotseu, Although new to Python, I've read many posts complaining about the indenting issue, usually from "other language" proponents. But for the longest time I wondered why not do exactly what you have done with comment lines? In essence I'm saying, I'm glad you made this point. :) In Pascal, C/C++ and VB (no rock-throwing please, it was a paycheck) I frequently did things like the following, to use a C example: if (something == something_else) { } // if (something == something_else) As you can see, using comments to label my end blocks explicitly. For me this issue was never an issue. thx From chris.walsh at real-sense.com Wed Sep 11 19:58:21 2002 From: chris.walsh at real-sense.com (Chris Walsh) Date: 11 Sep 2002 16:58:21 -0700 Subject: Getting __builtins__ into my local dictionary References: <1691b372.0209110828.31501d82@posting.google.com> Message-ID: <1691b372.0209111558.33c2990@posting.google.com> chris.walsh at real-sense.com (Chris Walsh) wrote in message news:<1691b372.0209110828.31501d82 at posting.google.com>... > Hi All, > > I know this may sound like I am repeating a much discussed topic but I > want to create a multiple environments within the one Python > interpreter so that each envronment contains it's own local defs and > attributes but also understands functions such as str() (e.g. contains > __builtin__ module). > > This is how I think I should do it: > > ================START=OF=CODE================ > PyObject *pMyMod = PyModule_New("unique000"); > PyObject *pMyDict = PyModule_GetDict(pMyMod); > > PyDict_SetItemString(pMyDict, "__builtins__", PyEval_GetBuiltins()); > > PyObject *pResultT; > pResultT = PyRun_String("dir()\n", > Py_eval_input, pMyDict, pMyDict); > DumpAndRelease("dir()", pResultT); > > pResultT = PyRun_String("dir(__builtins__)\n", > Py_eval_input, pMyDict, pMyDict); > DumpAndRelease("dir(__builtins__)", pResultT); > =================END==OF=CODE================ > > The results I get from my Dump module (which just throws out the > contents of pResultT) is: > > ================START=OF=DUMP================ > dir() > List of 3 items: ['__builtins__', '__doc__', '__name__'] > > dir(__builtins__) > List of 37 items: ['__class__', '__cmp__', '__contains__', > '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', > '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', > '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', > '__reduce__', '__repr__', '__setattr__', '__setitem__', '__str__', > 'clear', 'copy', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', > 'itervalues', 'keys', 'popitem', 'setdefault', 'update', 'values'] > =================END==OF=DUMP================ > > But... if I do a "dir(__builtins__)" from the Python interpreter there > are 118 items (not 37) including amongst other stuff, the str() > function. > > How do I create my own module/dictionary which contains the > __builtin__ module which contains all the handy functions that > "dir(__builtins__)" shows up from the interpeter? > > Kind Regards, > > Chris. PS: My Python dir(__builtins__) lists the following on startup: ================START=OF=PYTHON=============== Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeError', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', 'setattr', 'slice', 'staticmethod', 'str', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] =================END==OF=PYTHON=============== From wlfraed at ix.netcom.com Sun Sep 29 19:31:56 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 29 Sep 2002 16:31:56 -0700 Subject: tkinter & serial port References: Message-ID: user at domain.invalid fed this fish to the penguins on Sunday 29 September 2002 02:30 pm: > > How do I do this or its moral equivalent under Python so that it > runs without modification under both BSD and Windows? The closest Jump on Bill Gates a few times so he changes windows to allow any data stream in a select() > that I've been able to figure out is to poll the serial device > a few times per second. This is ugly, involves overhead and generally > not up to the standard of Python -- clearly I don't yet 'see the > light.' > Possibly put the serial device I/O into a separate thread, package up the lines, and send them using a socket protocol which you can then use with select? -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From gq437x at yahoo.de Wed Sep 25 04:05:42 2002 From: gq437x at yahoo.de (Volker Apelt) Date: 25 Sep 2002 10:05:42 +0200 Subject: summary: (was: callback + __call__ + TypeError: unbound method; on non method) References: Message-ID: ## Thank you, Alex Martelli for your help on this problem. Problem: Python 2.1.1. took a reference to a function stored in a class attribute as a class method. Calling that function through an object instance was not possible. Solution for 2.2 + Workaround for python < 2.2: In Python 2.2 use staticmethod(). For Python < 2.2 (eg: tested with 2.1.1) use a class replacement for staticmethod and add a second group of () to the call. Example: import time def call_me(): return time.time ## workaround for python < 2.2 class staticmethod: def __init__(self, func): self.func = func def __call__(self, *args, **kwds): return self.func(*args, **kwds) class Callback_good: """ """ _default_Func = staticmethod(call_me) #class wide default callback function def __init__(self): """ """ self._m_func = Callback_good._default_Func def __call__(self): """ """ # uncomment one of these #return self._m_func()() # for python < 2.2 #return self._m_func() # for ptyton >= 2.2 x = Callback_good() ## both prints are equal print time.time print x() -- Volker Apelt From kkto at csis.hku.hk Fri Sep 6 09:22:57 2002 From: kkto at csis.hku.hk (Isaac To) Date: 06 Sep 2002 21:22:57 +0800 Subject: Dictionary... References: <7ir8g7xqqk.fsf@enark.csis.hku.hk> Message-ID: <7iheh3qmku.fsf@enark.csis.hku.hk> >>>>> "Raymond" == Raymond Hettinger writes: Raymond> Hello Issac, Try looking at seqdict in the Vaults of Parnassus: Raymond> http://home.arcor.de/wolfgang.grafen/Python/Modules/Modules.html Ah... after I read this it makes sense again now, since Python map is not comparison based. Perhaps I've got the wrong idea from the beginning... Raymond> Your other ideas were good too. The auxilliary map of Raymond> successors and precessors is likely to be the fastest. To Raymond> efficiently update a sorted python list, try the bisect module. But difficult to code. I've to maintain 3 data structures instead of 1. Well... perhaps time to write a class. =) Regards, Isaac. From phlip_cpp at yahoo.com Tue Sep 3 00:38:24 2002 From: phlip_cpp at yahoo.com (Phlip) Date: Tue, 03 Sep 2002 04:38:24 GMT Subject: opening 'file open' dialog from console References: Message-ID: <41Xc9.1255$Qz2.231397557@newssvr16.news.prodigy.com> dsavitsk wrote: > I would like to open a file open dialog from a console on windows (2000). > I do this now using the line > >>>> from tkFileDialog import * >>>> fileName = askopenfilename(filetypes=[(".txt", ".txt")], title="Select > the file") > > but this opens a second window and leaves it there. what is the best way > (tkinter or MFC) to do this w/o the second window? Fetch the root singleton (or whatever it is) out of Tk land: root = Tk() Withdraw it: root.withdraw() Warning: Sometimes this withdraws the wrong thing. >sigh< Alternately, pass it into 'askopenfilename', if possible. -- Phlip http://www.greencheese.org/ParodyMode -- Have a :-) day -- From martin at v.loewis.de Thu Sep 5 03:41:07 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 05 Sep 2002 09:41:07 +0200 Subject: tk8.4 in python22 ? References: <3D76FFB4.FE5EF48A@ipm.fhg.de> Message-ID: Markus von Ehr writes: > I'd like to use tk8.4 with python22, in fact the windows installer > installs tk8.3. How can I replace tk8.3 to 8.4? Do I have to > compile any python files? You will need to recompile _tkinter.pyd, using the Tcl 8.4 headers and import libraries. Regards, Martin From dbasch at yahoo.com Sun Sep 29 22:22:47 2002 From: dbasch at yahoo.com (Derek Basch) Date: Sun, 29 Sep 2002 19:22:47 -0700 (PDT) Subject: Catching user defined exceptions from foreign modules Message-ID: <20020930022247.86781.qmail@web20810.mail.yahoo.com> Hello, I have defined 2 simple modules, test1 and test2. test1 calls the run function of test 2 which returns a user defined TestError function. I then catch the exception in test1 and perform a print. Heres the code: http://www.geocities.com/dbasch/test1.txt http://www.geocities.com/dbasch/test2.txt So, this code works fine for me. However, I have 2 much larger modules that have the same code structure but in these larger modules the test1 refuses to catch the raised TestError unless I change the except clause to: except test2.TestError: print 'fudge' I know that TestError has been imported because I can put a "print TestError" before the except clause in test1 and I get "test2.TestError". Can anyone tell me why I am having to put the test2.TestError instead of just TestError? It confuses me even further that my small test modules work like I would expect and it doesn't work on the larger modules. Thanks for the help, Derek Basch __________________________________________________ Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! http://sbc.yahoo.com From aleax at aleax.it Sun Sep 15 03:39:38 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 15 Sep 2002 07:39:38 GMT Subject: Tkinter in PyRun_SimpleString(char* s) References: Message-ID: <_OWg9.109539$pX1.3874894@news2.tin.it> Torsten Mohr wrote: > Hi, > > it doesn't seem to be as easy as i thought to load a script > from a C program and execute it, if i import Tkinter, it fails: ... > File "/usr/lib/python2.1/lib-tk/Tkinter.py", line 1476, in __init__ > baseName = os.path.basename(sys.argv[0]) > AttributeError: 'sys' module has no attribute 'argv' As you can see, the problem is with sys.argv, which you have not set. You can set it up from the Python code you execute, before you import Tkinter, or with C-API call PySys_SetArgv. Alex From maarten at tccn.info Wed Sep 18 07:10:20 2002 From: maarten at tccn.info (Maarten van Hulsentop) Date: 18 Sep 2002 04:10:20 -0700 Subject: 'Real' global (write var to different namespace) Message-ID: <29242dfa.0209180310.94c915d@posting.google.com> Hi y'all I'm sorry if it's a FAQ but i honestly can't find to solution to my problem; i've created a 'store' (a class) to store vars using the (really cool) pickle classes. Now i can store a var doing: "mystore['varname'] = myvar" and read it again by "myvar = mystore['varname']". My question is if it's possible to create a function like 'mystore.RestoreVars()' that sets ALL the stored vars in the _calling_ namespace at once. Hope it's clear enough, i'm still a python newbie so excuse me if i used the wrong terms or if i didn't explain it enough. Thanks Maarten van Hulsentop From totoNOSPAM at toto.fr Tue Sep 24 05:52:06 2002 From: totoNOSPAM at toto.fr (toto) Date: Tue, 24 Sep 2002 11:52:06 +0200 Subject: embedding Python in C Message-ID: <3D9035C6.BAC23A90@toto.fr> Hello, I try to use a simple programme to try to run Python code from C by calling the PyRun_SimpleString API function. But I have the following problem when I compile the programme C : ------------------------------------------------ bash-2.04$ make -f usermod.mak gcc embed-usermod.o /local/edf-python-2.1.1/lib/python2.1/config/libpython2.1.a -L/usr/lib -L/usr/X11R6/lib -lgdbm -ltk8.3 -ltcl8.3 -lX11 -lm -ldl -g -export-dynamic -o embed-usermod /local/edf-python-2.1.1/lib/python2.1/config/libpython2.1.a(posixmodule.o): In function `posix_tmpnam': /usr/src/redhat/BUILD/Python-2.1.1/./Modules/posixmodule.c:4212: the use of `tmpnam_r' is dangerous, better use `mkstemp' /local/edf-python-2.1.1/lib/python2.1/config/libpython2.1.a(posixmodule.o): In function `posix_tempnam': /usr/src/redhat/BUILD/Python-2.1.1/./Modules/posixmodule.c:4168: the use of `tempnam' is dangerous, better use `mkstemp' /local/edf-python-2.1.1/lib/python2.1/config/libpython2.1.a(thread.o): In function `PyThread_start_new_thread': /usr/src/redhat/BUILD/Python-2.1.1/Python/thread_pthread.h:135: undefined reference to `pthread_create' /usr/src/redhat/BUILD/Python-2.1.1/Python/thread_pthread.h:159: undefined reference to `pthread_detach' /local/edf-python-2.1.1/lib/python2.1/config/libpython2.1.a(posixmodule.o): In function `posix_openpty': /usr/src/redhat/BUILD/Python-2.1.1/./Modules/posixmodule.c:1754: undefined reference to `openpty' /local/edf-python-2.1.1/lib/python2.1/config/libpython2.1.a(posixmodule.o): In function `posix_forkpty': /usr/src/redhat/BUILD/Python-2.1.1/./Modules/posixmodule.c:1785: undefined reference to `forkpty' collect2: ld returned 1 exit status make: *** [embed-usermod] Erreur 1 ------------------------------------------------ If some of you can give me some ideas of this problem ? Thank you very much. Yang From jhorneman at pobox.com Mon Sep 30 02:51:00 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: Mon, 30 Sep 2002 08:51:00 +0200 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <3d976fbc$0$23666$91cee783@newsreader02.highway.telekom.at> <8428na.7vj.ln@ix.netcom.com> <3d979184$0$20332$79c14f64@nan-newsreader-03.noos.net> <8sf8na.86m.ln@ix.netcom.com> Message-ID: <3d97f3f4$0$32596$91cee783@newsreader02.highway.telekom.at> "Dennis Lee Bieber" wrote in message news:8sf8na.86m.ln at ix.netcom.com... > Guy Rabiller fed this fish to the penguins on Sunday 29 September 2002 > 04:49 pm: > > > > > yes it works on MS-DOS too. > > > Ah, good to know... Dennis Reinhardt was right: it doesn't work in the Win98 DOS shell. > Still need -vv to get the details from import though; -v just says > "not found" Ah, I thought the -vv was a typo. 'python -h' does not list 'vv' as an option. Thanks. Jurie. From jacek.generowicz at cern.ch Fri Sep 20 04:03:18 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 20 Sep 2002 10:03:18 +0200 Subject: strong/weak - dynamic/static [Was: Getting started] References: <5ami9.114674$ub2.2440492@news1.tin.it> Message-ID: Alex Martelli writes: > Jacek Generowicz wrote: > ... > > Could someone provide a serious reference ... > For example, Amer Diwan's lessons on Fundamentals of Programming > Languages at the University of Colorado ... > and the already-referenced URL gives some fundamental bibliography Thank you, Alex. From shalehperry at attbi.com Mon Sep 23 19:55:00 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Mon, 23 Sep 2002 16:55:00 -0700 Subject: Elementary confusion In-Reply-To: References: <878z1s1kqf.fsf@smtp.blueyonder.co.uk> Message-ID: <200209231655.00621.shalehperry@attbi.com> On Monday 23 September 2002 16:36, John Baxter wrote: > >>> a=0.1 > >>> b=0.2 > >>> c=a+b > >>> c==0.3 > > 0 > > >>> c > > 0.30000000000000004 > > >>> d=0.3 > >>> d > > 0.29999999999999999 > > > We "know" that c is 0.3. The computer has added two inexact values > which are "too big" and produced a result which is therefore both "too > big" and not the nearest representation of 0.3, which is "too small". > > --John Every C programming book I have ever read makes the comment that == and floating point do not mix. Just one the things you learn and accept. From andreas.ulbrich at gmx.net Mon Sep 23 10:11:04 2002 From: andreas.ulbrich at gmx.net (Andreas Ulbrich) Date: Mon, 23 Sep 2002 16:11:04 +0200 Subject: Session handling References: Message-ID: beachboy wrote: > Hi! > Please can anyone help me. > My problem: > I'm trying to program a web application with python. This tool has to > provide diffrent languages. The user has to choose the language at the > beginning. So i have to save the information which language the user > chooses. I think this is a perfect example for using sessions. > The only problem is I've got no idea how to realise this in python. > Please help me as soon as you can because I have to solve this problem > very quickly. > > hoping to hear from you soon > beachboy Whenever I need to write a web-application I do use jython and write servlets. This combines the power of Servlet/JSP with the worlds best programming language. a jython servlet would look like this: from javax.servlet.http import HttpServlet class MyServlet(HttpServlet) : def doGet(self, request, response) : session = request.getSession(1) lang = session.getAttribute('language') if not lang : # initialise the session (i.e. choose language) # produce output suitable to lang if lang == 'DE' : print >> res.writer, "Hallo Welt!" else : print >> res.writer, "Hello World!" There are other solutions. I believe that Zope offers session-management too. From jubafre at brturbo.com Mon Sep 23 17:53:44 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Mon, 23 Sep 2002 18:53:44 -0300 (GMT-03:00) Subject: list problem Message-ID: <-29615135.1032818024099.JavaMail.nobody@webmail2.brturbo.com> i have: x=[['0020', '0000x9'], ['0030', '0000xa'], ['00B4', '0000x8'], ['0030', '0000xb'], ['00F0'], ['0001'], ['0003'], ['0005']] and i want: y=['0020', '0000x9', '0030', '0000xa', '00B4', '0000x8', '0030', '0000xb','00F0', '0001', '0003', '0005'] how to do this? Juliano Freitas www.gebrasil.hpg.com.br From just at xs4all.nl Mon Sep 9 16:36:37 2002 From: just at xs4all.nl (Just) Date: Mon, 09 Sep 2002 22:36:37 +0200 Subject: Windows/DOS: double clicking a .py file References: <3h7f9.77472$l_4.28399@atlpnn01.usenetserver.com> Message-ID: In article <3h7f9.77472$l_4.28399 at atlpnn01.usenetserver.com>, "Steve Holden" wrote: > "Just" wrote in message > news:just-F18BA3.17425609092002 at news1.xs4all.nl... > [ how top see messages ] > > > > Thanks for both suggestions. Another workaround just occured to me: do a > > raw_input("type enter to exit") in an exception hook. That should work > > just fine in a py2exe-fied app as well I suppose. > > > > python -i > > will allow you to enter interactive statements after your execution > finishes, which can be useful when you're debugging. Actually, debugging on my side is not really the problem (I usually start the app from the command line anyway, it's a simple platform-neutral command line tool), but it's end users: they want to drop files onto the app. The DOS window can go away if everything went ok (it only displays some progress info), but not if an exception occurred: I want them to a) be able to tell something's wrong, and b) tell me _what_ went wrong ;-). The raw_input() call upon exception seems the easiest workaround for now. Just From usenet at wojas.vvtp.tudelft.nl Wed Sep 4 09:50:26 2002 From: usenet at wojas.vvtp.tudelft.nl (Konrad Wojas) Date: Wed, 04 Sep 2002 15:50:26 +0200 Subject: Why Python? References: Message-ID: Benjamin wrote: > Hi guys (and girls) > I just begun to learn how to program. And I choosed Python for > doing that. surfing around the web i found an article about this > language, they said it's the ideal language for beginners to the > world of programming. and i admit it, the syntax is very clear making > the code very readable, i learn easily the concepts of programming > and i soon wrote some nice programs. but since i finished my > newbie-tutorial, i am wondering about one question: is it worth to go > deeper into python? i talked to a friend of mine, he told me that i > should try php.. > what should i do?? ^_^ in other words: what is python good for? > why should i continue with python? I've been doing web development in PHP since 1998 and have written a content management system with a quite complex shopping cart system and a backoffice system to handle all sales. It's over 10000 lines of PHP code, excluding the html code. I've really had it with PHP, it's unmaintainable, ugly and slow. Errors like 'parse error on line 487' are not fun to work with. I really like python. The systax is a lot clearer, exceptions are great and I really love those stacktraces if an exception is not handles. Object oriented programming in PHP is a joke, it really sucks. And PHP is buggy. I've encountered numerous bugs, especially in the extension modules. XSLT in PHP? Forget it, the module will crash in 50% of the cases. And compiling PHP yourself with a lot of extension modules can be a real nightmare. And above all: python is a generic language, PHP is only useable for web development and small maintainance scripts. It doesn't have bindings for anything beyond web development. I'm still maintaining the PHP code I have written, but I use python for all new projects. Don't start big projects in PHP, you'll regret it ;-) Regards, -- Konrad Wojas From GavinT at ResMed.com.au Tue Sep 24 00:06:11 2002 From: GavinT at ResMed.com.au (Gavin Tomlins) Date: Tue, 24 Sep 2002 14:06:11 +1000 Subject: Python and activescripting within a host environment Message-ID: <362133AB12B2CE4EA3C01E12CD6CCC6E0254E0B7@osprey.corp.resmed.org> Greetings, We are still trying to solve one or two problems that we have with Python in a ActiveScripting host. Currently we can access COM based objects successfully from the python command line and perform normal operations. However, I was curious to know if people have any examples of products with ActiveScripting embedded within them that exposes a object model that can be utilised via Pythonscript. eg. (http://www.atozedsoftware.com/ FinalBuilder). In particular, we are unable to access variables from the host application. My understanding was that upon a request for a variable or unknown type it would be fired to the ActiveScripting engine to return the value or an error. eg. Within the hostapplication, they expose WindowTitle, ProjectVar Shouldn't I be able to do something simple like MyWindowTitle = WindowTitle MyProjectVar = ProjectVar or ProjectVar = "A new value" ie. above logic works with Vbscript etc. is there any special notation needed to identify host variables, or does the entire variable space of the host application become global to the python instance. Is there any documentation outlining the integrating or the absorption of such operations with Python and ActiveScripting. Regards Gavin Warning: Copyright ResMed. Where the contents of this email and/or attachment includes materials prepared by ResMed, the use of those materials is subject exclusively to the conditions of engagement between ResMed and the intended recipient. This communication is confidential and may contain legally privileged information. By the use of email over the Internet or other communication systems, ResMed is not waiving either confidentiality of, or legal privilege in,the content of the email and of any attachments. If the recipient of this message is not the intended addressee, please call ResMed immediately on +61 2 9886 5000 Sydney, Australia. From tismer at tismer.com Wed Sep 18 11:42:45 2002 From: tismer at tismer.com (Christian Tismer) Date: Wed, 18 Sep 2002 17:42:45 +0200 Subject: Stackless Python, eventual merge? References: <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <20020918060823.GB81158@hishome.net> <3D8880AC.7040902@tismer.com> <20020918181834.A27703@hishome.net> Message-ID: <3D889EF5.1080605@tismer.com> Oren Tirosh wrote: ... >>Just-need-an-idea-how-to-determine-that - ly y'rs - chris > > > Who says you have to determine that in advance? Just try. If the > extension actually calls the interpreter recusively it means that it > needs its own stack. Let it have exclusive ownership of the current OS > thread and its associated stack and allocate another thread from a > dynamic thread pool to continue tasklet scheduling. When the extension > returns back to nesting level 0 its thread will be released back into > the pool. This way a relatively small pool of OS threads can be used to > juggle a much larger pool of tasklets. This is of course an interesting idea. The reason why I thought I need to determine in advance is that I don't know when a new extension shows up on my stack. But when this happens, bazillions of tasklets may have been created already, and they have live cstack objects, which cannot be relocated (at least not in the near future). So they do need to use this one stack again. > This can also be a good way to handle extensions that make blocking I/O > calls like database engines - a relatively small pool of OS threads can > serve requests from a bigger pool of tasklets. This can be transparent: > when the number of concurrent requests exceeds the number of threads any > new request frames can be queued until a thread becomes available. The > level of concurrency for any resource can be tuned dynamically to > optimize the performance without affecting the overall structure of the > program. Sure, that's a thing I definately will do, if I can find a good solution to the other problem above. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From see_reply_address at something.invalid Thu Sep 26 19:28:28 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 27 Sep 2002 11:28:28 +1200 Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> Message-ID: <3D93981C.1030101@something.invalid> Pat Notz wrote: > Is there a short (one or two syllable) pronounciation for "__" (double > underscore). How about _ == "uh" __ == "uuuh" -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From llothar at web.de Sun Sep 15 21:28:59 2002 From: llothar at web.de (Lothar Scholz) Date: Mon, 16 Sep 2002 03:28:59 +0200 Subject: AspectP? References: Message-ID: <7cl9oucm65a4qr2tolm74gltqn7morbbm5@4ax.com> On Sun, 15 Sep 2002 08:13:34 -0500, "Mark McEahern" wrote: >[Robert Oschler] >> Anybody seen a robust (fairly ready for primetime) implementation >> of Aspect Oriented Programming for Python? > >Ignoring the criteria of robust... I think from this posting he has no problems in finding instable implementations. From eric.brunel at pragmadev.com Wed Sep 18 04:46:36 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 18 Sep 2002 10:46:36 +0200 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <6_Ph9.479711$q53.16315681@twister.austin.rr.com> Message-ID: Lee Gray wrote: [snip] > For a newbie, what's easier, Tk or wxWindows? Matter of taste, really... I do prefer Tkinter, because I find it far simpler than other GUI toolkits. But then, I've been into Tk for some years now, and maybe I'm too used to it. The first time I've looked at wxWindows and seen what's needed to open a simple window, it just made me run away screaming ;-). But seeing it again now, it's not that bad. See: http://www.wxpython.org/tut-part1.php In fact, example one in this tutorial would be much shorter in Tkinter than in wxWindows, but examples 2 & 3 would require much more code in pure Tkinter because of the status bar: it's apparently automatically managed by wxWindows, but not by Tkinter. Adding Pmw to Tkinter would make things easier ( see http://pmw.sourceforge.net ). For the record, here is the equivalent (untested) Tkinter+Pmw code for examples 1 & 3 in the wxPython tutorial: --- example 1 ------------------------- from Tkinter import * topWdw = Tk() topWdw.title("Hello from Tkinter") topWdw.mainloop() ---------------------------------------- --- example 3 ------------------------- from Tkinter import * import Pmw ## Main window topWdw = Tk() topWdw.title("Hello from Tkinter") ## Status bar statusBar = Pmw.MessageBar(topWdw) statusBar.pack(side=BOTTOM, fill=X) ## Helper for menu items helper = Pmw.Balloon(topWdw) helper.configure(statuscommand=statusBar.helpmessage) ## Function displaying about screen def showAbout(): showinfo('About Me', "This sample program shows off\n" "frames, menus, statusbars, and this\n" "message dialog.") ## Menus menuBar = Pmw.MainMenuBar(topWdw, balloon=helper) topWdw.configure(menu=menuBar) menuBar.addmenu('File', '') menuBar.addmenuitem('File', 'command', 'More information about this program', label='About', command=showAbout) menuBar.addmenuitem('File', 'separator') menuBar.addmenuitem('File', 'command', 'Terminate the program', label='Exit', command=topWdw.quit) topWdw.mainloop() --------------------------------------- Just see for yourself the one you find clearer. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From sismex01 at hebmex.com Wed Sep 18 10:59:53 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 18 Sep 2002 09:59:53 -0500 Subject: minimizing Tk programs to the taskbar Message-ID: > > Do properly-coded Tk extensions benefit Tkinter users > directly? Is there a way to load them? I doubt it, but > I haven't thought long about it ... > Of course there is, only it's kinda roundabout, and you have to declare a new type of widget, and play around with some Tkinter stuff, not very newbie friendly. I made bindings for the tkhtml and tktable extensions, and they more-or-less worked well; I didn't have enough time to keep pursuing it, so I didn't go very far; but they did work. HTH -gus -- Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From steve at ferg.org Sat Sep 7 08:01:05 2002 From: steve at ferg.org (Stephen Ferg) Date: 7 Sep 2002 05:01:05 -0700 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> Message-ID: "Joseph A. Knapka" wrote in message news:<3D798461.B3FE0E06 at earthlink.net>... > you probably shouldn't refer to the parent/child > relationship between UI elements as "binding", since > that will cause great confusion when you get around > to discussing the binding of events to code (using > the widget.bind() method). You're probably right. I'll see if I can't rewrite that. > Also, you should be aware of the "command" option I know about it, but I think that for beginners, it is very confusing. For one thing, it leads down the path to lambda, which is tricky enough itself. For another, it doesn't automatically pass an event object, which makes it even more difficult to use. So I think that beginners should consistently use the more plodding technique of explicit binding. But I should probably add a note to that effect. Otherwise, the avoidance of the "command" option might be confusing. Thanks for the feedback! :-) -- Steve From tjreedy at udel.edu Mon Sep 23 21:22:01 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Sep 2002 01:22:01 GMT Subject: writing in a file as binary mode???? References: Message-ID: wrote in message news:mailman.1032810110.30498.python-list at python.org... >i open the a file for writing in a binary mode, but doesnt work Depends what you mean by 'work'. On *nix, *all* read/write is binary mode. On Win*, the *only* difference is conversion of \r\n to \n on input and vice versa on output. >just the "f.write('\x03AHM ')" work, i open the file in the notepad and my file appears >like a text file and not as a binary file, i dont know why?? *All* files are string of binary digits. Notepad tries to interpret any file as as extended-ASCII text file as best it can. >>file.mem >AHM 0020 0000x7 0030 0000x8 0010 0000x9 00F0 0003 0002 0000 >>i have the file like this, how?? >AHM ? 0 ?  f ? That is how Notepad displays what it cannot properly interpret. Terry J. Reedy From bruce_deletethis_dawson at cygnus-software.com Sun Sep 22 01:19:25 2002 From: bruce_deletethis_dawson at cygnus-software.com (Bruce Dawson) Date: Sun, 22 Sep 2002 05:19:25 GMT Subject: Minimal debug/rep functionality References: Message-ID: <3D8D52D0.7050107@cygnus-software.com> On a tangential note... While doing some Python optimizing (for our about to ship Python based game) I tweaked the HAP Python debugger to count lines of Python code being executed. Then I displayed lines-of-code per frame in the game title bar. That turns out to be a very useful coarse indicator. Then I added the expression HeDbg.GetLineCount()[1] to the watch window. Since the GetLineCount() feature returns total lines executed and lines executed since the last call, and since the watch expression is evaluated each time control returns to the debugger, this simple expression tells me how many lines of code execute each time I step or go. So, if I step over a trivial looking function and the watch window says 700 then I investigate to find out whether 700 lines of Python executed for the function is reasonable. For profiling of a game I found this feature set worked really well. I don't think we've released an updated version of HAP that has this feature, but we certainly will - lots of other updates also. Mark wrote: > Hello all, > > In a nutshell, what I'd like to do is develop a utility that would print out > every line in a python program as the program executes (I may even just > want to print line numbers). I can see hints of how to do this in pdb (and > more directly in the underlying bdb class) and also in the code module. > > So, > > 1) Should I try and inherit a class and override some methods or should I > just pull out the relevant code and hand spin a small interpreter. > > 2) Anyone have a 20 liner solution for this? > > Thanks. > > Regards, > Mark > From SSchukat at dspace.de Fri Sep 20 10:41:59 2002 From: SSchukat at dspace.de (Stefan Schukat) Date: Fri, 20 Sep 2002 15:41:59 +0100 Subject: Python COM and variable number of arguments Message-ID: <84257D042AA7D411B3F700D0B7DB9B7C13B2FC@PDC-DSPACE> You just need the makepy generated wrapper and then you can just use named arguments: Object.Add(Item,After=3) Without the wrapper you are out of luck. Stefan > -----Original Message----- > From: Greg Green [mailto:gregory.p.green at boeing.com] > Sent: Thursday, September 19, 2002 10:36 PM > To: python-list at python.org > Subject: Python COM and variable number of arguments > > > I am using python with a third-party closed source application. It has > Visual Basic for Applications embedded in it for use as an extension > language. My question is what to do about com calls that have a > variable number of arguments in Visual Basic. It seems that I have to > use all of the arguments when I call the method using python. But I > don't know what to use for a value when I don't want that argument. > > For instance, In VB i can call the method .Add with 1, 2, or 3 > arguments. The 2nd and 3rd arguments are optional. In this case the > 2nd argument is called 'Before', and the 3rd is 'After'. So if I want > to add an item after the 3rd item. I do: > > .Add(Item,,3) > > In python I don't know what to use as the second argument: > > Object.Add(Item=Item,Before=????,After=3) > > In case you are wondering, I have tried 'None', or leaving off the > argument all together, but that doesn't work. :( > > Thanks for any replies. This is causing me a lot of pain. > > -- > > Greg Green > > -- > http://mail.python.org/mailman/listinfo/python-list > From robin at alldunn.NOSPAM.com Thu Sep 19 22:24:20 2002 From: robin at alldunn.NOSPAM.com (Robin Dunn) Date: Fri, 20 Sep 2002 02:24:20 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: Lee Gray wrote: [...] > Can someone point me to a good Python GUI app to demonstrate (other > than IDLE)? There are some new screen shots of apps written in wxPython at http://wxpython.org/screenshots.php -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From see_reply_address at something.invalid Thu Sep 19 21:17:41 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 20 Sep 2002 13:17:41 +1200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: <3D8A7735.3090403@something.invalid> Martin v. Loewis wrote: > That is not true. It is more reliable to inspect the source code. > > In general, it is very easy to do so: if there are no callbacks to > Python, the module is stackless-safe. That's a fair point, and I guess it takes care of the majority of extensions. But the cases where there is doubt are typically going to be big, complicated things like GUI libraries. Making a line-by-line inspection of one of those isn't exactly something you do over a cup of tea. And you don't just have to look at the code, you have to understand what it's doing, because the things which cause problems are dynamic rather than static features of the code. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From quiteblack at yahoo.com Wed Sep 25 01:05:32 2002 From: quiteblack at yahoo.com (black) Date: Tue, 24 Sep 2002 22:05:32 -0700 (PDT) Subject: about webbrowser.open~ Message-ID: <20020925050532.601.qmail@web21304.mail.yahoo.com> Hi, all~ I write something like this: webbrowser.open_new("http://www.python.org") it works, but it open the page with an old one, not the new page at all, what's wrong ? my OS is window2000 professional, thanx in advance~ --------------------------------- Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! -------------- next part -------------- An HTML attachment was scrubbed... URL: From mfranklin1 at gatwick.westerngeco.slb.com Mon Sep 16 04:46:16 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Mon, 16 Sep 2002 08:46:16 +0000 Subject: Tkinter listbox clicking problem In-Reply-To: References: Message-ID: <200209160846.16854.mfranklin1@gatwick.westerngeco.slb.com> Matthew, On Friday 13 Sep 2002 4:49 pm, Matthew Bonig wrote: > (lb.bind("", someFunc)) it calls function someFunc. Now, > someFunc() simply prints the curselection(). The problem is it's lagged... > if I first select list item 1 (index 0), and then 2, and then 3 (array Simply change the binding to >>> root=Tk() >>> lb=Listbox(root) >>> lb.insert("end", 1) >>> lb.insert("end", 2) >>> lb.insert("end", 3) >>> lb.insert("end", 4) >>> lb.pack() >>> def callback(event): ... print event.widget.curselection() ... print event.widget.get(event.widget.curselection()[0]) ... >>> lb.bind("", callback) '136346756callback' >>> ('0',) 1 ('1',) 2 ('2',) 3 ('3',) 4 ('3',) 4 ('2',) 3 ('2',) 3 ('1',) 2 ('0',) 1 ('1',) 2 ('2',) 3 ('3',) 4 HTH Martin -- ### Python Powered Signature I started writting this email on Mon Sep 16 08:40:42 2002 From marklists at mceahern.com Tue Sep 24 00:20:09 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 23 Sep 2002 23:20:09 -0500 Subject: Outlook 2002 and Python In-Reply-To: <03F53405C6ED434A986221919785A6A78C9339@nca-postal.ncaustin.com> Message-ID: [Paul Sage] >What: I saw an idea for a way to create a good SPAM filter for email. [snip] You might want to checkout: http://spambayes.sf.net/ // m - From eric.brunel at pragmadev.com Thu Sep 12 05:48:33 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 12 Sep 2002 11:48:33 +0200 Subject: class variable won't icrement! References: <3d8054ef$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: Gumuz wrote: > Hello everyone, > > I have something very strange and i can not understand it. probably, it's > not _that_ strange : ) > > I have this simple class which registers itself on a class variable in the > following code: > > ---------------------------------------------------------------------------- > ------ > class test: > dict = {} > id = 1 > def __init__(self, name): > self.dict[name] = self > self.id = self.id + 1 > > def show(self): > print "class variable dict element count: ", str(len(self.dict)) > print "class variable id: ", self.id > ---------------------------------------------------------------------------- > -------- > > now, look at the following: > >>>> john = test("john") >>>> frank = test("frank") >>>> bill = test("bill") >>>> bill.show() > class variable dict element count: 3 > class variable id: 2 >>>> frank.show() > class variable dict element count: 3 > class variable id: 2 > > The dict variable acts fine, maintaining it's content throughout every > instance of the class. > The id variable however, seems to be only incremented within the instance. > In the end this variable should've been 4. > > Could someone explain this to me? Is there something about class variables > whta i should know? Yep: to access them, you'd better always use the syntax .. Instances do in fact "inherit" the attributes of their class, but it leads to misunderstandings just as yours. In your example, here is what happens: > class test: > dict = {} Here, you create an attribute dict for class test. The value for this attribute is an *object*, which is *mutable*, that happens to be an empty dictionary. > id = 1 Here, you create an attribute id for class test. The value for this attribute is an *integer*, which is *not* an object, and is *immutable*. > def __init__(self, name): > self.dict[name] = self Here, you use the attribute dict, inherited from the class, and you modify it. These modifications happens *in place*, which means that the pointed dictionary is actully modified. Since both test.dict and self.dict point to the same object, they'll both see the modification. This is exactly the same if you do: a = {} b = a b['foo'] = 'bar' print a You'll see that a has been modified. In your example, here is roughly what happens: test.dict = {} self.dict = test.dict # Implicit inheritance from class to instance self.dict[name] = self > self.id = self.id + 1 This is a completely different story: here, you *recreate* an instance attribute named id, based on the id attribute inherited from the class. So, in fact, you're doing: test.id = 1 self.id = test.id # Again, implicit inheritance from class to instance self.id = self.id + 1 just as in: a = 1 b = a b = b + 1 print a Of course, a is not modified here... I always found that inheritance of class attributes to instance attributes was really misleading, and I even think it would be better if it were simply removed from Python. IMHO, it would far more conform to the "explicit is better than implicit" rule that is one of the basis of Python. To avoid its drawbacks: - never declare as a class attribute something that's actually an instance attribute - always use . to access class attributes, especially when you modify them HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From lu_gio at hotmail.com Wed Sep 4 18:16:57 2002 From: lu_gio at hotmail.com (Max) Date: Wed, 04 Sep 2002 22:16:57 GMT Subject: Database BSD on Mac? References: <3144be3c280c062e5e71a98ab191f664.98737@mygate.mailgate.org> <_7vd9.57894$ub2.928923@news1.tin.it> Message-ID: > > I read shelve can be used for small amount of data... will it work with 5mb? > > Certainly. And probably for _lots_ of more data, if your problem fits > an on-disk hashtable like shelve. Thanks, I'll try it. I was reading on my book it's possible to create encrypted modules, but don't explain much how. My idea is to create a exe file in C joust to execute the python encrypted modules stored with shelve. Is it possible? Can you point me to a tutorial/example code? From shalehperry at attbi.com Wed Sep 18 16:47:39 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 18 Sep 2002 13:47:39 -0700 Subject: linux python ideas In-Reply-To: <3D88E578.6010001@diespammerdieuselesspython.com> References: <3D88E578.6010001@diespammerdieuselesspython.com> Message-ID: <200209181347.39562.shalehperry@attbi.com> On Wednesday 18 September 2002 13:38, Rob Andrews wrote: > I'll be giving a presentation on Python to my local LUG > (http://lugoj.org) in a few weeks, and would like to point out at least > a few things that would be of particular interest to linux users. > > The idea is not "how to program in Python", which would take more than > one quick presentation, but a one-off demonstration of ways in which > Python is particularly useful for such a group. > > Any suggestions would be appreciated, since my notes are pretty generic > so far. > > regards, > Rob Andrews obvious ideas are things like zope and mailman as well as cheetah. From jubafre at brturbo.com Mon Sep 16 15:45:11 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Mon, 16 Sep 2002 16:45:11 -0300 (GMT-03:00) Subject: Alex Martelli -> search re and put in a list?? Message-ID: <1138212326.1032205511801.JavaMail.nobody@webmail1> mem=['7','8', '9'] labels=['D1','D2','D3'] S=['20 D1', '30 D2', '10 D3', 'F0', ' 3', ' 2', ' 0'] i want final=['20 7', '30 8', '10 9', 'F0', ' 3', ' 2', ' 0'] #++++++++++++++++++++++++++++++++++++++++++++++ repdict = dict(zip(labels, mem)) big_re = re.compile('|'.join(labels)) def replacer(mo, repdict=repdict): return repdict[mo.group()] final = [ big_re.sub(x, replacer)for x in S ] print final #++++++++++++++++++++++++++++++++++++++++++++++ Traceback (most recent call last): File "", line 1, in ? File "C:\Documents and Settings\jubafre\Desktop\teste.py", line 27, in ? final = [ big_re.sub(x, replacer)for x in S ] TypeError: expected string or buffer what happened???? Juliano Freitas www.gebrasil.hpg.com.br From martin at v.loewis.de Sun Sep 29 17:18:32 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 29 Sep 2002 23:18:32 +0200 Subject: Python, unicode, Windows32 and NTFS... References: Message-ID: "Werner Merkl" writes: > Python -- at least since version 1.6 -- is supposed to understand > and handle UNICODE. But my experience is, it doesn't support > UNICODE for NTFS file names. That's basically correct. Since Python 2.1, you can use non-ASCII characters in a Unicode file name as long as they are included in the "ANSI code page" (aka "mbcs encoding"). If you want to access arbitrary Unicode file names (within the limitations of the file system), you need the facility described in http://www.python.org/peps/pep-0277.html which is implemented in http://python.org/sf/594001 Regards, Martin From op73418 at mail.telepac.pt Wed Sep 4 13:53:46 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 04 Sep 2002 18:53:46 +0100 Subject: Why read-only nested scopes? References: Message-ID: On 04 Sep 2002 18:47:34 +0200, loewis at informatik.hu-berlin.de (Martin v. L?wis) wrote: >Gon?alo Rodrigues writes: > >> So why hasn't this been extended when nested scopes were introduced, >> e.g. by reusing the global directive or some other one? > >I think the main reason is that nobody could propose an acceptable >syntax. Reusing the global directive does not work. Can you explain why it does not work? > >Regards, >Martin All the best, Gon?alo Rodrigues From ianb at colorstudy.com Thu Sep 19 13:45:56 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 19 Sep 2002 12:45:56 -0500 Subject: Need advice on choosing the technology for intranet based application In-Reply-To: <3d88fd1e@news.ivm.net> References: <3d88fd1e@news.ivm.net> Message-ID: <1032457557.611.1179.camel@dsl-65-184-205-5.telocity.com> On Wed, 2002-09-18 at 17:30, Nenad Propadovic wrote: > Hello pythonistas, > I'm about to write an application related to injury prevention in big > industrial companies. It's supposed to be intranet-based (because the admins > are reluctant to install it on x (where x>>1) clients). So: the client is a > web-browser. I still don't know whether I will get a server on my own, or > I'll have to fit into an unknown web server environment, both options being > realistic. > By now it seems the logic of the application will be simple. It's going to > be a relational database with several tables, a modest number of users with > write priviledges, some more with read priviledges only. Performance is not > a big issue. > The GUI has a part I consider complex: I have to present some statistics in > form of charts or graphs. I would encourage you to consider the graph-creation process to be separate from the web interface. You can program and debug this outside of a web environment (e.g., just creating graphics files in a directory), and then plug it into whatever environment you want -- CGI, Webware, Skunkweb, etc. Skunkweb isn't Windows-compatible, however, which may be a concern. CGI is slow, but easy to install. Webware should install anywhere, but may take a bit more server setup -- if possible I would recommend using Apache, but it doesn't rule out IIS. There's a bunch of other frameworks -- Quixote, Albatross, jonpy... I can't remember them all, but they are all actually fairly similar in scope. I would *not* recommend Zope, which is a content management application and framework, not a good web development framework. CGI will be a little harder to program -- be sure to use cgitb if you go that route -- but the application you describe sounds fairly straight-forward. For the graphics, you may want Reportlab for nice reports, or another graphic library if you want to inline the graphs in HTML pages. I don't believe PIL does what you want -- there are wrappers for gnuplot, and there's a *ton* of other graphing packages (I think the scientists tend to use lots of graphs and lots of Python). Search Parnasus. Ian From martin at v.loewis.de Wed Sep 18 00:47:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Sep 2002 06:47:43 +0200 Subject: How to make a C extension module backwards compatible? References: Message-ID: Andrew McNamara writes: > Is there any community wisdom on how to make a C extension module that > implements a new-style class (type?) backwards compatible (albeit, > at the cost of some functionality)? > > Put another way, how *should* I make a class implemented in C behave > like a new-style class when installed with python 2.2 and above, and > like an old style class when installed with older pythons? What properties of a new-style class are you interested in? If you implement a plain type, it will work on all Python versions, no need to change anything for Python 2.2. Regards, Martin From peter at engcorp.com Tue Sep 3 23:58:39 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 03 Sep 2002 23:58:39 -0400 Subject: default tuple unpacking? References: <3d758180$1@news.sentex.net> Message-ID: <3d7584d2$1@news.sentex.net> Peter Hansen wrote: > Huaiyu Zhu wrote: > >> It is often very convenient to have default arguments such as >> >> def func(a, b, *c): ... >> >> Is there a way to use this in statements too? Examples: >> >> a, (b, *c), *d = e Hmm... I think there might be an inconsistency or an unexpected result in this. What if e already contains a tuple? e = (1, 2, 3) *a = e # a is ((1, 2, 3), ) That seems sensible, and it's just what happens if you pass "e" in to a function defined as "def func(*a)". Now what about this: a, *b = e # a is 1, b is (2, 3) That's one possible result, and presumably the one you want with this syntax, but it's not what you'd get with the function syntax: def func(a, *b): print a print b func(e) Here of course you get (1, 2, 3) in "a" and () in b. To get the same as the proposed syntax above, you can't pass in a tuple, but have to pass the parameters separately: func(1, 2, 3) # now a is 1, b is (2, 3) The problem is that in function calling, you can pass in a single tuple, which is one argument, or you can pass the elements separately as multiple arguments, which is when the special * syntax kicks in. When doing assignment with tuples you don't have the same two options: a, *b = 1, 2, 3 is the same as a, *b = (1, 2, 3) So maybe this won't fly. Comments? -Peter From jan.verstrepen at pandora.be Thu Sep 5 17:06:08 2002 From: jan.verstrepen at pandora.be (jan verstrepen) Date: 5 Sep 2002 14:06:08 -0700 Subject: deeply embedded python sources Message-ID: <5f0846a1.0209051306.2ea5a986@posting.google.com> Hi, It seems that the link to the "deeply embedded python" site is dead. Is it possible that someone has already downloaded those sources before the link died. I have already shrinked down a 2.0 version (so not pippy) by leaving out floating, long, complex, parser/compiler, docs but now I'm very interested in the modifications the deeply embedded project made to the sources itself. Or has anyone maybe one or two tips... thanks Jan From wlfraed at ix.netcom.com Mon Sep 23 20:46:08 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 23 Sep 2002 17:46:08 -0700 Subject: e vs exp()? / financial applications References: Message-ID: Andrew Thompson fed this fish to the penguins on Monday 23 September 2002 10:15 am: > > 1+w+w+w+w > > and > > w+w+w+w+1 > > which are both *different* according to the == operator, but for the > purposes of numerical accuracy are identical. > > This behaviour is quite mild, but it shows the point that rounding > errors can easily creep in, and using == to test for equality is not > always sensible. > Don't they teach anything about floating point in college anymore? I'm pretty sure it came up by my second year "advanced FORTRAN" class that one should not rely upon testing for equality between any two floating point values, but instead should test for a difference less than some predetermined epsilon... abs(f1 - f2) < epsilon -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From debl2nononospmmmy at bellatlantic.net Sat Sep 21 19:36:34 2002 From: debl2nononospmmmy at bellatlantic.net (David Lees) Date: Sat, 21 Sep 2002 23:36:34 GMT Subject: Math optimization References: <6T5j9.145247$pX1.5195840@news2.tin.it> Message-ID: <3D8D02A0.FF572334@bellatlantic.net> This depends on your hardware, OS and probably Python version. Further you need to specify the data type. Integer, floating point or infinite precision integers. It is quite easy to run benchmarks, which you should do yourself. David Lees Zed wrote: > > Hi! > What's faster in python? Divide or multiply? > (a= b*c is faster than a=b/c)? > > Math expressions with constants are calcolated during .pyc creation or real > time? > (a=b*5 is faster than a=b*5*2/2 )? > > Thanks From marklists at mceahern.com Fri Sep 13 11:35:26 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 13 Sep 2002 10:35:26 -0500 Subject: Restricting methods in derived classes In-Reply-To: Message-ID: Huaiyu, The problem with my previously posted solution is that I was trying to rewrite the class' methods at class __init__ time when I needed to be doing that at __new__. Here's a working model. As usual, the names I pick are probably plain goofy. I'd be interested to know whehther this is what you were looking for. Cheers, // mark #!/usr/bin/env python import inspect import unittest def make_unwanted(cls, method_name): def unwanted(self, *args, **kwargs): msg = "'%s' object has no attribute '%s'" % (cls.__name__, method_name) raise AttributeError(msg) return unwanted def is_unwanted(member, wanted_methods): return not member[0].startswith('__') and member[1] not in wanted_methods class Restricted(type): def __new__(cls, classname, bases, classdict): wanted_method_key = 'wanted_methods' # Don't do anything if we don't find the list of wanted methods. if wanted_method_key not in classdict: return type.__new__(cls, classname, bases, classdict) # Hide any method from bases not explicitly listed in wanted_methods. wanted_methods = classdict[wanted_method_key] for base in bases: for method in inspect.getmembers(base, inspect.ismethoddescriptor): if is_unwanted(method, wanted_methods): classdict[method[0]] = make_unwanted(cls, method[0]) return type.__new__(cls, classname, bases, classdict) class RestrictedDict(dict): __metaclass__ = Restricted wanted_methods = [dict.update] class tests(unittest.TestCase): def test_update(self): """Wanted methods should be accessible.""" d = RestrictedDict() d['a'] = 1 expected = {'a': 1} self.assertEquals(expected, d) d.update({'a': 2, 'b': 3}) expected = {'a': 2, 'b': 3} self.assertEquals(expected, d) def test_error(self): """Unwanted methods should raise AttributeError.""" d = RestrictedDict() d['a'] = 1 self.assertRaises(AttributeError, d.copy) def test_using_base(self): """We should still be able to access base methods if we really want to. """ d = RestrictedDict() d['a'] = 1 hidden_method_name = 'copy' for b in d.__class__.__bases__: if hasattr(b, hidden_method_name): copy_method = getattr(b, hidden_method_name) break d2 = copy_method(d) self.assertEquals(d2, d) if __name__ == "__main__": unittest.main() From writeson at earthlink.net Mon Sep 2 13:32:51 2002 From: writeson at earthlink.net (Doug Farrell) Date: 2 Sep 2002 10:32:51 -0700 Subject: RedHat 7.3 and Python2.2.1 Message-ID: <88bc63c6.0209020932.54723791@posting.google.com> Hi, I'm trying to install the latest version of Python (python2-2.2.1-1.i386.rpm) from the www.python.org download page, and I'm having problems. When I run rpm -i python2-2.2.1-1.i386.rpm I get all kinds of conflict messages like this: file /usr/bin/pydoc2 from install of python2-2.2.1-1 conflicts with file from package python2-2.2-16 probably hundreds of them in fact. Can anyone tell me what is going on here, as the www.python.org site says the RPM I'm using is for RH7.3, which is what I'm using. If you can tell me what I'm doing wrong and how to address this, that would be great too! My ultimate goal is to also install wxPython for the python2.2.1 installation, so if anyone has some 'heads up' on that, I'd appreciate it. Thanks in advance, Doug From syver-en+usenet at online.no Sun Sep 8 11:52:09 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Sun, 08 Sep 2002 15:52:09 GMT Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> Message-ID: steve at ferg.org (Stephen Ferg) writes: > "Joseph A. Knapka" wrote in message > news:<3D798461.B3FE0E06 at earthlink.net>... > > Also, you should be aware of the "command" option > > I know about it, but I think that for beginners, it is very > confusing. I think you are right here Stephen. Only learning the command option is a bit like using a wizard to generate code, you can get quite far with it but you haven't really understood what you are doing. bind is much more general and let's the student know what he/she is doing. -- Vennlig hilsen Syver Enstad From danielnuriyev at yahoo.com Tue Sep 10 19:32:11 2002 From: danielnuriyev at yahoo.com (Daniel Nuriyev) Date: 10 Sep 2002 16:32:11 -0700 Subject: Python GUI References: <3d8d3c0.0208262339.e7bc02c@posting.google.com> <8_8b9.3412$pw.4534678@ruti.visi.com> Message-ID: <3d8d3c0.0209101532.6fe25365@posting.google.com> Gentlemen, some of you have misunderstood what I wrote against using the native widgets. What I meant was not to use instead of the native widgets the least common denominator for all platforms but to use one basic graphical object of no matter which origin by means of which to simulate look&feels you like. This is what I meant when I compared this method with Java Swing. Surely it envolves a lot of work for those who will develop such packages. But in my opinion it is better than to call directly the native widgets. I apologize for being lazy to go into the explanation of why. But if you're interested in the comparoson of the two approaches, you can have a look at the advantages of Java Swing vs Java AWT. Another point I would like to make clear is that what I meant by my message was the general issue of a general idea of a general GUI package for Python. But of course each one of us has a concrete package we like and it is absolutely not compulsory to use something generic. I, for instance, use Tk for quickies. I don't like it but it's always there. When I need something nice I look at the needs of a concrete project and make choices not necessarily based on my personal taste. From steven_shaw at adc.com Mon Sep 9 23:23:55 2002 From: steven_shaw at adc.com (Steven Shaw) Date: 9 Sep 2002 20:23:55 -0700 Subject: dynamism Message-ID: <66715c02.0209091923.265fe77e@posting.google.com> I've been away from Python for awhile and I'm wondering whether Python got less "dynamic" while I was away. I thought you could just extend an object's attributes at run-time like this: >>> p = object() >>> p.x = 1 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute 'x' I thought that you could access dictionary values with object syntax: >>> x = { 'a': 1, 'b':2 } >>> x {'a': 1, 'b': 2} >>> x.a Traceback (most recent call last): File "", line 1, in ? AttributeError: 'dict' object has no attribute 'a' Maybe you could never do this as shown but I'm sure there were ways of getting this effect. Anyone care to remind me? Cheers, Steve. From shalehperry at attbi.com Thu Sep 12 15:05:49 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 12 Sep 2002 12:05:49 -0700 Subject: [newbie] Buying an introductory/reference text In-Reply-To: References: Message-ID: <200209121205.49267.shalehperry@attbi.com> On Thursday 12 September 2002 11:59, Brad Fonseca wrote: > Greetings! > > I'm looking for a few opinions on the above subject. I'm a computer > science student who has had some introductory lectures on Python and I've > done some very basic mucking around with. I'm looking for a clear > reference and/or introductory text. Any suggestions would be nice. I have > looked at http://www.python.org/cgi-bin/moinmoin/IntroductoryBooks but > there appears to be a number of good books to choose from there. > > Regards, I believe that "Python: Essential Reference" is about all you need if you have programmed in at least one other language. Top notch book. From erikprice at mac.com Wed Sep 4 10:17:26 2002 From: erikprice at mac.com (Erik Price) Date: Wed, 4 Sep 2002 10:17:26 -0400 Subject: Why Python? In-Reply-To: Message-ID: <09CB9911-C011-11D6-BB50-00039351FE6A@mac.com> On Wednesday, September 4, 2002, at 09:50 AM, Konrad Wojas wrote: > I've been doing web development in PHP since 1998 and have written a > content > management system with a quite complex shopping cart system and a > backoffice system to handle all sales. It's over 10000 lines of PHP > code, > excluding the html code. I learned to program from PHP, and wrote an application that was comparable (somewhere over 10,000 lines of code). It didn't deal with e-commerce but was essentially an extensive database front-end, and included shopping cart-like "features". > I've really had it with PHP, it's unmaintainable, ugly and slow. > Errors like > 'parse error on line 487' are not fun to work with. I really like > python. > The systax is a lot clearer, exceptions are great and I really love > those > stacktraces if an exception is not handles. Object oriented > programming in > PHP is a joke, it really sucks. And PHP is buggy. I've encountered > numerous > bugs, especially in the extension modules. XSLT in PHP? Forget it, the > module will crash in 50% of the cases. And compiling PHP yourself with > a > lot of extension modules can be a real nightmare. And above all: > python is > a generic language, PHP is only useable for web development and small > maintainance scripts. It doesn't have bindings for anything beyond web > development. I think that PHP is prettier than Perl but not nearly as pretty as Python. Its support for objects is adequate for some purposes, but for a fully object-oriented application it might not be quite up to snuff. If your code is mostly procedural and you use a few objects to make your life easier, though, you should be able to manage. The error messages from PHP were always fine for me, but there's no elegant way to handle them like in Python where you can catch exceptions, etc. PHP does have a few kinks, but the bugs are esoteric. It is a pretty well-developed language IMO. One of the biggest differences between PHP and Python is that in PHP most of the functions are built into the global namespace. I know that some people in Python have a lot of problems with that, but PHP is not a general-purpose language and so doesn't use modules like Python and Perl -- having these functions available is actually a blessing. But in a language like Python or Java I prefer the modular approach. PHP also has extremely good interconnectivity with the MySQL database, so many people who use MySQL see PHP as the web-language of choice. PHP/MySQL tutorials and books abound, which I think is interesting because there are so few jobs (in New England, US at least) that actually want PHP programmers. > I'm still maintaining the PHP code I have written, but I use python > for all > new projects. Don't start big projects in PHP, you'll regret it ;-) I would go back to PHP for some simple dynamic web page scripts, but not much more. I agree with the above -- if you're going to write full-blown applications, you will probably like the OO facilities of Python (or Java) better. Erik -- Erik Price email: erikprice at mac.com jabber: erikprice at jabber.org From jtk at yahoo.com Fri Sep 6 23:21:27 2002 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Fri, 6 Sep 2002 23:21:27 -0400 Subject: Sequence or Identity in gadfly Message-ID: I don't expect that it does (it would make more sense to do it in your python code), but is there a Sequence type in gadfly so that I can make an autonumber for ID columns similar this postgres code?: CREATE SEQUENCE id start 1000 increment 1 maxvalue 100000 SELECT nextval ('id'); Or some other construct for creating an identity value? From gumuz at looze.net Thu Sep 5 09:19:41 2002 From: gumuz at looze.net (Gumuz) Date: Thu, 5 Sep 2002 15:19:41 +0200 Subject: encryption (passwords) References: <3d75d115$0$221$4d4ebb8e@news.nl.uu.net> <7xd6ru2gfi.fsf@ruckus.brouhaha.com> <3d75f0f0$0$230$4d4ebb8e@news.nl.uu.net> <7xsn0pzcol.fsf@ruckus.brouhaha.com> Message-ID: <3d775896$0$231$4d4ebb8e@news.nl.uu.net> actually, i found a very good example for this at: http://www.nyx.net/~awestrop/crypt/dh2.htm it's a java applet only thing i'm still puzzling with is how to apply this properly "Paul Rubin" wrote in message news:7xsn0pzcol.fsf at ruckus.brouhaha.com... > "Gumuz" writes: > > although this is just a play-learn-project and security is not really an > > issue, i'd like to include encryption in it as well to get experience in > > this, too. > > If you want to learn programming cryptography, the book you want is > "Applied Cryptography" by Bruce Schneier. You might like to implement > everything yourself rather than using a library. > > > Actually, I am trying to create a sort of simple instant messenger > > server+client. > > I think this should use Diffie-Hellman key exchange to choose the > decryption keys. DH is a way for two people to agree on a key based > on random parameters they each choose. The traditional version goes: > > Alice and Bob agree beforehand on public parameters g and P, > where P is a big prime number (like 300 digits) with certain > properties and g is a generator of Z//p. If you don't understand > that, don't worry too much--there are standard values of g and P > that you can use. > > To start talking to each other, Alice chooses a secret random number x, > and Bob chooses a secret random number y. They do not reveal these > numbers to anyone. Alice instead computes the number X = g**x mod P > and sends X to Bob. Bob computes Y = g**y mod P and sends Y to Alice. > Computing these modular exponentials is trivial in python because > of Python's built-in long integers and its 3-argument pow function. > You can just say Y = pow(g,y,P). > > Since Alice receives Y from Bob and knows x already, she can compute > K = Y**x mod P. Notice Y**x mod P == (g**y)**x mod P = g**(yx) mod P. > Bob likewise can compute K = X**y mod P = (g**x)**y mod P = g**(xy) mod P. > Since multiplication is commutative, xy==yx so both have found the same K. > The coolness here is the computation required knowing at least one of > the secrets, x or y. An eavesdropper knowing neither secret doesn't > have any easy way to find K. > > At the end of the conversation, Alice and Bob should both erase their > secret values x, y, and K from computer memory. That means the > conversation can never be recovered by a third party, even by forcing > Alice and Bob to reveal their passwords, turn over their computers, etc. > The keys are gone forever, like burning a document. > > Note you will also have to protect against "man in the middle" > attacks, and deal with some other subtleties, to make DH secure--the > description above is just to sketch the process. See Applied > Cryptography for more info. From imbosol at vt.edu Mon Sep 2 19:34:29 2002 From: imbosol at vt.edu (Carl Banks) Date: Mon, 2 Sep 2002 19:34:29 -0400 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <1030962064.628232@ampungk.ozonline.com.au> <1031008966.343893@ampungk.ozonline.com.au> Message-ID: John La Rooy wrote: > Carl Banks wrote: > >>>"anything,anything,anything,same_as_3rd,same_as_2nd,same_as_1st" >>>or would you like to suggest something else? >> >> >> How about: >> >> pattern = Group(Any()) + Group(Any()) + Group(Any()) \ >> + GroupRef(3) + GroupRef(2) + GroupRef(1) >> > Err symantically that's exactly the same as the re and my suggestion > only the syntax is different. It's still nothing like saying > > pattern = "6 character palindrome" Oh. Well, methinks you don't give humans enough credit. I'm a human, and I can read the verbose regexp. Of course, humans can read regular expressions, too. Maybe I don't give humans enough credit, either. :-) The point is, I was arguing for less-cryptic, more-verbose regular expressions as a way to make complicated patterns more transparent. I certainly wasn't arguing for "6 character palindrome". Sorry-for-the-confusion-ly y'rs -- CARL BANKS http://www.aerojockey.com From grayshade at libero.it Wed Sep 18 11:37:18 2002 From: grayshade at libero.it (Domenico) Date: 18 Sep 2002 08:37:18 -0700 Subject: Python doesn't suck! Message-ID: http://www.theperlreview.com/at_a_glance.html According to the most accurate algorithm, Python is the second less-sucking language. From theller at python.net Mon Sep 9 12:12:30 2002 From: theller at python.net (Thomas Heller) Date: Mon, 9 Sep 2002 18:12:30 +0200 Subject: win32com.client.gencache and py2exe References: Message-ID: "Syver Enstad" wrote in message news:uit1ftba1.fsf at online.no... > > When using py2exe to make package a python program that uses gencache > to generate wrapper files from COM type libraries, the resulting > installation fails because the win32com system is unable to find the > generated files. Is there any workaround to this problem?z > It's already fixed in CVS. It should be sufficient if you replace the existing build_exe.py by the new one which you can grab from the CVS repository: http://cvs.sourceforge.net/cgi-in/viewcvs.cgi/py2exe/py2exe/py2exe/build_exe.py (the server seems down at the moment). There's a new command line flag, which you must use to specify the progids you use, like "--progids Excel.Application". HTH, Thomas From Padraig at Linux.ie Wed Sep 11 07:35:11 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Wed, 11 Sep 2002 11:35:11 GMT Subject: regular expression for space seperated quoted string References: Message-ID: Padraig Brady wrote: > Hi, I'm trying to split a string that is seperated > by spaces and also contains double quoted words which > can contain spaces: > > For e.g. using: re.split('[ ]*"?([^"]*)"?[ ]*', s1) > on this string: s1='1 "2" "thre e"' > gives: ['', '1 ', '', '2', '', 'thre e', ''] > > Problem with this is the '' entries, but this isn't too bad. > > However using the above re with: s2='1 2 "th ree"' > I get: ['', '1 2 ', '', 'th ree', ''] > > any ideas? Well this one does better: re.split('[ ]+|"([^"]*)"', string) It does leave '' and None entries in the list, but I can remove these easily. I presume there is something more elegant. P?draig. From eric.brunel at pragmadev.com Mon Sep 23 04:21:07 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 23 Sep 2002 10:21:07 +0200 Subject: Tk Getting a directory name References: Message-ID: Ken Payne wrote: > HI everyone - > > I'm writing a Tk interface to an app and in it I want the user to choose a > directory. There's an easy way to ask the user to pick a file - > > fileWanted=askopenfilename() > > but is there a similar way to ask for a directory? > > - Ken http://groups.google.com/groups?hl=en&lr=&ie=ISO-8859-1&q=tkinter+select+directory&meta=group%3Dcomp.lang.python.* -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From peter at engcorp.com Thu Sep 12 00:27:43 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 12 Sep 2002 00:27:43 -0400 Subject: I must be an idiot, please pity me! References: Message-ID: <3d8017ac@news.sentex.net> newbie wrote: > On Wed, 11 Sep 2002 18:10:42 +0100, Mark McEahern wrote: > >>[newbie] >> >>>But it doesn't seem to work like that. >> >>What are the symptoms of failure? > > Perhaps I wasn't clear, but I don't believe I mentioned anything not > functioning properly. I believe Mark read your above comment the same way I did, which was "it doesn't seem to work [when configured] like that", as opposed to what you appear to have meant which would be "it doesn't seem to work in that manner". A simple misunderstanding perhaps. :) -Peter From robin.siebler at corp.palm.com Mon Sep 16 16:08:44 2002 From: robin.siebler at corp.palm.com (Robin Siebler) Date: 16 Sep 2002 13:08:44 -0700 Subject: Difflib question Message-ID: <886c5e4b.0209161208.25012958@posting.google.com> Is there a way to get difflib to output *only* the lines that are different (instead of all of the lines)? From sholden at holdenweb.com Thu Sep 5 14:04:21 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 5 Sep 2002 14:04:21 -0400 Subject: Maybe it's a mod_python issue I'm hitting? References: <3D6E6BDA.7337426C@bullfrog-tech.com> <3D6E7022.3DE649D4@bullfrog-tech.com> <3D6E82E3.866CBA49@bullfrog-tech.com> Message-ID: "Manus Hand" wrote in message news:3D6E82E3.866CBA49 at bullfrog-tech.com... > Another follow-up.... > > It seems that all my code of the form: > vars(self).update(someDict) > still DOES work fine under 2.2. (Yay! Whew!) > It's not guaranteed to work in later versions, though, I suspect. > The one thing that STOPPED working reliably is this: > > locals()[varName] = someValue > Don't do that (see below). > My initial thought was that PEP 227 had made locals() read-only, hence my post > at the start of this thread. However, I soon realized that this line worked > fine > under 2.2 while it sat at global scope. The line started failing when I put it > > into a function (specifically, a handler() function, as part of a port to a > mod_python installation). > Erm, you should NOT treat the locals dictionary as modifiable, whether running under mod_python or not. The locals() function returns a dictionary (mapping, anyway), but for a long time now the documentation has said you should not (necessarily) expect changes to this mapping object to result in changes to the local name space. [other confusions] >From the library manual (section 2.1, Built-In Functions): """ locals() Return a dictionary representing the current local symbol table. Warning: The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter. """ regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From kseehof at neuralintegrator.com Wed Sep 4 15:40:47 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Wed, 4 Sep 2002 12:40:47 -0700 Subject: Could Python supplant Java? In-Reply-To: <3D64C3C5.7000502@softhome.net> Message-ID: Nick Ruisi wrote: > .net compiled code can run on linux with the mono CLR > (http://www.go-mono.com). One can use the mono tool kit to write / > compile .Net code on a linux box, without ever touching a microsoft > product. The compiler and SDK for C# and VB.Net is a free (albeit > large) download. Although I don't like VB.Net as a language, C# is fine. > It's just like java. C# and .Net are transparent ploys by Microsoft. This isn't paranoia, or fashionable "Microsoft bashing", it's just plain experience. The only possible motivation for Microsoft to market a product that increases compatibility across platforms, languages and applications is to be in a position to severely damage that compatibility at some point in the future. Anyone who has been in the computer industry for any length of time should see that this is obvious. Open Source, open architecture, and open anything, are extremely harmful to Microsoft's well being, and they know it. They aren't evil; they are just trying to survive. I expect .Net to provide what it promises in the short run, at least to some degree, in order to gain some degree of credibility. Hence, it works fine on Linux for now. Once people are hooked, you can expect microsoftisms to creep in for no reason other than to lock out competition. If this isn't obvious to you, please read Microsoft's own internal documentation as leaked in the "Halloween Documents". And don't waste space on this thread arguing with me until you have at least read part 1. Especially be sure to read about "decommoditizing protocols". "OSS [open source software] projects have been able to gain a foothold in many server application because of the wide utility of highly commoditized, simple protocols. By extending these protocols and developing new protocols, we can deny OSS projects entry into the market." - Microsoft internal memo http://www.opensource.org/halloween/ - Ken Seehof > Rex Ballard wrote: > > > netvegetable wrote: > > > > > >>Not offering any personal opinion on this conjecture, but a lot of > >>people are saying that java has failed to become a widely accepted > >>cross platform language for applications. > >> > > > > Java is still quite popular, and has established a pretty > > substantial market share. Microsoft is fighting Java and trying to > > Undermine Java 2 by bundling an older version of Microsoft's > > insecure JVM, but getting JRE is very easy, and even JDK is pretty > > easy to get if you want it. And since JDK 1.3 have some execellent > > IDEs available, on both Linux and Windows, it's pretty easy to > > implement applications that work on Both Linux and Windows. > > > > > >>These leaves the world defenseless against the Microsoft Borg. > >> > > > > PLEASE!!! - Microsoft has no really good general purpose scripting > > languages, and no low-cost development languages. PERL, PYTHON, > > JAVA, and TCL can all be downloaded for free. Microsoft obviously > > doesn't pay $4 billion/year to promote these Open Source based > > languages which can create products and projects that can run on > > both Linux and Windows. > > > > Of COURSE Microsoft is going to spend their $Billions promoting C# > > and Visual Basic, which run Exclusively on Windows and do not > > support comprehensive implementations on Linux. > > > > Of course, if you want some heavy-duty portability, you have > > cygwin, which give you the ability to run Linux programs on > > Windows, including Windows NT, 2000, and XP. Cygwin isn't as > > secure, stable, and fast as Linux (after all you are ultimately > > dependent on Windows infrastructure), but it's a nice way to make > > the transition. > > > > > >>But could Python do the trick? The python interpreter is smaller > >>than the JRE, and it's certainly a nicely structured language, > >>with nearly all the coding features of Java. > >> > > > > Unfortunately, Python, PERL, TCL/TK, Ruby, and the other fine > > languages all have to be loaded AFTER the machines are shipped. > > Obviously, it would be nice if OEMs could install PERL, Java 2, > > Python, and others as part of their OEM installation, when it can > > be put on the master disk. It would cost nothing, or extremely > > little, and would provide new capabilities not currently available > > to Windows. It would also make hundreds of applications available > > as well. > > > > Unfortunately, Microsoft has insisted on complete control of the > > preinstalled suite and is doing everything they possibly can to > > maintain that control despite the unanimous ruling of the Appeals > > court full panel that such exclusion of competitors is explicitly > > illegal. > > > > Sun is likely to be the strongest candidate to be prepared to fight > > this or have Microsoft cited for contempt. Sun could offer Java > > JRE and/or JDK, Star Office, and other applications which could be > > installed by OEMs for prices that are very competitive with > > Microsoft's office, JDK, and IE/VBScript. > > > > Red Hat could also press for the inclusion of Cygwin, in this case > > possibly even at no cost to OEMs. Corporate customers could also > > begin using Cygwin - including Python, Perl, and TCL/TK. > > > > These are "first steps" - steps that would create an application > > base that could lead to a marketplace in which both Windows and > > Linux compete in an open and equally accessible market. > > > > For this reason, Microsoft will do everything it can to fight this > > technology, since it cannot be controlled. Microsoft has even > > tried to force Corporations to agree to NOT use Open Source > > technology such as Python on their Windows desktops. The DOJ has > > ignored this, the Courts have ignored this, and Microsoft has tried > > to divert attention by releasing a support pack that allows users > > to choose which web browser they want to use. > > > > As long as Microsoft controls access to the OEM distribution > > channel, and has the ability to control what OS, Applications, and > > systems can be installed on PCs, they will do everything in their > > power to "Lock out" any technology which can be supported by both > > Linux and Windows. > > > > > >>-- > >>netvegetable at excite.com > >> > > > > > > -----= Posted via Newsfeeds.Com, Uncensored Usenet News =----- > http://www.newsfeeds.com - The #1 Newsgroup Service in the World! > -----== Over 80,000 Newsgroups - 16 Different Servers! =----- > -- > http://mail.python.org/mailman/listinfo/python-list > From kmp at NO2SPAMatrium.fsnet.co.uk Mon Sep 23 13:42:22 2002 From: kmp at NO2SPAMatrium.fsnet.co.uk (Ken Payne) Date: Mon, 23 Sep 2002 18:42:22 +0100 Subject: Tk Getting a directory name References: Message-ID: Eric - Thanks. Just what I needed. Best wishes - Ken Eric Brunel wrote: > Ken Payne wrote: > >> HI everyone - >> >> I'm writing a Tk interface to an app and in it I want the user to choose >> a directory. There's an easy way to ask the user to pick a file - >> >> fileWanted=askopenfilename() >> >> but is there a similar way to ask for a directory? >> >> - Ken > > http://groups.google.com/groups?hl=en&lr=&ie=ISO-8859-1&q=tkinter+select+directory&meta=group%3Dcomp.lang.python.* From sholden at holdenweb.com Fri Sep 27 17:16:01 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 27 Sep 2002 17:16:01 -0400 Subject: Local Python Server Installation References: <3d8b47c6.277669@news.jaring.my> <3d8c993c.2190426@news.jaring.my> <3d8d4009.375344@news.jaring.my> <3d947c26.2656654@news.jaring.my> Message-ID: "Kenneth Gomez" wrote ... > Steve, > > I stumbled onto this problem while going through the first exmaple in > the book Python:How to Progra, by Deitel, Deitel, Liperi and > Wiedermann. > > My little code sniipet, copied exactly from the book except for the > path to my python exe is : > > ________________________________________________ > > #!C:\prog\Python22\python.exe > > import time > > def printheader(title): > print """Content-type: text/html > > > "-//W3C//DTD XHTML 1.0 Strict//EN" > "DTD/xhtml1-strict.dtd"> > > %s > > """ % title > > printheader("Current Date & Time") > print time.ctime(time.time()) > print "" > ___________________________________________________ > This looks OK given the mailer mangling that's (presumably) lost some tabs from the code. > > I get the following error in IE6 : > > The XML page cannot be displayed > Cannot view XML input using style sheet. Please correct the error and > then click the Refresh button, or try again later. > Interesting that it even recognises XML given the Content-Type header and the fact that the program doesn't seem to be running. > > -------------------------------------------------------------------------- ------ > > Invalid at the top level of the document. Error processing resource > 'http://localhost/ken.py'. Line 1, Position 1 > > #!C:\prog\Python22\python.exe > ^ > So, basically, IE6 is also seeing a listing of the script. This isn't surprising: the server behavior is unlikely to change with a change of client. > > and when using Mozilla 1.0, all I get is the listing of the script. > > Bummer. > > Any advise? > Don't know. I presume you have already made http://httpd.apache.org/docs-2.0/platform/windows.html your bible? It does tell you almost all of what you need to know. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From ken at hotmail.com Fri Sep 20 23:07:28 2002 From: ken at hotmail.com (Ken) Date: Sat, 21 Sep 2002 13:07:28 +1000 Subject: Python about file I/O Message-ID: Hi, I have 2 questions on IO, not necessary related to one another: 1.) How do you list the filenames within a given directory so user can choose which file to open? 2.) How do you ensure the program doesn't crash if I specify a filename to open but the file doesn't exist? (I.E. how to check if file exist before opening the file?) Thanks From pyth at devel.trillke.net Sun Sep 1 18:56:27 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 2 Sep 2002 00:56:27 +0200 Subject: Python IPC options In-Reply-To: <3D727AFA.1FE19151@bio.gla.ac.uk>; from F.L.Burton@bio.gla.ac.uk on Sun, Sep 01, 2002 at 09:39:22PM +0100 References: <1030829572.943495@irys.nyx.net> <3D727AFA.1FE19151@bio.gla.ac.uk> Message-ID: <20020902005627.F3893@prim.han.de> Francis Burton wrote: > Armin Steinhoff wrote: > > SPREAD -> http://www.python.org/other/spread/ > > This seems to be very close to what I am looking for. > Thanks for the pointer! > > > Hope this is enough :) > > More than enough. :-) I'll investigate Spread first, > then maybe delve into some of the others. Check back if you get stuck. It took me some hours to get something meaningful running. One thing i didn't solve (and this might be a design-problem) is to dynamically add/remove a participating host/server. I had to restart *all* servers with updated configuration files to get a new server in. That's a bit 90' regards, holger From martin at v.loewis.de Wed Sep 18 00:44:16 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Sep 2002 06:44:16 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> Message-ID: Greg Ewing writes: > Also, I believe that, even on the supported > architectures, it plays dangerous tricks with > the C stack. I'd prefer to see that fixed > before making it a standard part of the > distribution. They aren't really dangerous, just unconventional. And that cannot be fixed, as it is essential to operation of Stackless. Regards, Martin From pyth at devel.trillke.net Wed Sep 11 19:29:14 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 12 Sep 2002 01:29:14 +0200 Subject: Destructor never called ??? In-Reply-To: <76710511.0209111450.40999dd8@posting.google.com>; from muk_pr@yahoo.com on Wed, Sep 11, 2002 at 03:50:24PM -0700 References: <76710511.0209111450.40999dd8@posting.google.com> Message-ID: <20020912012914.W3893@prim.han.de> I presume that you are using CPython (not jpython). vb wrote: > Hi, > I have the following code my problem is when I call any methods of > TCVector_Object the destructor never executes. > > I mean > > v = module.CreateTCVector() > del v; or maybe you are using JPython :-) > //destructor runs. message shown .OK > > but > in > > v = module.CreateTCVector() > v.Append(123); > del v;//or closing python interpreter At least you are coming from java :-) getting ontopic, what does your 'Append' method do? It's not the usual list.append method, right? > destructor never gets called. Any ideas? You need to provide *example* code, showing unexpected behaviour. Tossing in some information about the python version and the operating system might help, too. Especially when it's about low-level behaviour. regards, holger From StRanGy at dijana.vest.hr Fri Sep 6 12:52:49 2002 From: StRanGy at dijana.vest.hr (Ivica) Date: 6 Sep 2002 16:52:49 GMT Subject: Getting a proccesses ID References: Message-ID: On Fri, 06 Sep 2002 15:05:20 GMT, Micah Mayo wrote: > Hi, > > I'm writing a little tool for SysAdmins on FreeBSD - I'm trying to make > it as portable as possible(as far as the unices go), and have come upon > a problem - one of the things this tool does is restarts various deamons > on the system, in order to do that I have to send a killsignal to the > pid. The problem is getting the process id - right now I've got a hack > using ps, grep, and awk, which I doubt will translate well to other > flavors of *nix because they all seem to have their own method of > delivering info via ps. Can anyone tell me a cross platform way of > grabbing a particular processes ID > > Here's what I'm doing now, by the way: > > pid = os.popen("ps -x | grep sshd | grep -v grep | awk '{ print $1 }'") > pid = pid.atoi() > Maybe this will help you: def GetPids(list, procname): pidlist = [] for i in range(len(list)): if string.find(list[i], procname) != -1: str = list[i].strip() sp = string.find(str, ' ') pid = str[:sp].strip() pidlist.append(pid) mypid = os.getpid() if mypid in pidlist: pidlist.remove(mypid) return pidlist This I use for killing a proccess ny his name and not killing myself if the process is python the list argument is a list os proccesses which i got using ... pidlist = os.popen('ps').read() pidlist = pidlist.split('\n') -- --------------------------------- # RealName: Ivica Munitic # E-Mail: imunitic at vest.hr --------------------------------- From gumuz at looze.net Tue Sep 24 10:42:11 2002 From: gumuz at looze.net (Gumuz) Date: Tue, 24 Sep 2002 16:42:11 +0200 Subject: how to build up a guest book with python ? References: <6FYj9.157588$pX1.5677010@news2.tin.it> Message-ID: <3d90784e$0$231$4d4ebb8e@news.nl.uu.net> i might add that this is an exellent book! "Alex Martelli" wrote in message news:6FYj9.157588$pX1.5677010 at news2.tin.it... > black wrote: > > > I'm learning python for almost 1 month and decide to build up a guest > > book with it, but I really know nothing about web programming, any > > tutorials for me please ? > > Steve Holden's "Python Web Programming" (New Riders) should be > perfect for your needs -- it touches on all the technologies you > need to be acquainted with for the purpose, and gives a good > tutorial grounding in each of them. (I'm biased: Steve is a > friend and I was a tech editor for the book -- but I have some > counter-bias to compensate, as I could be recommending my own > books instead of his, so it probably balances out:-). > > > Alex > From dance_code at hotmail.com Sat Sep 28 20:31:53 2002 From: dance_code at hotmail.com (lee lion) Date: Sun, 29 Sep 2002 00:31:53 +0000 Subject: A simpler singleton pattern? Message-ID: singleton pattern is a way to provide one and only one object of a particular type. There are many ways to implement a singleton pattern, is the below one? class OnlyOne: instance = None def __init__(self, arg): OnlyOne.instance = arg def __getattr__(self, name): return getattr(OnlyOne.instance, name) if __name__ == "__main__": x = OnlyOne("x") print x y = OnlyOne("y") print y print x print `x` print `y` The output is: x y y 'y' 'y' "The best way of living is to earn a little more than you cost and to cost just as you need to." Li Hang _________________________________________________________________ ?????????????? MSN Messenger: http://messenger.microsoft.com/cn/ From davegaramond at icqmail.com Sat Sep 21 11:28:08 2002 From: davegaramond at icqmail.com (David Garamond) Date: Sat, 21 Sep 2002 22:28:08 +0700 Subject: if...else on the same line? Message-ID: <3D8C9008.70805@icqmail.com> i'm sorry for this terrorizingly basic question, but is it possible at all to write an if ... else statement on a single line in python? -- dave From ADATE at kc.rr.com Tue Sep 3 18:37:36 2002 From: ADATE at kc.rr.com (Shashank Date) Date: Tue, 03 Sep 2002 22:37:36 GMT Subject: Threads References: Message-ID: Splendid ! Thanks a lot ... -- Shanko "Aahz" wrote in message news:al0jd5$f5p$1 at panix1.panix.com... > In article , > Shashank Date wrote: > > > >I am trying to write a simple threading app in Python 2.2 (on Windows) which > >will spawn mutiple threads. > >Each thread will go out on the web (various web sites) and fetch certain > >documents. The main thread will wait for all the threads to terminate OR > >some external event (like deletion of a file). If the external event fires > >before termination of child-threads it kills all the spawned threads and > >terminates. > > > >Any ideas how to go about doing this. > > See my web page. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Project Vote Smart: http://www.vote-smart.org/ From cnetzer at mail.arc.nasa.gov Mon Sep 30 18:17:43 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Mon, 30 Sep 2002 15:17:43 -0700 Subject: Why doesn't this work? In-Reply-To: References: Message-ID: <200209302217.PAA07614@mail.arc.nasa.gov> On Saturday 28 September 2002 23:29, Michael Bakkemo wrote: > Why doesn't the rectangle start somewhere in the middle of the canvas > (where one would expect (40,40) to be, instead of all the way over on > the left? Because of the way Tk works. You are setting up a lot of things before entering the mainloop(), and not giving Tk a chance to execute and update it's internal state (not your fault, really). But to fix things, add the line: sc.update() Just before: rect = MovingRect(root, sc, 40,40, 10, 10) (ie. right near the end of the program, but before the mainloop). This let's the canvas get information from the window manager about how big the window that opened actually was, so it can position things like you expect it to. -- Chad Netzer cnetzer at mail.arc.nasa.gov From jdhunter at ace.bsd.uchicago.edu Wed Sep 25 10:53:30 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 25 Sep 2002 09:53:30 -0500 Subject: Removing all occurences of a character from a string. In-Reply-To: ("Sean Ross"'s message of "25 Sep 2002 03:36:01 GMT") References: Message-ID: >From the example you gave, I was wondering if a dictionary might be a more suitable data structure: attr = { "gill-attachment" : ["a", "d", "f", "n"], "gill-spacing" : ["c", "d", "w"], "gill-size" : ["b", "n"] } print attr["gill-size"] John Hunter From aleax at aleax.it Tue Sep 24 08:57:13 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 12:57:13 GMT Subject: callback + __call__ + TypeError: unbound method; on non method References: Message-ID: Volker Apelt wrote: > But I can't remove the .__call__ method from my > Callback class. The method is essential for The problem is not with method __call__, as it gets called with an instance. Rather, it's right here: > class Callback: > """ > """ > _default_Func = call_me # class wide default callback function > > def __init__(self): > """ """ > self._m_func = Callback._default_Func Here, self._m_func is NOT a function -- it's an unbound method, thus it's not callable unless the first argument is an instance of the class (or any subclass thereof). When you fetch from a class an attribute that is a Python coded function object, what you get is an unbound method object. This behavior is intrinsic to Python's OO mechanisms. Remedy: have Callback._default_Func be just about ANY callable except a Python-coded function object:-). In Python 2.2, the built-in staticmethod is made just for the purpose: class Callback: """ """ _default_Func = staticmethod(call_me) # class wide default callback and the rest can stay unchanged (haven't examined it in detail, but this is the surely-buggy spot in your code and explains the traceback that you report). Alex From amk at amk.ca Thu Sep 19 20:08:03 2002 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 20 Sep 2002 00:08:03 -0000 Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> Message-ID: In article <3d88fd1e at news.ivm.net>, Nenad Propadovic wrote: > -I assume the simplest way to present a graph/chart kind of graphic is to > create a jpg/giff/tiff on the server side, and just show it on the client? Yes. PIL, the Python Imaging Library, would be one possibility; so is the gd module. For example, the pricing charts on the pages at http://www.mems-exchange.org/catalog/ are generated from Quixote using gd. PDF likely isn't helpful, because browsers won't display PDF images inlined in a web page, though it's certainly well-suited for multi-page reports that need to be printed. --amk From marklists at mceahern.com Thu Sep 26 20:40:03 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 26 Sep 2002 19:40:03 -0500 Subject: Help! This is driving me insane! In-Reply-To: Message-ID: [kara.klosterman] > I created a very simple class that totals some data > but I am not getting the output from it that I would > expect at all. > Here is the class: > http://www.geocities.com/dbasch/insane.txt > > I would expect to get: > [0, 0] > [0, 0] > [[0, 0]] > > but I am getting: > [0, 0] > [0, 0] > [[1, 1]] > > I dont understand how the 'grouptotals' list is > getting the incremented values prior to the > 'grouptotalcounter' function being called. > furthermore, I can place a 'print grouptotals' right > after the errorlog append and it isnt the incremented > values! Please tell me this isnt a normal thing! I glanced at your code and tried to decipher it. My overall reaction is that the intention behind your code is obscure to me. Note that you don't even really tell us how to run it and how you got your output. I'm guessing you did this: t = Test() x = t.run() print x // m From bwucew at yahoo.com Thu Sep 12 13:12:05 2002 From: bwucew at yahoo.com (Bwuce_Wee) Date: 12 Sep 2002 10:12:05 -0700 Subject: Extending a C++ App Message-ID: <996eade8.0209120912.3a653d7@posting.google.com> There are lots of utilities that allow a person to bind a DLL's classes, variables, etc to use as a python module. I can find incredibly little information though on how to run python INSIDE a C++ EXE, and still have that binding of classes,etc. For instance, I want to make application MyApp.EXE that can load in x number of python scripts that are called inside the app. However, there is a application object model that I want the scripting to be able to interact with (from both C++ code and from the script) If you found my explanation too vague - I apologise Please mention it so I can ellaborate Any help is appreciated - thanks in advance for the replies From max at alcyone.com Sun Sep 8 02:28:08 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 07 Sep 2002 23:28:08 -0700 Subject: ANN: empy 1.4 -- Embed Python in template text as markup Message-ID: <3D7AEDF8.767B27DC@alcyone.com> Summary empy is a system for embedding Python expressions and statements in template text; it takes empy source files, processes them, and produces output. This is accomplished via expansions, which are special signals to the empy system and are set off by a special prefix (by default the at sign, '@'). empy can expand arbitrary Python expressions and statements in this way, as well as a variety of special forms. Textual data not explicitly delimited in this way is sent unaffected to the output, allowing Python to be used in effect as a markup language. Also supported are recording and playback via diversions and dynamic, chainable filters. The system is highly configurable via command line options. Expressions are embedded in text with the '@(...)' notation; as a shortcut, simple variables and expressions can be abbreviated as '@variable', '@object.attribute', '@function(arguments)', '@sequence[index]', and combinations. Full-fledged statements are embedded with '@{...}'. A '@' followed by a whitespace character (including a newline) expands to nothing, allowing string concatenations and line continuations. Comments are indicated with '@#' and consume the rest of the line, up to and including the trailing newline. '@%' indicate optional "significators," which are special forms of variable assignment intended to specify per-file identification information in a format which is easy to parse externally. '@(...?...:...)' allows for conditional expressions, and '@(...$...)' allows handling of exceptions thrown from expressions. Finally, a '@@' sequence expands to a single literal at sign. Getting the software The current version of empy is 1.4. The latest version of the software is available in a tarball here: http://www.alcyone.com/pyos/empy/empy-latest.tar.gz. The official URL for this Web site is http://www.alcyone.com/pyos/empy/. Requirements empy should work with any version of Python from 1.5.x onward. License This code is released under the GPL. ... Release history [since 1.3] - 1.4; 2002 Sep 7. Fix bug with triple quotes; collapse conditional and protected expression syntaxes into the single generalized '@(...)' notation; 'empy.setName' and 'empy.setLine' functions; true support for multiple concurrent interpreters with improved sys.stdout proxy; proper support for 'empy.expand' to return a string evaluated in a subinterpreter as intended; merged Context and Parser classes together, and separated out Scanner functionality. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ The work of many cannot be done alone. \__/ (a Bemba proverb) Python chess module / http://www.alcyone.com/pyos/chess/ A chess game adjudicator in Python. From billgates at msn.com Sun Sep 22 09:08:29 2002 From: billgates at msn.com (El Jesuita) Date: Sun, 22 Sep 2002 14:08:29 +0100 Subject: wxTreeCtrl and Drag&Drop Message-ID: Hi, how can I use drag and drop any wxTreeCtrl node? Thank you -- fmarcelo(AT)airtel(DOT)net From gustav at morpheus.demon.co.uk Mon Sep 9 17:05:50 2002 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: 09 Sep 2002 22:05:50 +0100 Subject: Pysol Solitaire for Windows wanted References: <2MPe9.47925$Jo.5395@rwcrnsc53> Message-ID: "Alan Winston" writes: > > I have done the Google exercise several times over recent months, and have > > never gotten a working Windows installable, only the pyc files, which > > briefly open a Python window, display some messages (presumably errors) > > then close again before I can read the messages. There are bugs in the Windows code for the latest version (4.80). IIRC, it also depended on a version of Tk which isn't the standard. None of the problems were impossible to solve, but they were a mild pain, and the result is *not* the same as the original, as the supplied .pyc file is somehow built as a single file from multiple source files. The author is also effectively uncontactable, which makes getting fixes included in the source pretty much impossible. It's a real pain, as PySol is a really good program. If anyone could package it up again, I'm sure the result would be of value to a lot of people... Paul. From never at mind.info Wed Sep 18 07:43:16 2002 From: never at mind.info (G. Willoughby) Date: Wed, 18 Sep 2002 12:43:16 +0100 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: > Can someone point me to a good Python GUI app to demonstrate (other > than IDLE)? I wrote a GUI interface to another python console app to create maps for an online game by reading the installed in-game graphics, 3D model and terrain data, see it here: http://www.thecalm.fsnet.co.uk/MapperGUI --G. Willoughby From maxm at mxm.dk Tue Sep 3 05:05:23 2002 From: maxm at mxm.dk (Max M) Date: Tue, 03 Sep 2002 11:05:23 +0200 Subject: Why it is so dramatical? References: <20020902.104707.1789376348.1554@cybermesa.com> Message-ID: <3D747B53.6000307@mxm.dk> Bo M. Maryniuck wrote: > On Monday 02 September 2002 05:47, Jay O'Connor wrote: > >>As a result Perl is much faster at some kinds of operations than >>Python, and vice-versa. > > > Yeah, actually, but I just would like to find some optimal Python solution :) Actually it is possible to make it as readable as concatenation with: result = [] a = result.append a('some string') a('another string') a('third string') for letter in 'abcdefghijklmnop': a(letter) result = ''.join(result) rather than: result = '' result += 'some string' result += 'another string' result += 'third string' for letter in 'abcdefghijklmnop': result += letter regards Max M From peter at engcorp.com Sun Sep 15 23:09:07 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 15 Sep 2002 23:09:07 -0400 Subject: can wxpython do this? References: <737aefee.0209151702.3f735252@posting.google.com> Message-ID: <3d854b44@news.sentex.net> Lothar Scholz wrote: > On 15 Sep 2002 18:02:17 -0700, erick_papadakis at yahoo.com (Erick > Papadakis) wrote: > > There is no problem to setup an installer easily that takes > Python,WXPysthon and whatever you need. It simply blowes up the > installer package size. A better option, although I haven't tried it myself, would be to use py2exe to build an executable, then package that up using one of the regular installers. This should come out substantially smaller than a full Python+wxPython+app installation. -Peter From shalehperry at attbi.com Fri Sep 6 13:06:13 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 6 Sep 2002 10:06:13 -0700 Subject: question: iso 14977 ebnf grammar for Python? In-Reply-To: <77977a28.0209060856.6974e6eb@posting.google.com> References: <77977a28.0209060856.6974e6eb@posting.google.com> Message-ID: <200209061006.13290.shalehperry@attbi.com> On Friday 06 September 2002 09:56, Michael Weigend wrote: > Hello! > > Is there a ebnf grammar for Python written according to the ISO 14977 > standard somewhere in the www? > > Michael asks not familiar with that standard but in the source under Grammar/ is a definition of the grammar in something very close to ebnf. From op73418 at mail.telepac.pt Thu Sep 26 13:28:10 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Thu, 26 Sep 2002 18:28:10 +0100 Subject: design question References: <1ha6pukqdqell8f31q1k7rtor2rv5ogjs0@4ax.com> Message-ID: On Thu, 26 Sep 2002 11:56:05 -0500, "Mark McEahern" wrote: >[Gon?alo Rodrigues] >> I know I am being a little vague in my question, but does anyone have >> any ideas? Open-source code where this "same problem" has been tackled? > >Have you considered metaclasses? Do you need a concrete Wrapper for each >class? Why not a generic wrapper that wraps any given class? > Well, I have thought that somewhere further down the way some (though not all) of the wrapping code could be factored out in some kind of metaclass, and then I would just set __metaclass__ at module level. But since I am still at the entrance, I am kinda polling for ideas. Assuming that my description of the problem is enough, how would you go about writing a metaclass as a general wrapper? >// m > All the best, Gon?alo Rodrigues From max at alcyone.com Thu Sep 5 15:11:49 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 05 Sep 2002 12:11:49 -0700 Subject: Graham's spam filter References: <3D647B4B.28D9BF04@alcyone.com> <3D655AE6.A097AA25@alcyone.com> <3D770156.2E55864C@alcyone.com> Message-ID: <3D77AC75.B9B7F27@alcyone.com> Christopher Browne wrote: > Have you considered simply replacing strings that appear to be > base64-encoded with a token like "base64-text"? > > That allows the database to at least be aware that the spam commonly > contains base64 data. Well, that really depends on what your goal is. Again, if you're one of those people that has a very tight circle of email buddies and so essentially any unsolicited email is by definition spam, then you can tighten down your spam filter in all kinds of very powerful ways. I, as I've mentioned before, receive unsolicited email from my Web sites and various projects, and so unfortunately don't have the luxury of doing this. So I need to support receiving email from faraway lands and unknown email addresses as well as trying to vigorously filter spam. Fact is, unfortunately, lots of people send legitimate email that is MIME encoded. > -> Supposing there is interesting text encoded (such as source code > for a virus) inside the base64 stuff, it _would_ be useful to > decode it; > > -> Supposing the base64 stuff is basically just a GIF/JPEG/PNG, or > something else that doesn't contain "interesting text," you'll > have not much of value from the decoding process. > > Making the "tokenizing" step a tad smarter (e.g. - recognizing "this > is likely base 64" and collecting stats on numbers of lines of base64 > material) requires minimal added effort, and I expect it would buy you > _most_ of the benefits of decoding. Spammers are hitting upon the strategy, though, of sending emails in which the body consists of nothing but a completely encoded base64 MIME part. So in that case, the entire body of your message would consist solely of your "base64encoded" token. So in the general case of any kind of spam filter (not just limited to a Graham filter), it's questionable how useful this will be, unless you plant to always filter against that token, presuming it to always indicate spam. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From lienard.bruno at free.fr Sat Sep 21 05:01:54 2002 From: lienard.bruno at free.fr (Bruno Liénard) Date: Sat, 21 Sep 2002 11:01:54 +0200 Subject: Htmlxtract modules Message-ID: <3d8c3668$0$225$626a54ce@news.free.fr> I am looking for the HtmlXtract packages quoted in the "vaylts of Parnassus" repository. The quoted link seems to be dead. So can somebody send it to me ? Thanking you by advance, Bruno Lienard From ulbi at ivs.tu-berlin.de Tue Sep 24 02:56:32 2002 From: ulbi at ivs.tu-berlin.de (Andreas Ulbrich) Date: Tue, 24 Sep 2002 08:56:32 +0200 Subject: Jython file manipulation?! References: <2yej9.32454$gA4.4053@sccrnsc02> Message-ID: Matthew Bonig wrote: > There are no exceptions raised... > If you look at the source Jython uses for the os.rename function it just > uses Java's File.renameTo()... > that function returns false... which then the os.rename function throws a > OSError exception, but it's not helpful in any way. > The only thing I can think is happening is that I am doing this renaming on > files that are on a netword drive on a win32 box, but I have double > checked... the new filename is NOT there... (since win32 won't overwrite the > new file if it exists, and therefore return an error, but that's not > happening). I've also double checked to make sure I have write permissions > on the network drive, which I most definetly do (I usually write 3-5 files > onto that drive a day). > This is why I thought there might be some sort of security issue with > Jython... I'm pretty sure it's in the Jython side since when I tried exactly > the same thing (os.rename(oldfilename, newFilename)) in python it worked > perfectly. Sounds weird. Have you tried to write a java program and check the results? Maybe it's an java issue ... Which java you are using? From mstenner at phy.duke.edu Tue Sep 10 08:59:28 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Tue, 10 Sep 2002 08:59:28 -0400 Subject: Pickle problem In-Reply-To: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D10@hendrix.empolisuk.com>; from hst@empolis.co.uk on Tue, Sep 10, 2002 at 01:44:57PM +0100 References: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D10@hendrix.empolisuk.com> Message-ID: <20020910085928.B4329@phy.duke.edu> On Tue, Sep 10, 2002 at 01:44:57PM +0100, Harvey Thomas wrote: > Erik Price wrote: > > > > On Tuesday, September 10, 2002, at 06:13 AM, Harvey Thomas wrote: > > > > > I'm trying to pickle a complicated data structure which includes a > > > dictionary whose entries are created by (simplified): > > > > > > a[x] = re.compile(y).match > > > > > > The pickle fails, however, with the error: > > > > > > PicklingError: Can't pickle > _sre.SRE_Pattern > > > object at > > > 0x00838700>: it's not found as __main__.match > > > > > > I'd be grateful if someone could tell me if it is possible > > to pickle > > > the data structure and what I'm doing wrongly. > > > > Are you trying to store the MatchObject returned by a call to > > a regular > > expression object's match() method? If so, it looks like you're > > forgetting the parens at the end of "re.compile(y).match". > > > No, I haven't forgotten the parentheses. I'd like to pickle the match method of the compiled regular expression. My bad... I just reread this. I had misread it before. Sorry for the misunderstanding. I am bit curious about what you get out of pickling the method that you can't get from the compiled re object itself. You can always call the match method after unpickling, right? -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From zopestoller at thomas-guettler.de Thu Sep 26 06:37:18 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 26 Sep 2002 12:37:18 +0200 Subject: Length of file extension Was: convention for Pickler file extension References: <918bc22f.0209230208.4eaca702@posting.google.com> Message-ID: Richie Hindle schrieb: >>I call files *.pickle > > > Me too. > > Are there any non-medieval platforms that don't let you have arbitrary > length file extensions? I think it works for Win98, WinNT, Win2000 and of corse Unix. Don't know about Mac or MacOSX thomas From tchur at optushome.com.au Sat Sep 7 19:01:16 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 08 Sep 2002 09:01:16 +1000 Subject: Smoothing a discrete set of data References: <3csmdso5.fsf@morpheus.demon.co.uk> Message-ID: <3D7A853C.5E5BD96B@optushome.com.au> Fernando P?rez wrote: > > Tim Churches wrote: > > > AFAIK, there is no native Python package which > > implements a > > comprehensive range of regression and smoothing techniques, but I can > > highly > > recommend the R package for statistics and statistical graphics - this > > mature, free, open > > source package has more statistical facilities than you are ever likely > > to need. > > While not as comprehensive as R in its statistical coverage, SciPy probably > has enough in it for what the OP wants (which sounded fairly basic). Quick > linear (in the parameters) fits are easily done with scipy, plotting, simple > smoothing (if he wants to), etc. I know R is industrial-strength statistics, > but it sounds like more than what the OP needed. Yup, although I suggested R because a) some very gentle companion introductions to basic statistical analysis are available for R (see for example http://cran.r-project.org/doc/manuals/R-intro.pdf or the various documents listed at http://cran.r-project.org/other-docs.html ); and b) R will not run out of steam when the OP realises that there might be a wee bit more to the analysis of his data than he first thought eg some of his data are almost certainly time series and hence he will need access to techniques which take auto-correlation etc into account. Of course, the biggest hurdle for Pythonistas who want to use R is the fact that R uses one-based indexing, not zero-based indexing as intended. Tim C From gerhard.haering at opus-gmbh.net Tue Sep 10 10:05:14 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 10 Sep 2002 14:05:14 GMT Subject: os.tempnam() warning References: Message-ID: Rajarshi Guha wrote: > The C library advises against using tempnam() and suggests using > mkstemp(). Is there any Python equivilant? tempfile.mktemp() -- Gerhard From nospam_t.roessler at v-d.com Thu Sep 26 07:16:52 2002 From: nospam_t.roessler at v-d.com (Thilo =?ISO-8859-15?Q?R=F6=DFler?=) Date: Thu, 26 Sep 2002 13:16:52 +0200 Subject: Zope, MySQL and pictures in blob-fields ... Message-ID: Hello to everybody! I'd like to provide users with a possibility to upload pictures into a MySQL-Database. Therefore I created a web-form (using method="post" and enctype="multipart/form-data") with an input for uploading files (). The action of the form calls a SQL-Method that stores the data received from the into a MySQL-table (insert into Vorschlag values([...])). The picture should be put into a blob-field. I used 'type="string"' because "file" or something similar does not exist. Finally, the record gets stored into the MySQL-database, but the picture isn't saved the way I expected. Taking a look at the content of the table using webmin, the appropriate field just shows "". Can anybody tell he how I manage to save/upload the picture and possibly even show it again in a website afterwards? Thanks in advance, and sorry if it is a simple question ... I tried to find a solution but couldn't find one. Thilo From cliechti at gmx.net Fri Sep 27 13:24:53 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Sep 2002 19:24:53 +0200 Subject: watching mutables? References: Message-ID: anton at vredegoor.doge.nl (Anton Vredegoor) wrote in news:an211j$oi$1 at news.hccnet.nl: > On Fri, 27 Sep 2002 09:34:55 -0500, "Mark McEahern" > wrote: > >>l = Watched() >>l.append(1) > > Thanks for reacting to my question. However, I am looking for > something that calls a defineable function if *any* mutable variable > in the current scope changes. Variables should be 'marked' to install > this function for them. For example 'watch(m,f)' indicates that > function f is called if mutable variable m is changed. I do not want > function f to be a method of object m since I want object m to be > *any* mutable python object and furthermore I do not want to change > the orginal object. The call of function f would be triggered by *any* > change of object m. This would make debugging (and some other things I > am tinkering with) a lot easier. Is it possible? see EventObj: http://oomadness.tuxfamily.org/p-pyobjtools.php chris -- Chris From whisper at oz.net Mon Sep 16 23:26:06 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 16 Sep 2002 20:26:06 -0700 Subject: More on Protecting Source Code Message-ID: I have read what I consider to be the narrow minded and short sighted views wrt to protecting IP in the form of Python source code, and I would like to make a few points. * Not everyone believes that all or most software ought to be free. I for one, don't. * Owners of property have the right to control it. If you disagree and own a nice car or house, I'll be right over :-> * Why invest a substantial amount of time and money developing in a language that makes it trivial to gain access to the work product? Python may be easy to use, but if it's also easy to steal software written in it, that's an impediment to it's being widely used in commercial products, especially shrink-wrapped products. Perhaps that's a reason why there seems to be so few commercial products in Python, beyond those that are fairly closely licensed and/or have substantial parts of the app written in C/C++. I suppose one solution is to modify the Python interpreter with different op-codes and that ought to make it somewhat painful for the average hacker. A better solution is to make a .pyc file approximately as hard as a binary .exe file to decompile - however that could be done. David LeBlanc Seattle, WA USA From simon at callan.demon.co.uk Tue Sep 17 14:43:56 2002 From: simon at callan.demon.co.uk (Simon Callan) Date: Tue, 17 Sep 2002 19:43:56 +0100 Subject: using python as cgi on apache unix References: Message-ID: <664284774b.simon@satin.callan.demon.co.uk> In message wrote: > All, > > I have developed a python solution to run and connect to a mysql > database. I did all my development under windows apache 1.3.26 and > python 2.2.1. I know want to move this to my unix server. > Unfortunately, no matter what I do I can not get apache on my linux > box to execute any python scripts. I get the following errors in > apache: > > Premature end of script headers: /var/www/html/cgi-bin/test.py Check the access permissions on the file. On my setup, the file has to have the "other" access permissions set to read and execute. Ie try typing "chmod o+rx test.py", and trying again. It took me some time to spot this problem, when I had it. Simon From aleax at aleax.it Fri Sep 20 10:01:54 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 14:01:54 GMT Subject: Newbia alert .. working my way through Easy Python Montana Edu page, need help.. References: Message-ID: Highwaykind wrote: ... > def print_options() : You define this function, but never call it anywhere. > choice = 'p' > while choice != 'q': > if choice == 'r': > a=input ("width") > b=input ("height") > print "result",rect (width,height) Note that the print is NOT aligned with the input calls, but rather with the if statement. Thus, the print (and its call to rect) is not conditional -- it happens even when choice is NOT 'r'. This is unlikely to be what you want, so, indent this print statement 4 more spaces rightwards. However, the crux of your problem is another: > But the thing keeps telling me width is not defined, also I can;t use Inddeed, width is not a defined variable: what you obtained from the call to input("width") you did not assign to the name width, but rather to the name a. Therefore, the variable that is defined once this statement has executed is named a. Therefore, change your call to rect to rect(a,b) -- and similarly for the following passages in your code. > the ELIF command .. THink I could do with some help :) The reason you can't use elif (not a 'command' -- a clause in an if statement) is probably the indentation problem I mentioned earlier -- once you fix that you can probably also change the following if's to elif's (not the first one of course). When indentation returns to the same level as the word 'if', it means the if statement is over: therefore you cannot "reprise" it later, continuing it, so to speak, with an elif clause. Once you correct the indentation of the print statements, this will change. Alex From bokr at oz.net Mon Sep 30 00:42:39 2002 From: bokr at oz.net (Bengt Richter) Date: 30 Sep 2002 04:42:39 GMT Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: On Sun, 29 Sep 2002 17:33:57 -0500, "Chris Gonnerman" wrote: >----- Original Message ----- >From: "Bengt Richter" > > >> On 29 Sep 2002 17:06:53 GMT, Christopher Browne wrote: >> >> >The problem with FP is that FP involves the use of binary >> >approximations, which commonly cannot exactly represent >> >decimal values. >> > >> >Notably, the decimal fraction 0.1, which is /exactly/ 1/10, >> >does not have any exact encoding in binary. Its >> >representation in binary is a repeating binary fraction. >> >> How is that a significantly different problem from repeating >> decimal fractions? (E.g., 1/3. or 1/7. or wxyz/9999. which >> will give you 0.wxyzwxzy..?) > >Humans think in decimal. To a human, 1.0/10.0 == 0.1, not >0.10000000000000001. OK, so this *rounds* to 0.10 at two >decimal places, but what about: > >>>> .70 * .05 >0.034999999999999996 > >Rounded to two decimals, that's 0.03; but done in proper >decimal numbers, the answer should be 0.035, rounded to 0.04 >using either "classic" or "banker's" decimal rounding. > >If you are calculating sales tax, for instance, this is >unacceptable. > >(I borrowed this example from memory from a previous poster, >and if I could remember who it was I'd give credit...) > >You ask how it is a different problem. Simple. A human, I hope that includes me ;-) >training in decimal math in grade school, knows that > > 1/3 = 0.3333333... > >and would *expect* it to round to 0.33 (still in two decimal >places). The problem with *binary* floating point is the >"surprise factor." > Old programmers aren't surprised by anything. They expect the unexpected ;-) >So, Bengt, how do I do this right using only floats? I can't. >I have to have decimal arithmetic to get the right answer. > It goes back to requirements. E.g., >>> for x in xrange(100): ... for y in xrange(100): ... fx = float('.%02d' %x) ... fy = float('.%02d' %y) ... fxy = fx*fy ... xy = x*y ... sfxy = '%.2f' % (fxy*1.000000001) ... sxy = '0.%02d' % ((xy+50)/100) ... assert sfxy == sxy ... finishes sans problem, as a quick check on a limited problem domain. Obviously a proper test suite and some math would be required to show validity for a realistic problem domain. If you can specify exactly how your decimal virtual machine works, (i.e., how many significant figures are carried, how it rounds/truncates intermediate values etc., and how many figures are going to be in the inputs and outputs, then we can determine how much of a problem it will be to do it using floating point. The example you cited is included in the above: >> '%.2f' % ( .05 * .70) 0.03' >> '%.2f' % (-.05 * .70) -0.03' changes to >> '%.2f' % (( .05 * .70) * 1.000000001) 0.04' >> '%.2f' % ((-.05 * .70) * 1.000000001) -0.04' There is not unlimited room in the double floating point space around the true abstract real values corresponding to decimal representations, but there is quite a bit, unless you are carrying a lot of figures. E.g., as an approximate indication, >>> '%.2f' % ((.0349999999 ) * 1.0000000001) '0.03' >>> '%.2f' % ((.03499999999 ) * 1.0000000001) '0.03' >>> '%.2f' % ((.034999999999 ) * 1.0000000001) '0.04' and the multiplier is probably bigger than it has to be (and better specified in binary). But that can be optimized when you specify your decimal virtual machine. If you need rounding that alternates direction on alternate exact trailing fives, then you need an extra step. If you visualize the true theoretical decimal values representable in your decimal virtual machine as little red glowing dots on the real axis, and visualize as little glowing blue dots all the exact theoretical numbers corresponding to all valid bit combinations in a floating point double, then if every pair of successive red dots has thousands of blue dots in between, and the error in floating point calculations can be held to within a few blue dots, then you can see how to select the red dot that represents the true decimal answer, even if there is no blue dot exactly coinciding with it. Twelve decimal digits would give about a thousand blue dots between the red ones. And a thousand times that while still in the FPU, before storing in memory. Rounding an exact decimal is moving from one red dot to another, perhaps skipping hundreds or thousands of dots, depending on fractional decimals carried. But we must round by moving from some blue dot to another blue dot. By shifting the blue uncertainty set reliably to one side of its true red dot, we can move from blue dot to blue dot where the new blue dot will reliably be in an uncertainty set corresponding to the proper red dot. If more blue dots are needed, they can be arranged. If you are doing very few operations, so that the range of blue dot uncertainty that can be accumulated is small, then you can have more red dots. Regards, Bengt Richter From sadams123 at optushome.com.au Tue Sep 17 00:50:39 2002 From: sadams123 at optushome.com.au (Steven) Date: Tue, 17 Sep 2002 14:50:39 +1000 Subject: More on Protecting Source Code References: Message-ID: <3d86b4a0$0$23173$afc38c87@news.optusnet.com.au> "David LeBlanc" wrote in message news:mailman.1032232999.22661.python-list at python.org... > I have read what I consider to be the narrow minded and short sighted views > wrt to protecting IP in the form of Python source code, and I would like to > make a few points. > > * Not everyone believes that all or most software ought to be free. I for > one, don't. > > * Owners of property have the right to control it. If you disagree and own a > nice car or house, I'll be right over :-> > > * Why invest a substantial amount of time and money developing in a language > that makes it trivial to gain access to the work product? > > Python may be easy to use, but if it's also easy to steal software written > in it, that's an impediment to it's being widely used in commercial > products, especially shrink-wrapped products. Perhaps that's a reason why > there seems to be so few commercial products in Python, beyond those that > are fairly closely licensed and/or have substantial parts of the app written > in C/C++. but if you're worried about protecting your IP, then wouldn't your package be under a closed license? > I suppose one solution is to modify the Python interpreter with different > op-codes and that ought to make it somewhat painful for the average hacker. > A better solution is to make a .pyc file approximately as hard as a binary > .exe file to decompile - however that could be done. >From what I've read of that thread, the gist of it was "once its released, a determined person can, to some extent get your code" and "Security through obscurity is no security against a determined attacker" So, someone who is willing to hacka nd hack and hack away at your code, can get at it, and this is true for things coded in assembler, C, Python or Befunge. Most people aren't determined attackers, they're simply Joe Average who needs to get a job done. An operating system is a complex beast, compiled into machine code its even more complex, how many people out there are using an unlicensed copy of Windows or Office? they didn't decompile, that would take skill, they just copied it bit for bit and posted the registration key. Do a very very simple risk analysis. Who is your target audience, what is the price of your software, will people bother going through your bytecode, or will they just post the registration key to a website? Will stolen software lead to a loss in revenue - or will those pirate users be people who would never have bought it in the first place? (yes, the pirate users are annoying, and you would feel ripped off, but OTOH you haven't lost money, and you've gained a bunch of users) Steven From martian_bob at portalofevil.com Thu Sep 26 18:17:28 2002 From: martian_bob at portalofevil.com (Bob Arens) Date: Thu, 26 Sep 2002 22:17:28 GMT Subject: Newb - web portal for Unix tool Message-ID: Hiyo, total newbie to Python though not HTML, etc. I'm writing a web-based portal allowing users to use Expat by entering their XML into a form. The HTML is trivial - just a text area and submit button. I'm using a pretty good reference for the CGI bit (Internet Programming with Python by Watters, van Rossum and Ahlstrom), but their examples don't seem to be working for me. So here are my big questions: 1. How do I write out input from a text area to a file? 2. How do I make a command line call from within a CGI script? 3. How can I debug my script? Here (more or less) is what I have for the script (where METHOD="POST" and TEXTAREA NAME="XMLin" in the HTML, and testme.xml is the file I'm writing to) ---------------------------- import genCGI, string class ExPortal(genCGI.ParseMixin, genCGI.Verbose_Mixin, genCGI.cgiBase): MultiValuedFields = ["XMLin"] def success(self): items = self.formdict.items() items = map(str, items) items = string.joinfields(items) outfile = open("testme.xml") outfile.write(items) outfile.close() if __name__=="__main__": ExPortal().GO() ----------------------------- Any help is much appreciated! From fedor at mailandnews.com Wed Sep 18 09:21:42 2002 From: fedor at mailandnews.com (Fedor Baart) Date: Wed, 18 Sep 2002 15:21:42 +0200 Subject: running external programs References: Message-ID: You might want to try: import webbrowser webbrowser.open('url') or import os os.system('application') "Jonathan Beebe" wrote in message news:p%_h9.507714$UU1.83878 at sccrnsc03... > Is there a function or library i can import that i can use to run external > programs from within my program? > > example: > > runprogram("iexplore.exe") > > thanx, > -JONATHAN BEEBE > > > From loewis at informatik.hu-berlin.de Tue Sep 3 06:56:29 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 03 Sep 2002 12:56:29 +0200 Subject: Which XML parser under Python can handle Unicode? References: <9ac02e81.0209030214.515d6c0@posting.google.com> Message-ID: jhorneman at pobox.com (Jurie Horneman) writes: > Could someone please recommend an XML parser under Python which can > handle Unicode? The "standard" parser of Python 2.x, ie. xml.parser.expat, supports Unicode quite well, as do all libraries on top of this parser (xml.sax, xml.dom.minidom). Since PyXML 0.7, xmlproc supports Unicode as well. > Specifically, most European languages and Asian > languages such as Chinese (traditional, simplified), Japanese, Korean > and Thai? (Please don't make me look up the actual codetables.) All of those languages are supported by all Python XML parsers, in various encodings - but best in UTF-8. > Ideally the parser would use Python's codec system. pyexpat/Expat has builtin codecs for UTF-8 and Latin-1, and falls back to Python codecs - but only for byte-oriented encodings. xmlproc uses the Python codec system. > I'd prefer an event-based parser, although tree-based would not be a > huge problem. Both pyexpat and xmlproc are event-based. I'd recommend to use SAX on top of this, which is also event-based. Regards, Martin From pedronis at bluewin.ch Sun Sep 29 11:23:35 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Sun, 29 Sep 2002 17:23:35 +0200 Subject: FYI (was: watching mutables?) References: <3d96f25a$0$498$7a628cd7@news.club-internet.fr> Message-ID: <3d971af8$1_3@news.bluewin.ch> "Jiba" ha scritto nel messaggio news:3d96f25a$0$498$7a628cd7 at news.club-internet.fr... > > Try EditObj (http://oomadness.tuxfamily.org/en/editobj) and look at the > module editobj.eventobj. > > It does exactely what you need, but it is quite a hack... FYI in Python 2.3: __class__ will be immutable for builtin types, and only mutable for (user) subtypes. See: http://mail.python.org/pipermail/python-checkins/2002-August/028681.html regards. From jjl at pobox.com Sat Sep 28 13:12:24 2002 From: jjl at pobox.com (John J. Lee) Date: Sat, 28 Sep 2002 18:12:24 +0100 Subject: Strange behavior of ClientCookie and site-packages In-Reply-To: <6cb82943.0209191238.4b116988@posting.google.com> References: <6cb82943.0209191238.4b116988@posting.google.com> Message-ID: On 19 Sep 2002, Brian Ibbotson wrote: [...ClientCookie works from command line, but...] > However, Idle for Python 2.2 cannot do the same. With an identical set > of paths reported by sys.path, including the ClientCookie reference > above, Idle reports: > > >>> import ClientCookie > Traceback (most recent call last): > File "", line 1, in ? > import ClientCookie > ImportError: No module named ClientCookie > >>> > > Can anyone suggest an explanation for this behavior? Other third-party > modules installed to site-packages (such as ChartDirector and MySQLdb) > have had no problems once they are included in sys.path That's odd. I don't use IDLE -- have you checked the IDLE docs for any information about import peculiarities? All ClientCookie does, as you've no doubt seen, is to import the 'public' names from various modules into __init__.py, so that they can be imported using from ClientCookie import foo rather than from ClientCookie._some_obscure_module import foo So you may be able to work around the problem by doing the latter (look in __init__.py to see what import statements you need). Perhaps you'd have better luck asking directly about IDLE's behaviour in this case. Let me know if it's something that can/should be fixed in ClientCookie. BTW, you'll have a much better chance of getting a prompt response from me if you mail me questions about ClientCookie rather than (or in addition to) posting them here -- I don't read c.l.py very often now. John From justnotworking at yahoo.com Wed Sep 18 09:51:42 2002 From: justnotworking at yahoo.com (mowestusa) Date: Wed, 18 Sep 2002 08:51:42 -0500 Subject: (Newbie) Menu Not Functioning Message-ID: I have created the following simple program. import os def menu(): print "1. Copy Python Files from Office Computer to Floppy" print "2. Copy Python Files from Home Computer to Floppy" print "3. Copy Python Files from Floppy to Office Computer" print "4. Copy Python Files from Floppy to Home Computer" print "5. Quit" print def officetoflop(): os.system("xcopy C:\MyDocu~1\*.py a:") def hometoflop(): os.system("xcopy E:\MyDocu~1\*.py a:") def floptooffice(): os.system("xcopy a:\*.py C:\MyDocu~1") def floptohome(): os.system("xcopy a:\*.py E:\MyDocu~1") menu_choice = 0 while menu_choice < 5: menu() menu_choice = input("Enter your selection:") if menu_choice == 1: officetoflop() elif menu_choice == 2: hometoflop() elif menu_choice == 3: floptooffice() elif menu_choice == 4: floptohome() else: print "Goodbye" As you can see it is designed to simply keep all of my python files current between home and work. I know that there are probably better ways to write this program by not using "os.system", but using "shutil" instead. I tried that first but I couldn't figure out how you could get just the ".py" files from a directory, and then put into "shutil.copyfile". The problem I have with my script is that I can only run it once. For example it lets me choose "1". It copies all of the files onto the floppy without problem. Then the menu appears and the line "Enter your selection:", but it doesn't allow me to make another choice. I can't type in any key from the keyboard at all. The program seems to freeze. Any ideas why? I tried using the same technique shown in the menu examples given in the "Non-programmers Tutorial." Thanks for the help. mowestusa From gupsmail at ihatespam.shaw.ca Wed Sep 25 11:02:06 2002 From: gupsmail at ihatespam.shaw.ca (Grant Hallam) Date: Wed, 25 Sep 2002 15:02:06 GMT Subject: problem with dictionaries within lists References: Message-ID: Thnks for the clarification...I must have gotten confused on that one. :), I didn't realize that dict was a builtin...changed to be more representative of the actual contents. Using the .copy() worked great. Thanks. Grant (da gup) On Wed, 25 Sep 2002 07:51:21 -0700, Alex Martelli wrote: > Grant Hallam wrote: > >> The problem with blanking out the dictionary with dict{} is that it >> wipes the keys out. As the loop goes through it assigns the matching >> second half of the list to a matching key. If you insert a print >> statement on the dict you can see the values in the dict are changing. >> Thus while it is the same dict the key values within the dict are >> different. Thats why I'm somewhat confused as to why its the same dic >> value. As for the tabs, > > It's the same dict object because you didn't copy it. You just appended > many references to it to the list. So, just use: > >>> webdatabaselist.append(dict.copy()) > > appending *copies* of the dict to the list, and you should be OK. > > BTW, avoid naming your own variables like builtins -- list, dict, file, > int, str, &c -- you'll come to grief eventually when you do that and > then some other piece of your code tries to use the builtin in the > normal way. It's always possible to find a more significant name, > anyway, so avoiding the types' names is no burden. (This has nothing to > do with your specific problem -- it's just general advice). > > > Alex From oliver.eichler at dspsolutions.de Mon Sep 9 03:37:22 2002 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Mon, 09 Sep 2002 09:37:22 +0200 Subject: Howto debug self? Message-ID: Hi Is it possible to debug self with pdb? I mean it in the sense of getting a list of vars and their values. I know I can do: pdb> print self.xyz but is there a way to dump a complete list of all vars within self. The same applies for a class instance. I would like to dump all of it vars at a time. Without knowing the class structure like the print command in pdb assumes. Pretty much stuck here... Oliver From ws at mystrobl.de Sun Sep 22 16:33:31 2002 From: ws at mystrobl.de (Wolfgang Strobl) Date: Sun, 22 Sep 2002 22:33:31 +0200 Subject: How to get memory usage on Windows? References: Message-ID: "GerritM" : >"Wolfgang Strobl" schreef in bericht >news:f51sou8o4j9pkilhc3g6jevkqmkk7jr3pl at 4ax.com... >> "GerritM" : >> >> >Searching in books , documentation (a.o. win32api) and net did not yet >help >> >I found this article on the net: >> >http://www.developeriq.com/Magazinestories/02jul29memory.php3 >> >but how to call this function from Python? >> >> I guess thanks to Mark Hammond you already have everything you need. >> >> Have a look at \Python22\Lib\site-packages\win32\Lib\win32pdhutil.py, >> uncomment the test function, run it. >> >> I snarfed the following snippet straight from win32pdhutil.py: ><...snip...> >> -- >> Wir danken f?r die Beachtung aller Sicherheitsbestimmungen > >Wolfgang, > >thanks. I think this will work only on NT. Here at home I have "only" >windows98, which gives the following message: >"RuntimeError: The pdh.dll entry point functions could not be loaded." Well, I haven't used windows 98 anymore for years, but I guess you're right. > >I will have to try this at work, on a windows2000 machine. That's what I'd do. Another option would be using calldll (see http://www.nightmare.com/software.html). This is more dangerous, but will most probably work on any win32 system. -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From pete at shinners.org Mon Sep 23 11:41:02 2002 From: pete at shinners.org (Pete Shinners) Date: Mon, 23 Sep 2002 15:41:02 GMT Subject: PyGame + PyOpenGl + ZBuffer? References: <3D8EDCEF.70F827F6@hotmail.com> Message-ID: Max wrote: > I found my code is not working well in all computers: with a SiS 300/200 > graphic card, the Z buffer seems disabled. > > The OpenGL initialization code is: > > pygame.init() > pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF|HWSURFACE,32 ) > glEnable(GL_DEPTH_TEST) > glDepthFunc(GL_LESS) > glDepthRange(0,1) > > How can I force Opengl to utilize ZBuffer? pygame has a function to control extra setting for opengl. it must be called before display.set_mode(). you'd probably want to pass something like "pygame.display.gl_set_attribute(GL_DEPTH_SIZE, 16)". perhaps try different sized depths? http://pygame.org/docs/ref/pygame_display.html#gl_set_attribute you might also try testing with GLUT, which usually builds with pyopengl. From thoa0025 at mail.usyd.edu.au Tue Sep 17 08:11:55 2002 From: thoa0025 at mail.usyd.edu.au (:B nerdy) Date: Tue, 17 Sep 2002 12:11:55 GMT Subject: raw post data References: Message-ID: yeah good guess! and thats something that looks like it will werk =B thanks "Alex Martelli" wrote in message news:siAh9.118475$pX1.4269024 at news2.tin.it... > :B nerdy wrote: > > > how could i make it so when i read the stdin it still is there.. cause i > > use cgi.FormVariables() also > > When you instantiate class cgi.FieldStorage (there's no such > thing as cgi.FormVariables, so I'm just guessing at what it IS > that you want!) you can pass it an optional first parameter > that is a file object open for reading -- it uses sys.stdin > as the default if you don't pass the first parameter. > > Thus, the following should work (untested!): > > import cgi, sys, cStringIO > > copyInput = cStringIO.StringIO(sys.stdin.read()) > fieldStorage = cgi.FieldStorage(copyInput) > > > The raw posted data are now available as the string returned > by calling copyInput.getvalue(), and are also parsed by cgi to > obtain fieldStorage. > > > Alex > From robin at jessikat.fsnet.co.uk Thu Sep 5 10:57:13 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 5 Sep 2002 15:57:13 +0100 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> <3d765ce6_4@news.bluewin.ch> <3d767c4a$1_1@news.bluewin.ch> <3d774f40$1_1@news.bluewin.ch> Message-ID: In article <3d774f40$1_1 at news.bluewin.ch>, Samuele Pedroni writes >Ok, I have discovered an undocumented fact and maybe relevant fact. ....... >Now one can log class loading, you can edit jython.bat and >put -verbose:class in there: > >"..java.exe" -verbose:class "-Dpython.home=..." > >then running jython.bat > >you should get an initial burst of [Loaded ] >and then normally nothing or a pattern of > OK I get over 600 lines at the initial burst which ends with ....... [Loaded sun.reflect.GeneratedMethodAccessor18] [Loaded sun.reflect.GeneratedMethodAccessor19] [Loaded org.python.modules.MD5Object] [Loaded reportlab.lib.fonts$py] [Loaded java.io.RandomAccessFile from C:\Program Files\Java\j2re1.4.0_01\lib\rt.jar] [Loaded sun.reflect.GeneratedMethodAccessor20] memory usage climbs continuously and then Exception in thread "CompileThread0" java.lang.OutOfMemoryError: requested 32756 bytes C:\jython-2.1\reportlab\test> >[Loaded ...] >... >[Unloading class ...] > >If you get an increasing sequence of [Loaded ...] without corresponding >[Unloading class ...] then we have reduced >the possible suspects. > >regards. -- Robin Becker From edream at tds.net Fri Sep 20 09:36:23 2002 From: edream at tds.net (Edward K. Ream) Date: Fri, 20 Sep 2002 13:36:23 GMT Subject: Setting cursor colors in tkinter Message-ID: Hi, I would like to set the foreground an background colors of a cursor. Following: http://www.tcl.tk/man/tcl8.3/TkLib/GetCursor.htm#M4 I am synthesizing a cursor description with cursor="xterm " + fg + " " + bg yielding, e.g., cursor = "xterm red green" I then call: body.configure(cursor=cursor) However, Tcl complains: self.tk.call((self._w, 'configure') TclError: bad cursor spec "xterm red green" Can anyone say how this should properly be done? Put another way, I may be asking what the proper format of "name [fgColor [bgColor]]" is in the URL above. Thanks. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From marklists at mceahern.com Thu Sep 12 13:42:22 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 12 Sep 2002 12:42:22 -0500 Subject: dynamic includes from classes... In-Reply-To: Message-ID: [mike] > First, is there a better way than exec to dynamically include a module? > i.e. > importvar = "foo" > exec("from %s import %s" % (importvar, importvar)) s = "sys" sys = __import__(s) print sys.path // m - From shagshag13 at yahoo.fr Fri Sep 20 10:40:18 2002 From: shagshag13 at yahoo.fr (Shagshag13) Date: Fri, 20 Sep 2002 16:40:18 +0200 Subject: bit operations ? Message-ID: hello, i'm looking for any libs which could handle bit operations on integer. (i must be able to get 0 to n bits from any int., only bit j, etc.) thanks in advance, s13. From aunueco at veritas.com Sat Sep 21 06:10:16 2002 From: aunueco at veritas.com (Allen Unueco) Date: 21 Sep 2002 03:10:16 -0700 Subject: Creating a standalone embedded Python app. Message-ID: I'm looking for a way to somehow bundle the Python modules that my embedded application uses. I would like to be able to distribute an executable file that would work without having Python installed on the system. I would rather have everything in one file but having the modules in a separate bundle (pickle?) would be workable. Is there any clever way to do this? Any help would be very appreciated. -allen From kseehof at neuralintegrator.com Tue Sep 10 19:32:02 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Tue, 10 Sep 2002 16:32:02 -0700 Subject: COM, Outlook, and constants Message-ID: <4.3.1.0.20020910162432.00c10c80@pop.hurrah.com> I just upgraded my windows box to XP, and resumed working on a Outlook COM project that I haven't touched for a few weeks. For some reason it doesn't work anymore. Anyway, the symptom I am trying to resolve now is that win32com.client.constants doesn't seem to work anymore. It's supposed to acquire attributes for all constants defined in loaded COM servers through its __dicts__ attribute. The following is typical of python COM client code. Any hints? >>> import win32com.client >>> ol = win32com.client.Dispatch("Outlook.Application") >>> ns = ol.GetNamespace("MAPI") >>> oc = win32com.client.constants >>> oc.olFolderInbox Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\lib\site-packages\win32com\client\__init__.py", line 131, in __getattr__ raise AttributeError, a AttributeError: olFolderInbox >>> oc.__dicts__ [] >>> Thanks, - Ken Seehof From wlfraed at ix.netcom.com Thu Sep 19 17:04:44 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 19 Sep 2002 14:04:44 -0700 Subject: execfile syntax & zope error References: Message-ID: dd fed this fish to the penguins on Thursday 19 September 2002 02:07 am: > Hi, > > Im having problem using execfile. > > Using execfile('filename.exe') on zope for web purpose, generate an > error: > > An error has occurred. The Site Admistrator has been notified. > global name 'execfile' is not defined and Traceback (innermost last) > Doesn't Zope run python in bastion (?) mode -- IE, restricted execution to prevent access to non-Zope file space? -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From sismex01 at hebmex.com Wed Sep 25 11:35:39 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 25 Sep 2002 10:35:39 -0500 Subject: parsing from a position found with a regexp Message-ID: > > Hi, > > I would like to parse only a portion of a particular > file. The portion I am interested in starts after the > last occurrence of a particular string in the file. > Ideally, I was hoping there might be a function > (perhaps like the string rfind function, but for > files) that would make this quick and simple. Any > suggestions? > > Thanks, > Mark > Dealing with text files, in a random-access fashion, is never "quick and simple" :-( But, something like the following might help? def file_rfind(fp, string): last_pos = -1 pos = fp.tell() for line in fp: if line.find(string) > -1: last_pos = pos pos += len(line) return last_pos I haven't tested it though, but the final solution won't be too far away, conceptually. :-/ AND, remember that text files in M$ operating systems are 2-chars, and on unix and mac-os based systems are 1-char, and this can cause problems when opening files in text mode. Good luck :-) -gustavo Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From gmuller at worldonline.nl Wed Sep 18 14:23:31 2002 From: gmuller at worldonline.nl (GerritM) Date: Wed, 18 Sep 2002 20:23:31 +0200 Subject: MarketProductLifecycle References: Message-ID: "Steve Holden" schreef in bericht news:cVNh9.15168$T4.10611 at fe04... > "GerritM" wrote in message > news:am81ff$pdh$1 at reader1.tiscali.nl... > > > > Oops pressed the send key before verifying the destination... > > > > This does not belong here, but how to cancel from OE5? > > > > Select your message (you have to be able to see it on your server...) and > select "cancel message" from the "Message" menu. > > regards > ----------------------------------------------------------------------- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/pwp/ > Previous .sig file retired to www.homeforoldsigs.com > ----------------------------------------------------------------------- > thanks, I already succeeded in cancelling. The file which was attached is the source version of the (very preliminary) presentation at: http://www.extra.research.philips.com/natlab/sysarch/MarketProductLifecycleS lides.pdf which has no relation with Python, except that generation of documents and webpages are automated via Python. regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From no at mail.com Mon Sep 16 19:24:05 2002 From: no at mail.com (BT) Date: Mon, 16 Sep 2002 23:24:05 GMT Subject: Source code References: Message-ID: > > I really don't understand posts like these. > > You think I'm fool to protect my work? > > No, only a bit uninformed if you think you can get "security through > obscurity". Obscuring the code will dissuade only the most casual or > incompetent from decompiling/disassembling your code. Sort of like > hiding a spare key to your house under the "Welcome" mat. I was talking to people who suggest to "seek psychiatric help" if you want to protect your code. I know that no protection is unattacable but, I think it's better to protect something instead of release source code and write in a .txt file "please, don't copy it". > > I can give you the phone of my clinic, but stop it NOW, join the ideal > > world. > > You mean the "real" world. No, I meant "ideal": I was persuading Id people to join open source ideology. > This question ("how can I obscure Python byte-code?") comes up at least > once a month on this list. It's fairly clear that any scheme you come > up with will take longer to implement than it will to break by a > competent hacker. True.. that's why I'm planning to obfuscate the code then encrypt it. A hacker (not every programmer) is specialized in modify jmp instructions and could find the password to decrypt the .pyc in less than 20 minutes, but maybe 5% of them knows about python. Then obfuscated source should persuade everyone to steal the code: sometimes it's difficoult to modify even a source with comments. > Anyway, good luck! If your software is any better than your protection > scheme I'll download it from http://www.warez.com when you release it ;) I'd like it: it would means my software it's worth to crack. From cben at tx.technion.ac.il Thu Sep 12 14:50:36 2002 From: cben at tx.technion.ac.il (Beni Cherniavsky) Date: 12 Sep 2002 11:50:36 -0700 Subject: "str"(expr)"str" interpolation syntax References: Message-ID: "Mark McEahern" wrote on 2002-09-10: > Beni Cherniavsky wrote: > > I was searching for a new interpolation syntax ... > > > > You might be interested to: > > 1. Checkout the PEPs for string interpolation and simple string > substitution. > 2. Read this thread: > > http://groups.google.com/ > groups?selm=ouit4e63fr.fsf%40andlx-anamika.cisco.com > > 3. Read the archives from Python-Dev regarding the relevant PEPs. > Read them all before (except py-dev but I dind't find much new there now). > After you do all that, you may reconsider or reframe your suggestion in > light of what has been discussed. > To tell the truth my idea looked nice while I tossed it in my head but when I actually wrote the post I noticed that something doesn't look well... The "Bleagh" reply said it best though perhaps a bit strongly :-) Anyway I wanted to get feedback on how it looks to others. As for the motivation [to answer the other posts]: I'm a happy user of "%d" % x but I was targeting here the cases of long strings and other reasons why PEPs 215 and 292 came to be. I didn't like (and still don't) the idea that I need to scan string literals for _code_. Especially if I might want to nest strings inside that code... It can confuse editors but that's a sign it can also confuse me. I thought for a moment that I found a nice solution but it turns out not to be nice... Still I don't like interpolations as in the PEPs. [Never liked double quotes in perl/shell either]. I'd rather stick to %s... Maybe something very simple along the lines of: subst("A template string - here: % it goes\n", foo, "Also multiple values: %, %\n", bar, quux, "Quoting percent (%) sings probably not needed...\n", '%') could be useful... Yes it smells like perl formats but the intelacing of pictures/values is really near optimal IMHO. I've just read perl 6's plans for formats and they have hyphenation! Beat me if I want that in a language core ;-) From bobx at linuxmail.org Mon Sep 16 16:42:52 2002 From: bobx at linuxmail.org (Bob X) Date: Mon, 16 Sep 2002 20:42:52 GMT Subject: [ANN] PySQLite 0.3.0 released References: Message-ID: Steve Holden wrote: > > No, his two-paragraph "sig" is a PITA, but probably it's not aa sig but > something that his company's mailer sticks on the end of all message quite > gratuitously, just so some corporate lawyer can sleep better (fancying his > ass is covered). > > regards > ----------------------------------------------------------------------- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/pwp/ > Previous .sig file retired to www.homeforoldsigs.com > ----------------------------------------------------------------------- > And here I thought a PITA was a sandwich! :-) Bob From brueckd at tbye.com Fri Sep 6 18:36:14 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 6 Sep 2002 15:36:14 -0700 (PDT) Subject: Larry Wall's comment on python... In-Reply-To: Message-ID: On 6 Sep 2002, Tim Daneliuk wrote: > > The very idea of Larry Wall lecturing on code readability is hilarious. > > > > -Dave > Well, that's true, but for all of its similarity to line noise, perl has > been an enormous contribution to our profession/community. I would never want > to diminish Wall's stature, therefore. Me neither, and I didn't intend it that way. There's just something very pot-calling-the-kettle-black about it, that's all. -Dave From mstenner at phy.duke.edu Fri Sep 13 16:46:12 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Fri, 13 Sep 2002 16:46:12 -0400 Subject: Coding Style: Quotes In-Reply-To: ; from thorsten@thorstenkampe.de on Fri, Sep 13, 2002 at 10:05:45PM +0200 References: Message-ID: <20020913164612.A14152@phy.duke.edu> On Fri, Sep 13, 2002 at 10:05:45PM +0200, Thorsten Kampe wrote: > * John Waycott > > I'm curious if others have adopted any standards for choice of single vs. > > double quotation marks to delimit strings. A look through the standard > > library reveals the choice of one over the other is rather arbitrary. I > > suspect it really makes no difference, but the question has come up during a > > code review. > > Python itself seems to "prefer" single quotes slightly: > 1: >>> "String" > 1: 'String' > 2: >>> I hate to be so picky, but it _is_ after all, my nature... :) Just because it uses the single quote doesn't mean it prefers it. It (or the authors, rather) had to choose. They couldn't just not pick one. Also, the method you use to input the string IS NOT part of the string, and so should be dropped after it's role (encoding the string) is complete. Therefore, your example does not support your statement. Of course, I suspect it is for just this reason that you quoted "prefer". :) -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From phoebe_1 at att.net Tue Sep 24 20:43:40 2002 From: phoebe_1 at att.net (Holden Caulfield) Date: 24 Sep 2002 17:43:40 -0700 Subject: Solaris 64 bit compilation References: Message-ID: loewis at informatik.hu-berlin.de (Martin v. L?wis wrote in message news:... > phoebe_1 at att.net (Holden Caulfield) writes: > > > > > "./Include/pyport.h", line 480: #error: "LONG_BIT definition appears > > > > wrong for platform (bad gcc/glibc config?)." > > > > > > So what value has SIZEOF_LONG in pyconfig.h? > [...] > > To answer your questions: > > - pyconfig.h does say 8 as SIZEOF_LONG > > That raises the question then why the error in pyport.h is > produced. LONG_BIT comes from limits.h, and, if _LP64 is defined, is > 64. So I'm still uncertain what you did to provoke this error. > > > - 'curses' modules does not compile. > > - 'dbm' modules compiles fine but core dumps during test. > > So, I disabled these modules in 'setup.py' and built it and ran the > > make test. > > curses fails for me as well, since it finds a 32-bit ncurses > installation; dbm also core dumps here. > > > test test_time failed -- Traceback (most recent call last): > > File "./Lib/test/test_time.py", line 46, in test_mktime > > time.mktime, (999999, 999999, 999999, 999999, > > File "/apps/python/build/Python-2.2.1/Lib/unittest.py", line 279, in > > failUnlessRaises > > raise self.failureException, excName > > AssertionError: OverflowError > > This is a known bug (#460357), which has been fixed in CVS. > > > 2) > > test_gettext > > test test_gettext crashed -- exceptions.OSError: [Errno 20] Not a > > directory: 'xx/LC_MESSAGES/gettext.mo' > > I believe this also has been fixed in CVS. > > > Are there any plans to support 64-bit python executable/module on > > solaris platforms for future versions? > > Building python in 64-bit mode on Solaris works already. Some modules > may still not work; patches are welcome. > > > Is anyone even interested in the configure.in patches? > > I don't really see a need, since it works fine without the patches. > Well, I will have to disagree here. As currently at lease in V2.2.1 vanilla source there is *no* option to built in 64 bit mode, unless you hack the CFLAGS, LDSHARED etc. Unless, you know of way to pass the appropriate flags? Because my expectation was that I could build 64bit excutable/object/module by running "configure", currently out of the box I could *not* figure out a way to do this. > Regards, > Martin From emile at fenx.com Sun Sep 1 21:17:25 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 1 Sep 2002 18:17:25 -0700 Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: Robert: > (wow what a great password this link would make): > > http://groups.google.com/groups?hl=en&lr=lang_en&ie=UTF-8&oe=UTF-8&safe=acti > ve&threadm=mailman.997727540.19628.python-list%40python.org&rnum=1&prev=/gro > ups%3Fhl%3Den%26lr%3Dlang_en%26ie%3DUTF-8%26oe%3DUTF-8%26safe%3Dactive%26q%3 > DRe%253A%2BCopy%2Bconstructors%2Bpython > OT A trick to shortening a groups.google link is to identify the thread or message identifer and the specific message id and just pass that part. These are the segments that start 'selm=' or 'threadm='. In the reference above, it's this part: threadm=mailman.997727540.19628.python-list%40python.org then put http://groups.google.com/groups? in the front to get: http://groups.google.com/groups?threadm=mailman.997727540.19628.python-list% 40python.org Emile van Sebille emile at fenx.com From gmcm at hypernet.com Wed Sep 11 18:37:16 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 11 Sep 2002 22:37:16 GMT Subject: Building a python executable archive References: <6c20157a.0209110826.3e98a77@posting.google.com> Message-ID: [posted and mailed] Rich Browne wrote: > I'm trying to build python as an archive bound executable. > > This sounds dumb, Python is inherently dynamic, so why am I doing > this? > Because the python executable will have to execute without any dynamic > dependencies on shared libs outside the build environment that I plan > to install it in. > > I have succeeded in statically linking most of the shared objects... snip > ... This works, but I'm looking for an > easier(automated)way to do this. Have you looked at whether Installer http://www.mcmillan-inc.com/install1.html can be made to suit your needs? It's not statically linked, so you have to control the shared libs along with the exe, but it's designed to operate from only it's own directory tree, (so you can ship an app built from one version of Python without fear of conflicts with an installed version). > Also, what is the difference between the *.pyo and *.pyc files. At this point, not much (the pyo's omit line numbers and maybe doc strings?). The goal is to have pyo's be the product of an optimizing compiler. -- Gordon http://www.mcmillan-inc.com/ From jdhunter at ace.bsd.uchicago.edu Thu Sep 26 19:07:32 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 26 Sep 2002 18:07:32 -0500 Subject: indexing and searching pdf files In-Reply-To: (Rajarshi Guha's message of "Thu, 26 Sep 2002 18:05:37 -0400") References: Message-ID: >>>>> "Rajarshi" == Rajarshi Guha writes: Rajarshi> Hi, I have a load of pdf files and I would like to index Rajarshi> them so that I can serach them for keywords. I was Rajarshi> thinking of using pdftotext to generate the textfile and Rajarshi> then create the index from that. As far as I have been able to tell, the pdftotext approach is about as good as any. Darrell Gallion was kind enough to forward a Plex parser to me that he had been working on which I'm sure he would send to you if you asked: dgallion1 at yahoo.com. I haven't had a chance to look at it yet. You could also consider exposing your pdf dirs to a web server, and induce google to crawl it. You could then use their advanced pdf searching, cacheing, html-izing and indexing capabilities by doing an advanced search restricted to your server. You could use pygoogle and do the same if you wanted to stay within the fold. JDH From paul at boddie.net Mon Sep 30 09:54:34 2002 From: paul at boddie.net (Paul Boddie) Date: 30 Sep 2002 06:54:34 -0700 Subject: DBI cursor behaviour with multiple statements? References: <7e964d1d.0209270137.568a3f3@posting.google.com> Message-ID: <23891c90.0209300554.5b37c195@posting.google.com> Henrik.Weber at sys.aok.de (Henrik Weber) wrote in message news:<7e964d1d.0209270137.568a3f3 at posting.google.com>... > Hello, > > I'm trying to write a DBI2 compliant module for Microsoft Access > databases. Now I'm not quite sure how to interpret the DBI2 > specification when it comes to the execution of multiple data > returning statements with the same cursor. > > For example if c is my cursor and I do: > c.executemany("SELECT * FROM table WHERE column = '%s'", [["parm1"], > ["parm2"], ["parm3"]]) Note that you probably don't want the quoting inside the SQL statement. In other words, it should be... "SELECT * FROM table WHERE column = %s" Personally, I'd recommend supporting different parameter notations, since this issue always confuses people. > should the result be the union of all three statements or just the > result of the first or the last statement? Or should the user switch > from one resultset to the next with nextset? An interesting, related issue is the treatment of the IN operator, and this doesn't necessarily yield uniform treatment across database modules, even for the same database system (compare pyPgSQL and psycopg on PostgreSQL). For some applications of your query (where you want the union), the IN operator is probably what is desired: "SELECT * FROM table WHERE column IN %s" This appears highly counter-intuitive, of course, since the Python-style %s parameter marker actually represents a list in this case - another reason for choosing a better parameter notation. Paul From jlselsewhere at my-deja.com Thu Sep 5 16:24:04 2002 From: jlselsewhere at my-deja.com (J. L. Schilling) Date: 5 Sep 2002 13:24:04 -0700 Subject: Memory fault - core dumped while compiling python 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> <3D765A05.6030004@nospam.yahoo.com> <3D768753.8030302@nospam.yahoo.com> <3D76A139.1030304@nospam.yahoo.com> Message-ID: bokr at oz.net (Bengt Richter) wrote in message > > [...] > > How about > cc -v > ? Just for the record, cc -V is the option on the SCO compiler to report its version. It should show something like this on an OSR 5.0.5 system: 217$ /bin/cc -V SCO UNIX Development System Release 5.1.1A 27Jul98 Usage: cc [ options ] files ... The cc -v option enables lint-like warnings. Jonathan Schilling From python at rcn.com Mon Sep 9 23:45:35 2002 From: python at rcn.com (Raymond Hettinger) Date: Mon, 9 Sep 2002 23:45:35 -0400 Subject: dynamism References: <66715c02.0209091923.265fe77e@posting.google.com> Message-ID: "Steven Shaw" wrote in message > I thought that you could access dictionary values with object syntax: > > >>> x = { 'a': 1, 'b':2 } > >>> x > {'a': 1, 'b': 2} > >>> x.a > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'dict' object has no attribute 'a' > > Maybe you could never do this as shown but I'm sure there were ways of getting > this effect. Anyone care to remind me? >>> class AttrDict: pass >>> ad = AttrDict() >>> ad.__dict__ = {'a': 1, 'b':2} >>> ad.a 1 >>> ad.b 2 >>> class BetterAttrDict(dict): def __getattr__(self, key): return dict.__getitem__(self, key) >>> bad = BetterAttrDict({'a': 1, 'b':2}) >>> bad.a 1 >>> bad.b 2 Raymond Hettinger From donn at drizzle.com Wed Sep 25 00:31:40 2002 From: donn at drizzle.com (Donn Cave) Date: Wed, 25 Sep 2002 04:31:40 -0000 Subject: popen2() gives broken pipe for large files - is it fixed yet? References: None Message-ID: <1032928299.406088@yasure> Quoth Frank Gibbons : ... | It worked fine for a small test file, but I get a broken pipe for realistic | sizes (1MB). I've written a little test script that shows the same behavior | (see below). I've searched the newsgroups, and find that popen2() has a | history of breaking the pipe on large files. Does anyone know if this has | been fixed? Is popen3 any better? I've also read that the os module now has | a popen function (as of Python 2.x, forget which x). Is this any better? ... | data = f.readlines() ... | zip_output, zip_input = popen2.popen2("%s -c "% GZIP) | data = string.join(data, "") ... | zip_input.write(data) ... | zipfile = open("popen.gz", "w+") | zipfile.write(zip_output.read()) It isn't going to be fixed, either, because there are just some axiomatic truths in operation here, like "I/O buffers aren't infinitely elastic." Since your example doesn't do anything with the output, you don't have to shoot yourself in the foot this way. Try something like this - zip_input = os.popen('gzip -c > popen.gz', 'w') while 1: data = f.read(16000) if not data: break zip_input.write(data) zip_input.close() The main point is that this allows gzip to write directly to disk. If your actual application needs to process the data further at this point, you may read it back from disk and write to a new file if you like. Otherwise, if you really want a second pipe, you have to figure out how to read some, write some, etc., to keep gzip's output from filling up while you're trying to write all its input. Donn Cave, donn at drizzle.com From pjdurai at hotmail.com Mon Sep 30 14:12:21 2002 From: pjdurai at hotmail.com (pjd) Date: 30 Sep 2002 18:12:21 GMT Subject: embedding question: cant import some modules Message-ID: Hi I am embedding Python 22 in a C++ application. Everything works fine except when I import a module like win32api, which is installed in C:\Python22\Lib\site-packages\win32, it complains that it cant find the module. The sample script I am executing works fine when executed from the shell with Python.exe. But failes with module not found, when executed from my C++ app. I have tried to set PYTHONPATH( = C:\Python22\Lib\site-packages\win32), and PYTHONHOME to various values . No avail. Is there something I need to do inside my app, to make it find the installed modules ? Any ideas ? Appreciate your time. cheers pj From sross at connectmail.carleton.ca Wed Sep 18 09:07:11 2002 From: sross at connectmail.carleton.ca (Sean Ross) Date: 18 Sep 2002 13:07:11 GMT Subject: Splitting a list of strings References: Message-ID: Terry: Thank you. However, I do not decide what format will be applied to the data, I operate on what is provided. Moreover, the data really is not what I'm interested in. (Mark asked to see a sample, so I provided it.). Your suggestion is certainly true and I would follow it, if I could. What I was interested in was finding a way to do a three pronged filter of a list of strings using a single list comprehension. Sort of like a change filter, where you drop handfuls of change into the top of the device and they come out the other side sorted into pennies, nickels, dimes, quarters. In this case I had comments, attributes, and data. The comments could be redirected to a chaff outlet, i.e., ignored, so long as the attributes and data where filtered properly. The suggestions people have provided are fine (using an attribute and data list, marching through the list of lines from the file and sticking an attribute string into the attribute list and a data string into the data list). They do what I need to accomplish, but they are not quite what I was looking for. Think of it this way, if I have a pile of pennies, nickels, and dimes, and pull out all the nickels, then I have a pile of nickels and a pile of pennies and dimes. Using list comprehensions, I've been able to create the pile of nickels, but the original pile is unchanged. That's as it should be, I suppose. However, I guess what I was looking for was a side-effect, or some such mechanism where, by extracting the nickels, I get the two piles: one of nickels, one of pennies and dimes. I want my cake, and to eat it too, in other words. You can probably just chalk this all up to an infatuation with list comprehensions. Thanks again, to all, for your suggestions Sean From claird at starbase.neosoft.com Wed Sep 18 09:25:05 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 18 Sep 2002 08:25:05 -0500 Subject: minimizing Tk programs to the taskbar References: <3D8872F1.87850856@optushome.com.au> Message-ID: <656913E3D19D40D2.0831BD5165F06A87.FDA870F87AEF2207@lp.airnews.net> In article , Alex Martelli wrote: >Richard Tardif wrote: > >> Is there any way to minimize programs to the taskbar? I'm talking about >> windows here. By taskbar I mean the area down in the bottom right >> corner, near the clock, that shows icons for what proggies you've got >> running. Thanks for any help. > >I don't think Tkinter offers such an intrinsically non-cross-platform >functionality. I suspect therefore that you'd need to work this part >through the win32all add-ons, win32gui.Shell_NotifyIcon &tc. . . . ? Alex and Richard, I think you'll want to experiment with root = Tkinter.Tk() ... Tkinter.Wm.iconify(root) Alex' intuition that a lot of the operations people say they want are platform- or window-manager-specific is certainly apt. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From shalehperry at attbi.com Wed Sep 25 03:40:12 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 25 Sep 2002 00:40:12 -0700 Subject: problems defining an empty list In-Reply-To: <20020925070654.GB57911@partagas.as.de.cw.net> References: <20020925070654.GB57911@partagas.as.de.cw.net> Message-ID: <200209250040.12209.shalehperry@attbi.com> On Wednesday 25 September 2002 00:06, Manuel Hendel wrote: > This is what I'm trying to do: > > # empty list for lines per domain > linesperdomain = [] > linesperdomain = [domain, domainlines] > print linesperdomain > > domainlines is also a list. > > Error: > > linesperdomain = [] > ^ > IndentationError: unindent does not match any outer indentation level > it sounds like you have a hidden piece of whitespace. Perhaps the code is indented when it should not be? If the code is not in a loop, class, if structure, etc then it should not be indented. From fb at ultranet.com Mon Sep 9 20:47:31 2002 From: fb at ultranet.com (basegmez) Date: Mon, 9 Sep 2002 20:47:31 -0400 Subject: returning values from FORTRAN with f2py References: Message-ID: Chris Fonnesbeck wrote in message ... >I am wondering how to persuade some fortran code that I have compiled >with f2py to return its calculated values to me in python. I have >some code that does gaussian elimination (mostly from Numerical >Reciopes), and is supposed to return an inverted matrix so that I can >solve a system of linear equations. However, when run in python, the >function runs without error but returns no values: > >>>> a = [[2,1,3],[1,-1,1],[3,6,-1]] >>>> b = [7,2,10] >>>> import gauss >>>> gauss.gauss(a,3,b,1) >>>> > >Is there something that I have to change in my fortran code to make >this work? > >Many thanks, >cjf I just used Numeric to do something similar. I used Newton-Raphson to solve a set of non-linear equations. from __future__ import nested_scopes from Numeric import array from Numeric import matrixmultiply as mm from Matrix import inverse g = 386.08 ''' Given Ix, Iy, Iz, and weight, calculates X, Y and Z dims of a rectangular box uses Newton-Raphson to solve three simultaneous nonlinear equations''' def dim_box(w, Ix, Iy, Iz, tol = .0001): m = w/g mc = m/12 def f(x, y, z): # Function return array([(y**2 + z**2)*mc - Ix, (x**2 + z**2)*mc - Iy, (x**2 + y**2)*mc - Iz]) def J(x, y, z): # Jacobian return array([[0, 2*y*mc, 2*z*mc], [2*x*mc, 0, 2*z*mc], [2*x*mc, 2*y*mc, 0]]) x, y, z = 1.8, 4, 5 for i in range(200): res = mm(inverse(J(x, y, z)), -f(x, y, z)) + array([x, y, z]) x, y, z = res[0], res[1], res[2] check = f(x, y, z) if abs(check[0]**2 + check[1]**2 + check[2]**2) <= tol: return x, y, z print 'No solution!', '\n', f(x, y, z), '\n', x, y, z # Example: # >>> dim_box(1000, 1600, 700, 1800) # (45.6599607331 79.0853715939 34.0329252342) Alternatively, you can use the solve_linear_equations from LinearAlgebraModule. from Numeric import array from LinearAlgebra import solve_linear_equations as solve #Example: # a + b = 5 # 2a - b = 7 #should give # [4., 1.] LHS = array([[1, 1], [2, -1]]) RHS = array([5, 7]) print solve(LHS, RHS) Fahri Basegmez From yaipa at aol.com Wed Sep 18 13:30:53 2002 From: yaipa at aol.com (yaipa) Date: 18 Sep 2002 10:30:53 -0700 Subject: Is Python 2.1 for Solairs 8 broke on SunFreeware? References: <8d148763.0209131005.65de04a8@posting.google.com> Message-ID: <8d148763.0209180930.56cd3f92@posting.google.com> loewis at informatik.hu-berlin.de (Martin v. L?wis wrote in message news:... > yaipa at aol.com (yaipa) writes: > > > % /usr/local/bin/python CronTar.py -c cronTar.cfg > > Traceback (most recent call last): > > File "/export/fruid/bin/CronTar.py", line 26, in ? > > import time > > ImportError: ld.so.1: /usr/local/bin/python: fatal: > > libgcc_s.so.1: open failed: No such file or directory > > % > > That is somewhat unfortunate: gcc 3.2 links another shared library to > every binary. > > > Am I required to have gcc installed also? > [...] > > Any ideas? > > No need to do that. Just install the libgcc package from Sunfreeware > also. This is much less than the full GCC. > > Regards, > Martin Thanks Martin. I'll give that a try this weekend. One of those times when I should have know, and if not, should have asked sooner. Thanks again. Yaipa From pedro_rodriguez at club-internet.fr Mon Sep 30 09:02:59 2002 From: pedro_rodriguez at club-internet.fr (Pedro RODRIGUEZ) Date: Mon, 30 Sep 2002 15:02:59 +0200 Subject: Find out link location References: <7uf9na-vd9.ln@lbdb01.gsi.de> Message-ID: On Mon, 30 Sep 2002 14:26:47 +0200, Klaus Hoeppner wrote: > with the os.path module I can use the islink function to check, wether a > file is symbolic link. But how can I find out, where the link points to. > E.g. if I have readme.txt --> ../packages/mypackage/readme.txt how do I > get the "../packages/mypackage/readme.txt" with python? > in http://www.python.org/doc/current/lib/os-file-dir.html : os.readlink("readme.txt") Pedro From fgibbons at hms.harvard.edu Tue Sep 24 11:04:03 2002 From: fgibbons at hms.harvard.edu (Frank Gibbons) Date: Tue, 24 Sep 2002 11:04:03 -0400 Subject: popen2() gives broken pipe for large files - is it fixed yet? Message-ID: <5.0.0.25.2.20020924105700.00ad1a08@hms.harvard.edu> Hi, I'm trying to allow users of my CGI script to download rather large data files by clicking a button. The solution which worked for small test files was this: - Create a button whose action is to print the formatted data with the appropriate content-type header, so that the desired application will open. - Create another button whose action is to open a pipe to gzip (using popen2()), write the same data into the pipe, then write the output from the pipe to the browser, again with appropriate content-type, to say that it's a zipped file. It worked fine for a small test file, but I get a broken pipe for realistic sizes (1MB). I've written a little test script that shows the same behavior (see below). I've searched the newsgroups, and find that popen2() has a history of breaking the pipe on large files. Does anyone know if this has been fixed? Is popen3 any better? I've also read that the os module now has a popen function (as of Python 2.x, forget which x). Is this any better? TIA, Frank Gibbons #!/usr/bin/python import os import popen2 import string GZIP = "/bin/gzip" filename = "ChIP_Squared_Template_FR2.txt" f = open(filename) data = f.readlines() f.close() print "Read %d lines" % len(data) zip_output, zip_input = popen2.popen2("%s -c "% GZIP) data = string.join(data, "") print "LEN(data) = %d" % len(data) zip_input.write(data) #zip_input.close() zipfile = open("popen.gz", "w+") zipfile.write(zip_output.read()) zipfile.flush() zipfile.close() PhD, Computational Biologist, Harvard Medical School BCMP/SGM-322, 250 Longwood Ave, Boston MA 02115, USA. Tel: 617-432-3555 Fax: 617-432-3557 http://llama.med.harvard.edu/~fgibbons From gerhard.haering at gmx.de Fri Sep 6 02:45:29 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Fri, 6 Sep 2002 08:45:29 +0200 Subject: How to install informixdb-1.3 for python2.2 on RH7.3? In-Reply-To: References: Message-ID: <20020906064529.GB614@lilith.ghaering.test> * J Dubal [2002-09-05 23:22 -0700]: > Hello again! > > I managed to compile and install informixdb module manually for py221. > However, when I import it in python2, it gives following error: > ImportError: Cannot locate C core module for informix db interface. Normally, I write a setup.py using Python's distutils in such cases, however informixdb seems to use some sort of SQL preprocessor for the ext/_informixdb.ec file. So, I'd try to perform the step with the SQL preprocessor manually, then invoke "python setup.py build". > If I try import _informixdb, it gives following error: ImportError: > /opt/informix/lib/esql/libifgen.so: undefined symbol: stat You need to link against a additional libraries. If the Informix documentation is silent about this, I'd recommend to ldd on some client utility of the database and add these libraries in the Makefile. -- Gerhard From marco at boo.it Wed Sep 4 12:18:24 2002 From: marco at boo.it (kyro) Date: Wed, 04 Sep 2002 16:18:24 GMT Subject: Program for ... HELP!!! Message-ID: Hello everybody, I need a little piece of program thath calculate the determinant of a square matrix. Can somebady help me?!??!?!?! Thanks a lot >>kyro<< P.S.: I think to use the recursion, but I don't use thr recursion in Python, I'm a newby.... :oP From bkc at Murkworks.com Mon Sep 9 18:15:22 2002 From: bkc at Murkworks.com (Brad Clements) Date: Mon, 9 Sep 2002 18:15:22 -0400 Subject: Larry Wall's comment on python... References: Message-ID: <3d7d1ae6$1_1@goliath.newsgroups.com> "All is fair if you predeclare." I declare, Larry is some kind of anti-Guido! -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From tdelaney at avaya.com Thu Sep 26 01:09:03 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 26 Sep 2002 15:09:03 +1000 Subject: revenge of the python puzzle Message-ID: > From: Michal Wallace [mailto:sabren at manifestation.com] > > Okay, so you guys think you're so smart. Try this one! No > contest this time, I've learned my lesson. (I suppose if > someone really wants some free hosting bad enough to solve > this puzzle, you could talk me into it, but I'm just posting > this for revenge... Um, I mean "fun".) Hmm - a little bit harder. The fake perl actually made it easier though (gave while and s). def decrypt(yourstring): dedict = { 'a': 'm', 'b': 'r', 'c': 'y', 'd': 'j', 'e': 'b', 'f': 'd', 'g': 'l', 'h': 'i', 'i': 'e', 'j': 'u', 'k': 'w', 'l': 'v', 'm': 'o', 'o': 'k', 'p': 't', 'q': 'g', 's': 's', 't': 'x', 'u': 'p', 'v': 'f', 'w': 'c', 'x': 'h', 'y': 'n', 'z': 'a', } return "".join([dedict.get(i,i) for i in yourstring]) data = r'''wbjig_ucpxmy, kxzp_xzli_h_fmyi \ ='ilhg.zuuiyf(ghsp(izwxmyi))',\ "zkvjg wmfi hs sm ajwx vjy" hv 'h za sazbp': 'hp djsp ahqxp bjy' "hp's sm ajwx kmbsi pxzy 'xiggm kmbgf'" "kxc, pxisi yitp ghyis zgamsp gmmo ghoi uibg!" 'kxhgi(<>){wxmau;s/uibg/ucpxmy;ubhyp}';mbzyqis='vbjhp'; ezf="'iyhpgzlm bjmc oyhbf'=qsa;qsa gzemgqtqsa pyhbu"; iaupc="";qgmezg izwxmyi;ilhg=[]; 'ejp z siwbip xibi hs hy cmjb bizwx' zuugis=mbzyqis, "izwxmyi=izwx" fiv fm(pzso="fm kxzp h zso"): qgmezg izwxmyi; itiw pzso "zyf djsp hy wzsi cmj'bi ymp uibugitif," kmbsi,ymk = (ezf.sughp('t'),"!") vmb izwx hy kmbsi: itiw zuugis[1] hv izwx hy kmbsi: fm(wbjig_ucpxmy) kmbsi = ilhg; "ilhg".sughp().bilibsi() [izwx.bilibsi() vmb izwx hy kmbsi] "zyf ymk ki'li bizwxif pxi vhyzg libsi"; azu(fm, azu(iaupc.dmhy, kmbsi))''' print decrypt(data) From johann.hoechtl at myrealbox.com Mon Sep 30 07:28:46 2002 From: johann.hoechtl at myrealbox.com (Johann Höchtl) Date: Mon, 30 Sep 2002 11:28:46 GMT Subject: Stackless Python Howto Message-ID: <1033385295.69247@charme.kabsi.at> Hello! Can someone give me a short briefing how to use stackless python? I thought it's all about a replacement of python.dll, and as long as you don't use stackless threading and continuations, at least arbitrary, lightweight recursion will be available. However, the famous ackermann function with parameters ack (3, 7) and onwards still failes because of stack constraints. What else do i have to specify to be go stackless? Thank you, Johann From edream at tds.net Thu Sep 12 14:59:14 2002 From: edream at tds.net (Edward K. Ream) Date: Thu, 12 Sep 2002 18:59:14 GMT Subject: Cursed newlines and readline() Message-ID: <6u5g9.11312$Da3.1133980@kent.svc.tds.net> According to one of Leo's Linux users, the Python's readline() routine on Linux delivers "\r\n" line end strings verbatim, while the windows versions force the string to use the Unix convention of using only "\n". This seems unfortunate. Is there a justification for it? If not, I would like to suggest that readline() work the same on all platforms and that it deliver only "\n" as a line terminator. This is an example of what I have come to call the "cursed newline" problem, a problem that seems trivial, and in fact has caused me, by far, the most grief as a programmer trying to write cross-platform software. BTW, TK handles this problem superbly, so well that one might not even suspect that it is a problem. Any comments? Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From jggramlich at yahoo.com Thu Sep 5 17:40:19 2002 From: jggramlich at yahoo.com (Joshua Gramlich) Date: 5 Sep 2002 14:40:19 -0700 Subject: PyListObject & C Modules References: Message-ID: Okay...I finally got it. in: if(!PyArg_ParseTuple(args, "O!", &list)) return NULL; The option "O!" doesn't work. If you look at the tutorial* :D http://www.python.org/doc/current/ext/parseTuple.html ...you'll see this: "O" (object) [PyObject *] Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object's reference count is not increased. The pointer stored is not NULL. "O!" (object) [typeobject, PyObject *] Store a Python object in a C object pointer. This is similar to "O", but takes two C arguments: the first is the address of a Python type object, the second is the address of the C variable (of type PyObject *) into which the object pointer is stored. If the Python object does not have the required type, TypeError is raised. Removing the '!' from the PyArg_ParseTuple solved the problem (before it was returning TypeError), and when I ask for item 3 (really 4) I get the following: [d0ora3 ~/work/grid_query/test]$ python hello.py [0, 3, 8, 22, 9] [22] [d0ora3 ~/work/grid_query/test]$ THANKS FOR ALL THE HELP!!! From martin at v.loewis.de Tue Sep 10 14:38:34 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 10 Sep 2002 20:38:34 +0200 Subject: how to build wxPython w/ Sun's C++ compiler? References: <23891c90.0209092359.11acb607@posting.google.com> Message-ID: Skip Montanaro writes: > Agreed. However, disutils commands have this structure: > > python setup.py [ options ] command [ more options ] ... > > which I think can get kind of confusing. You forgot python [ options ] setup.py [ options ] command [ more options ] ... :-) Regards, Martin From loewis at informatik.hu-berlin.de Fri Sep 20 12:57:56 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 20 Sep 2002 18:57:56 +0200 Subject: Porting woes References: <3a4b2539.0209200809.407d50d5@posting.google.com> Message-ID: jstavnitzky at atsautomation.com (Jay) writes: > This failure is occuring during the function classic_mro(). The > stack at that point is > classic_mro(),mro_implementation(),mro_internal(),PyType_Ready(), > PyTypeReady(),Py_ReadyTypes(),Py_Initialize(),Py_Main(). > > Help!! What is happening at this point, and what could be causing this > assertion to fail? It checks whether the cls argument to classic_mro really is a classic class. It is surprising that it calls into classic_mro. Can you tell which line in Py_ReadyTypes comes from? (type, list, string, ...?) None of these are classic classes, so this code should not have been executed. It appears that this was executed because of the test in if (PyType_Check(base)) parentMRO = PySequence_List( ((PyTypeObject*)base)->tp_mro); else parentMRO = classic_mro(base); i.e. base appears not to be a type. This, again, should not happen: base is PyObject *base = PyTuple_GET_ITEM(bases, i); which in turn comes from bases = type->tp_bases; All base types of the types initialized in Py_ReadyTypes have only types as bases, so it is surprising that one of them has a base which is not a type. It would be good to study the value of type, and tp_bases, at this point. It might be that some initialization of global objects has failed to happen, or has happened incorrectly. Regards, Martin From praveen.patil at silver-software.com Wed Sep 4 08:36:16 2002 From: praveen.patil at silver-software.com (Praveen Patil) Date: Wed, 4 Sep 2002 13:36:16 +0100 Subject: Please help in calling python fucntion from 'c' Message-ID: Hi, I have written 'C' dll(MY_DLL.DLL) . I am importing 'C' dll in python file(example.py). I want to call python function from 'c' function. For your reference I have attached 'c' and python files to this mail. In my pc: python code is under the directory D:\test\example.py dll is under the directory C:\Program Files\Python\DLLs\MY_DLL.pyd Here are the steps I am following. step(1): I am calling 'C' function(RECEIVE_FROM_IL_S) from python. This 'C' function is existing imported dll(MY_DLL). step(2): I want to call python function(TestFunction) from 'C' function(RECEIVE_FROM_IL_S). Python code is(example.py) :- ---------------------------- import MY_DLL G_Logfile = None def TestFunction(): G_Logfile = open('Pytestfile.txt', 'w') G_Logfile.write("%s \n"%'I am writing python created text file') G_Logfile.close G_Logfile = None #end def TestFunction if __name__ == "__main__": MY_DLL.RECEIVE_FROM_IL_S(10,50) 'C' code is (MY_DLL.c) :- --------------------- #include #include #include PyObject* _wrap_RECEIVE_FROM_IL_S(PyObject *self, PyObject *args) { FILE* fp; PyObject* _resultobj; int i,j; if( !(PyArg_ParseTuple(args, "ii",&i,&j))) { return NULL; } fp= fopen("RECEIVE_IL_S.txt", "w"); fprintf(fp, "i=%d j=%d" , i,j); fclose(fp); /* Here I want to call python function(TestFunction). Please suggest me some solution*/ _resultobj = Py_None; return _resultobj; } static PyMethodDef MY_DLL_methods[] = { { "RECEIVE_FROM_IL_S", _wrap_RECEIVE_FROM_IL_S, METH_VARARGS }, { NULL , NULL} }; __declspec(dllexport) void __cdecl initMY_DLL(void) { Py_InitModule("MY_DLL",MY_DLL_methods); } Please anybody help me solving the problem. Cheers, Praveen. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: exampl.py URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: MY_DLL.c Type: application/octet-stream Size: 788 bytes Desc: not available URL: -------------- next part -------------- [ The information contained in this e-mail is confidential and is intended for the named recipient only. If you are not the named recipient, please notify us by telephone on +44 (0)1249 442 430 immediately, destroy the message and delete it from your computer. Silver Software has taken every reasonable precaution to ensure that any attachment to this e-mail has been checked for viruses. However, we cannot accept liability for any damage sustained as a result of any such software viruses and advise you to carry out your own virus check before opening any attachment. Furthermore, we do not accept responsibility for any change made to this message after it was sent by the sender.] From marklists at mceahern.com Wed Sep 18 13:24:06 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 18 Sep 2002 12:24:06 -0500 Subject: New RPMs at python.org In-Reply-To: <20020918171900.GB13272@tummy.com> Message-ID: [Sean Reifschneider] > Find them at: > > http://python.org/2.2.1/rpms.html Sean, thanks! Is this a typo in the above? Installs "python2.2" as well as "python2.2". ^^^ ^^^ They are the same, no? // m - From jpmieville at bluewin.ch Wed Sep 18 15:40:47 2002 From: jpmieville at bluewin.ch (Jean-Paul Mi=?ISO-8859-1?B?6Q==?=ville) Date: Wed, 18 Sep 2002 21:40:47 +0200 Subject: Problem with urllib Message-ID: I don't understand why with some URL I have got [Errno 57] Socket is not connected. The code is : import urllib2 page = urllib2.urlopen(' http://www.python.org/doc/NonEnglish.html') print page.read() If I do the same thing with python interactive, I can't reproduce the error. Thanks in advance, Jean-Paul From marco at sferacarta.com Thu Sep 26 18:17:14 2002 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 27 Sep 2002 00:17:14 +0200 Subject: Who knows somefunction? In-Reply-To: <3D9382AF.5070800@aon.at> References: <664e469667.69667664e4@icomcast.net> <3D9382AF.5070800@aon.at> Message-ID: <20020926221714.GA11579@sferacarta.com> On Thu, Sep 26, 2002 at 11:57:03PM +0200, Gregor Lingl wrote: > How did you understand my question? > (Errors should never pass silently) > Gregor Yeah, it's useless and a bad idea. However, let's try: ------------------------------ // Pointer.c #include #include PyObject* pointer(PyObject* self, PyObject* args) { PyObject* p; if (!(PyArg_ParseTuple(args,"l",&p))) return NULL; Py_INCREF(p); return p; } static PyMethodDef pointer_methods[] = { {"pointer", (PyCFunction) pointer, METH_VARARGS, NULL}, {NULL,NULL,0} }; void initpointer(void) { Py_InitModule("pointer", pointer_methods); }; ------------------------------ ## setup.py from distutils.core import setup, Extension module1 = Extension('pointer', sources = ['pointer.c']) setup(name="Pointer", version = "0.1", author = "Anonymous Coward", author_email = "noway at example.com", description = "Blah", ext_modules = [module1] ) ------------------------------ Build with "python setup.py build" Now you can harm yourself. :-) Tested with python 2.2.1 From gerhard.haering at gmx.de Sun Sep 1 21:11:34 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 2 Sep 2002 01:11:34 GMT Subject: curses: AttributeError: initscr References: Message-ID: Cesar wrote in comp.lang.python: > I'm running python 1.5/2.2.1 under redhat linux 7.2. > screen = curses.initscr() > ==> AttributeError: initscr > > any idea ?? The Python curses module is likely packaged in a separate RPM. From cmay4 at yahoo.com Tue Sep 24 15:56:08 2002 From: cmay4 at yahoo.com (Chuck May) Date: Tue, 24 Sep 2002 19:56:08 GMT Subject: Limit number of concurrent threads References: Message-ID: That sounds interesting. I'll try it. I was just hacking a much less elegant way of doing it. Here is what I came up with: from threading import Thread import time, random maxthreads = 5 # maximum number of concurrent threads totalops = 80 # hold total number of operations all = {} # global holding the current running threads class Worker(Thread): global all def __init__(self, id): Thread.__init__(self) self.all = all self.id = id def run(self): time.sleep(random.randint(10, 100) / 1000.0) print "id %d: " % self.id, all.keys() del all[self.id] if __name__ == "__main__": for i in range(totalops): while (len(all) > maxthreads): time.sleep(.1) all[i] = 1 w = Worker(i) w.start() There may be problems with that, but it does seem to work. Syver Enstad wrote in news:uwupbdwnj.fsf at online.no: > Chuck May writes: > >> I've searching for examples that fit my problem, and I haven't found >> any. Most examples I've found look something like this: >> >> threads = [] >> for i in range(number_of_tasks): >> thread.append(thread_for_task) >> >> # let the threads run - just wait for shutdown >> for t in threads: >> t.join() >> >> which whould work fine if I wanted to start all 80 threads at once. >> >> I've read about the Queue, but I'm not sure if it's what I want, and >> I >> >> can't seem to find any good examples on it. > > I think Queue would be nice to use, Have a thread (the main thread > perhaps) feed all the table names (or a table object if you please) > into a Queue. > > Set up some worker threads with access to the Queue > (global variable, member). The worker threads should loop something > like this: > > while 1: > queueItem = self._queue.get() > doSomethingWithQueueItemHere > > Then you can start your workers. > > (You'll have to find out some way to make the workers exit when the > work is done, perhaps putting a number of None's equal to the number > of workers last in the queue and testing for None in the working > thread loop. > > -- Chuck May IMS, Inc. may at ims.nci.nih.gov From oren-py-l at hishome.net Thu Sep 12 10:47:10 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Thu, 12 Sep 2002 10:47:10 -0400 Subject: Coding Style: Quotes In-Reply-To: References: Message-ID: <20020912144710.GA78280@hishome.net> On Thu, Sep 12, 2002 at 02:25:11PM +0000, John Waycott wrote: > I'm curious if others have adopted any standards for choice of single vs. > double quotation marks to delimit strings. A look through the standard > library reveals the choice of one over the other is rather arbitrary. I > suspect it really makes no difference, but the question has come up during a > code review. The default repr of a string uses single quotes unless the string contains a single quote. Most of the time I use the same convention but I'm not 100% consistent. For docstrings I always use triple double-quotes even if the docstring fits in a single line. I use triple single-quotes to comment out blocks of code. This is very useful since "if 0:" would require re-indentation. Oren From thorsten at thorstenkampe.de Wed Sep 18 10:34:33 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 18 Sep 2002 16:34:33 +0200 Subject: Python equivalent to perldoc? References: <%Avh9.7933$Lg2.1392332@news2.news.adelphia.net> Message-ID: * Bob X > "Thorsten Kampe" wrote in message >>> Shouldn't Python know its own libs? >> >> It does: >> ,--- >> | Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 >> | Type "help", "copyright", "credits" or "license" for more information. >> | >>> import pydoc >> | >>> >> `--- > It doesn't...you are executing from with Python...I am trying to do a ViM > script that executes it. So Vim doesn't doesn't know about Python's libs. No surprise. >>> Or at least put the "libs" in the ENV variable? >> >> Windows XP doesn't have a ENV variable. > > Lets see...right click "My Computer"...go to the "Advanced" tab....OH LOOKY > a button that says "Environment Variables". I could have been a wee bit more > specific like...putting the the lib dir in the PATH. It's not reasonable to put $PYTHONPATH in your $PATH, it's vice versa. And the Python executables (python, pydoc, etc.) should be put to where your path is: /bin or /usr/bin or /usr/local/bin. Thorsten From loewis at informatik.hu-berlin.de Thu Sep 12 06:14:04 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 12 Sep 2002 12:14:04 +0200 Subject: ignoring dtd file in sax parser References: <1010a26.0209112251.3efd57f4@posting.google.com> Message-ID: amichail at cse.unsw.edu.au (Amir Michail) writes: > I tried: > > parser.setFeature(feature_namespaces, 0) > parser.setFeature(feature_validation, 0) > > parser.setContentHandler(ph) > > try: > parser.parse(f) > # print "NO PARSE ERRORS" > except xml.sax._exceptions.SAXParseException: > print "XML parse errors in " + fn > > > However, it still complains about not finding the dtd file. You need to install an EntityResolver in the parser; that resolver can then return an empty resource. Regards, Martin From tjreedy at udel.edu Wed Sep 25 10:51:35 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Sep 2002 14:51:35 GMT Subject: Newbie References Question References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> Message-ID: "Guy Rabiller" wrote in message news:3d91c72f$0$8558$79c14f64 at nan-newsreader-02.noos.net... > let say I have: > i1 = 1 > i2 = 2 > and > p = [i1,i2] > > How can I have: > p=[*i1,*i2] > rather than > p=[**i1,**i2] as it is curently ? > > ( Sorry for this nasty hybrid syntax ) > > Textualy, how if I want that p[0] refere to the 'i1' container, and not to > the refererence it contains ? Names, in themselves, are not Python objects and are certainly *not* containers. Once turned into Python string objects, they may be contained within a dictionary and as key, associated with a reference. But they still do not *contain* the reference; the dictionary, not the name, is the container. As a side note but still relevant: as a optimization in CPython at least, local names within a function that are not used within nested scopes are turned into array indexes. They may be tossed after compilation since they serve no further purpose. > What I want is that if now I set: > i1 = 4 > that automaticaly: > p -> [4,2] > and not keeping [1,2] Too bad, since, it should not be clearer, this is not possible. The assignment means: associate 'i1' with [int object with value] 4 after removing any previous association. Terry J. Reedy From david at no.westcontrol.spam.com Fri Sep 27 08:33:43 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Fri, 27 Sep 2002 14:33:43 +0200 Subject: hex numbers?? References: Message-ID: wrote in message news:mailman.1032881550.14068.python-list at python.org... > >>> y=hex(x) > >>> y > '0xa' > >>> type(y) > > > the hex() function put the hexadecimal number in a string type like this '0xa', but the real hexadecimal number of 10 is 'a', why python puts a '0x', and how i can get just the real hexadedcimal number, for example i want to write in a file 10 in hexadecimal, but if i use hex(10) the result is '0xa' as a string, is not the same as 'a'. > > '0xa' != 'a' > > x = [12,13,14] > y = ['0xc', '0xd', '0xe'] > > hex() create a list of string, how i can write in a file just the real value of hexadecimal number? > If you want to do the conversion over a list of numbers, try: map(lambda a : "%x" % a, x) From missive at frontiernet.net Sun Sep 1 16:54:14 2002 From: missive at frontiernet.net (Lee Harr) Date: Sun, 01 Sep 2002 20:54:14 -0000 Subject: Installation of multiple versions of Python on Unix References: Message-ID: In article , Gerhard H?ring wrote: > Lee Harr wrote in comp.lang.python: >> I have a very similar setup on a FreeBSD server (Zope still at 2.4.X tho >> as I have not had a chance to upgrade yet) >> >> I just leave /usr/local/bin/python as a hard link to >> /usr/local/bin/python2.1 and run the other as /usr/local/bin/python2.2 > > Any reason not to use a symbolic link? Any reason to use a hard link > for anything, ever? I never needed one. > Not sure... that is the way the port does it, so I just did the same thing. If it were me I would probably have just used a symlink, but I figured there must be some reason. >> One issue is building ports. > > Erh. Really? <0.8 wink> > >> Whenever I want to build a port to go with 2.2 (like I just added >> twisted python, for instance) I will change the plain python to link >> to python2.2 before I make and make install, then switch it back >> when I am done. That has no impact on the running Zope at all. > > For the ports you want to build, use: > > $ make PYTHON_VERSION=python2.1 > > to use the FreeBSD ports system instead of working around it ;-) > > Look into /usr/ports/Mk/bsd.python.mk for why this works :-) > Thanks. That should be much easier :o) From somebody at nojunk.invalid Mon Sep 30 19:13:13 2002 From: somebody at nojunk.invalid (Russell E. Owen) Date: Mon, 30 Sep 2002 17:13:13 -0600 Subject: [Mac] Editor on Macintosh? References: <1fj7za2.1erbqps1uvzpj8N%news@agapow.net> <300920020926012729%pecora@anvil.nrl.navy.mil> Message-ID: In article <300920020926012729%pecora at anvil.nrl.navy.mil>, "Louis M. Pecora" wrote: >In article , Russell E. Owen > wrote: > >> Python has the Mac IDE is a bit limited (need an extra plug-in even to >> do syntax coloring) > >What Plug-in works for the Python IDE? I know an add-on of some kind used to exist, but I just looked for it and couldn't find it. I've never used it myself so I may just have overlooked it. If you subscribe to the MacPython mailing list I suggest you ask there. -- Russell From cbbrowne at acm.org Fri Sep 27 00:19:58 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 27 Sep 2002 04:19:58 GMT Subject: ANN: Tim Peters' FixedPoint on SourceForge References: Message-ID: "dougfort" wrote: > What would it take to get you to use FixedPoint in a serious application.... > benchmarks? > celebrity endorsements? > sample code? > other? Photo opportunities with spokesmodels! :-) -- (reverse (concatenate 'string "moc.enworbbc@" "sirhc")) http://www.ntlug.org/~cbbrowne/python.html Whatever you do don't mail me at pink-and-wobbly at asdkjlwelkj.com, because then I'll know you're just an address-harvester, and blacklist your IP until the end of time From danb_83 at yahoo.com Thu Sep 19 15:45:47 2002 From: danb_83 at yahoo.com (Dan Bishop) Date: 19 Sep 2002 12:45:47 -0700 Subject: monetary applications (et al) References: Message-ID: terry wrote in message news:... > ... > I do admit to being OO inhibited, so maybe you could take it from this > short piece code and execution results, and, provide a brief > description of what you would put into this money class that would > eliminate this error message, while maintaining the code simplicity. > [code snipped] > ... def _roundToEven(x): if x < 0: return -_round(-x) iPart, fPart = divmod(x, 1.) iPart = int(iPart) if fPart == 0.5: if iPart & 1: return iPart + 1 else: return iPart elif fPart > 0.5: return iPart + 1 else: return iPart class Money(object): def __init__(self, dollars): self.__cents = _roundToEven(dollars * 100) def __repr__(self): return "Money(%0.2f)" % float(self) def __str__(self): return "$%0.2f" % float(self) def __float__(self): return self.__cents / 100. def __pos__(self): return self def __neg__(self): return Money(-float(self)) def __add__(self, other): assert isinstance(other, Money) return Money(float(self) + float(other)) def __sub__(self, other): assert isinstance(other, Money) return Money(float(self) - float(other)) def __mul__(self, other): return Money(float(self) * other) def __div__(self, other): if isinstance(other, Money): return float(self) / float(other) else: return Money(float(self) / other) def __cmp__(self, other): return (self.__cents).__cmp__(other.__cents) def __hash__(self): return hash(float(self)) From chris.gonnerman at newcenturycomputers.net Sun Sep 29 18:59:21 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sun, 29 Sep 2002 17:59:21 -0500 Subject: Graphics library Message-ID: <00af01c2680b$d9fa8c80$ba01010a@local> ----- Original Message ----- From: "David Siroky" > Hi! > > I'd like to know, which library for creating images (like > libgd) is "the best". I want to use it with Python. This is a sore point with me. I am the current maintainer of the Python gdmodule: http://newcenturycomputers.net/projects/gdmodule.html I took it over because I needed to annotate graphic images using TrueType fonts. The PIL (PythonWare Imaging Library) is probably superior otherwise, but the font support stinks. There are two other projects, claimed to be PIL-compatible, one supporting FreeType (TrueType) and the other supporting Postscript Type 1; but when I asked here previously for examples and/or support using either of them I got resounding silence. PIL can be found at: http://www.pythonware.com/products/pil/index.htm The Image-SIG's t1python module is at: http://www.python.org/sigs/image-sig/t1lib/ (Incidentally this may have been updated since I first looked at it, so my complaints here may no longer apply.) Robert Kern's PyFT can be found at: http://starship.python.net/crew/kernr/Projects.html PIL Plus from Pythonware includes TrueType support (I've read) but as a commercial product it was not an option for my project. I looked for the gdmodule, and discovered Richard Jones wasn't supporting it anymore. When I asked about taking it over, he answered "Sure, go ahead." So I did. With help from others I have updated it to support the 2.01 (beta) libgd. There are weaknesses, in particular the terrible JPEG output (rule 1: always use PNG with the gdmodule), but at least all my TTF fonts work. gdmodule also has a very simple interface; I don't have to know as much about an image file to work with it. This may be related to the crummy JPEG output... I dunno. I'd love to see sample code to render either type of fonts via PIL and one or more of the above libraries. In fact, it seems like an ideal thing for a HOWTO or some such. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From cstrong at arielpartners.com Wed Sep 25 23:02:40 2002 From: cstrong at arielpartners.com (Craeg K Strong) Date: Wed, 25 Sep 2002 23:02:40 -0400 Subject: Is there a way to find the name of the method currently being executed? Message-ID: <3D9278D0.9060307@arielpartners.com> Hello: class a: def func1(self): print "func1 being called" def func2(self): print "func2 being called" In the code sample above, I would like to replace the "func1" and "func2" strings with constants so the same code could be copied verbatim into multiple functions and do the right thing. Is there a way to do this in Python? For example, maybe you could get your hands on the call stack and print out stack[0].__name__ or something.... Thanks in advance, --Craeg BTW, I could not find this in the python.org FAQ.... From keith_oconnell at blueyonder.co.uk Thu Sep 19 13:45:08 2002 From: keith_oconnell at blueyonder.co.uk (Keith O'Connell) Date: Thu, 19 Sep 2002 17:45:08 GMT Subject: finding last match in a file References: Message-ID: <87r8fplvq4.fsf@smtp.blueyonder.co.uk> Dag writes: > I have a number of very large files where I have to find the last line > which matches a certain experssion. Currently I'm simply opening the > file and looping through it noteing each time a line matches and at the > end of the loop I see which was the last match. However this is very > slow and inefficient. Is there some way to read through the file > backwards and simply find first match starting from the end of the file. > The files are really too big to read the entire thing into memory. Would you not be able to use grep with the "-n" option. It will list all your matches with the lines numbered so you can see the last match having the highest line number. If you then use wc on the file you will get the total number of lines. Take one from the other and you can see how far from the end your last match is. That seems to easy - Have I misunderstood you question? Keith. -- ___________________________________ _ Keith O'Connell. -o) Maidstone, Kent. (UK) /\\ keith_oconnell at blueyonder.co.uk _\_v From timr at probo.com Fri Sep 20 00:19:29 2002 From: timr at probo.com (Tim Roberts) Date: Thu, 19 Sep 2002 21:19:29 -0700 Subject: Destructor never called ??? References: <76710511.0209111450.40999dd8@posting.google.com> Message-ID: <4e8lou018f9uosl5p9mb0tt6691mfivamj@4ax.com> aahz at pythoncraft.com (Aahz) wrote: >In article , >Tim Roberts wrote: >> >>However, Python is a garbage-collected system. Unlike in COM, an object is >>NOT destroyed as soon as its reference count goes to 0. Your object will >>only be destroyed if the garbage collector happens to run, and decides that >>it might be a convenient time to actually free up the space your object >>occupies. > >Wrong. CPython uses reference counting backed by GC. Well, then, what was all the fuss about deterministic desctructors in the newsgroup last year or so? Has this changed, or am I just remembering this entirely wrong? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From LogiplexSoftware at earthlink.net Fri Sep 6 15:07:34 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 06 Sep 2002 12:07:34 -0700 Subject: Soviet/Russian military In-Reply-To: <3D66BF07.852B6858@worldnet.att.net> References: <3D66A072.75F7E2B2@worldnet.att.net> <3D66BF07.852B6858@worldnet.att.net> Message-ID: <1031339254.19985.2630.camel@software1.logiplex.internal> On Fri, 2002-08-23 at 16:03, Peter Koren wrote: > Peter Koren wrote: > > > > Dan, > > > > I ran across a discussion of the Soviet/Russian military. It is > > attached. > > > > Love, > > > > Dad > > Gasp, apologies offered. I addressed this to my son, but this news group > was selected in Mozilla so it got posted. Even worse, you forgot to attach the article. > Sorry, > > Pete Koren > -- > http://mail.python.org/mailman/listinfo/python-list -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From tim.one at comcast.net Sat Sep 7 13:11:10 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 07 Sep 2002 13:11:10 -0400 Subject: None or 0 In-Reply-To: Message-ID: [Michael Str?der] > I'm using the idiom > > a = a or b > > to get rid of statements like > > if a is None: > a = b That's fine, although you may get burned someday if 'a' has an interesting value that's not None but happens to evaluate as false. Like, e.g., def eat(number_of_pounds=None): # Default to 1 pound. to_eat = number_of_pounds or 1 ... If you're not hungry and try to do eat(0), you're in for a treat. As a rule of thumb, whenever you use None to mean "not there", you'll cut bugs by testing for "is None" or "is not None" explicitly. I've seen many subtle bugs as a result of not doing this; sometimes code works fine for years, and then someone happens to add a __len__ method to an object's class, and "all of a sudden" evaluating to false no longer means a var is still bound to None, but that it may also be bound to a non-None object that suddenly decided to call itself empty. > Now I wonder what happens if both a and b have zero-length values. If A evaluates to false, 'A or B' returns B without testing B (so it doesn't matter whether B does or doesn't evaluate to false -- B is simply evaluated and returned then). > Trying in Python 2.2.1 reveals: > > >>> repr(0 or None) > 'None' > >>> repr(None or 0) > '0' > >>> repr('' or None) > 'None' > >>> repr(None or '') > "''" > >>> > > Is it guaranteed to work like this Yes. Similarly, 'A and B' returns B untested whenever A evaluates to true. A or B same-as if A then A else B A and B same-as if A then B else A B is never tested for true/false, and in the cases where A is the result the B expression isn't even evaluated. > or should that be avoided? That's really a different question . From itamar at itamarst.org Fri Sep 27 21:16:35 2002 From: itamar at itamarst.org (Itamar Shtull-Trauring) Date: Fri, 27 Sep 2002 21:16:35 -0400 Subject: ANN: Twisted 0.99.2 - now with stable internet Message-ID: <20020927211635.327e6494.itamar@itamarst.org> The Twisted team is proud to announce Twisted 0.99.2, which includes a API-stable version of twisted.internet, Twisted's event-driven networking core (like asyncore, but more so). Twisted's twisted.internet pacakge provides: - event-driven TCP, SSL and unix socket networking - cross-platform (Unix and Win32) support - pluggable reactors, including select(), poll() and Kqueue - event loop GUI integration, for Win32, GTK+, Qt, wxPython and Tkinter - threading integration - scheduling - process running API With the twisted.internet APIs now stable, we feel Twisted provides the best networking platform available today for Python. This also gives us a solid basis for working on stable APIs for the rest of Twisted's packages. Download it now from http://www.twistedmatrix.com, or visit us on IRC on #twisted (irc.freenode.net servers, formerly known as openprojects). What is Twisted? ================ Twisted is an event-based framework for internet applications. It includes a web server, a telnet server, a chat server, a news server, a generic client and server for remote object access, and APIs for creating new protocols and services. Twisted supports integration of the Tk, GTK+, Qt or wxPython event loop with its main event loop. The Win32 event loop is also supported, as is basic support for running servers on top of Jython. Twisted works with Python 2.1 and Python 2.2. Twisted even supports the CVS versions of Python, so it is ready for Python 2.3. Twisted currently supports the following protocols, all implemented in pure python, most of them as both servers and clients: - FTP - HTTP - NNTP - SOCKSv4 (server only) - SMTP - IRC - telnet - POP3 - AOL's instant messaging TOC - OSCAR, used by AOL-IM as well as ICQ (client only) - DNS - MouseMan - finger - Echo, discard, chargen and friends - Twisted Perspective Broker, a remote object protocol - XML-RPC For more information, visit http://www.twistedmatrix.com, or join the list at http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python What's new in 0.99.2 ==================== - Improved HTTP support - bug fixes, caching APIs - WOVEN, a web templating system (formerly known as DOMTemplate) - microdom, a very small DOM implementation - An inetd server written with Twisted (coming soon to a Debian mirror near you) - Switched to epydoc for API docs (http://epydoc.sf.net - it rocks!) - RDBMS storage for the NNTP server, and improved NNTP protocol support - Finalized process-running API - Huge numbers of bug fixes and feature improvements, and better docs From vtail at yandex.ru Mon Sep 9 09:57:29 2002 From: vtail at yandex.ru (vtail) Date: 9 Sep 2002 06:57:29 -0700 Subject: Possible bug in WxPython Message-ID: <9ff6b66.0209090557.3c0e3c94@posting.google.com> Greetings. When trying to run an example program from wxWiKi http://wiki.wxpython.org/index.cgi/Getting_20Started, section 7.1.2, I encounter following error. Could someone please explain it to me? My python version is Python 2.2.1c2 (#33, Mar 26 2002, 13:04:18) [MSC 32 bit (Intel)] on win32, my wxpython version is 2.3.2.1 (from c:/Python22/Lib/site-packages/wxPython/__version__.py) I've attached the error message and the program that causes it. Thanks for your help, Vtail. ====> O:\_PUBLIC\Newdbase\Python\wxPython>python test4.pyw > aaa.txt 17:52:59: Debug: c:\Projects\wx\src\msw\app.cpp(542): 'UnregisterClass(no redraw canvas)' failed with error 0x00000584 (class still has open windows.). 17:52:59: There were memory leaks. 17:52:59: ----- Memory dump ----- 17:52:59: wxFrame at $FF8890, size 332 17:52:59: wxTextCtrl at $115EAA8, size 316 17:52:59: wxStatusBar at $778C38, size 260 17:52:59: wxMenu at $10D3AB0, size 112 17:52:59: wxMenuItem at $F9CE50, size 124 17:52:59: wxMenuItem at $F9CF08, size 124 17:52:59: wxMenuItem at $F9CFC0, size 124 17:52:59: wxMenuItem at $F9D078, size 124 17:52:59: wxMenuItem at $F9D130, size 124 17:52:59: wxMenuBar at $F8FD88, size 312 17:52:59: wxPyCallback at $F81C40, size 12 17:52:59: wxObject at $85DC50, size 28 17:52:59: wxPyCallback at $F81830, size 12 17:52:59: wxPyCallback at $F82638, size 12 17:52:59: wxBoxSizer at $F8FF98, size 96 17:52:59: wxButton at $F85128, size 264 17:52:59: wxSizerItem at $F7F998, size 60 17:52:59: wxButton at $10601A0, size 264 17:52:59: wxSizerItem at $F903A0, size 60 17:52:59: wxButton at $F90418, size 264 17:52:59: wxSizerItem at $F906D8, size 60 17:52:59: wxButton at $F90750, size 264 17:52:59: wxSizerItem at $F90A10, size 60 17:52:59: wxButton at $F82B08, size 264 17:52:59: wxSizerItem at $F82CE8, size 60 17:52:59: wxButton at $F82D60, size 264 17:52:59: wxSizerItem at $F82FF8, size 60 17:52:59: wxBoxSizer at $F83070, size 96 17:52:59: wxSizerItem at $F831A0, size 60 17:52:59: wxSizerItem at $F83218, size 60 17:52:59: 17:52:59: 17:52:59: ----- Memory statistics ----- 17:52:59: 8 objects of class wxSizerItem, total size 480 17:52:59: 6 objects of class wxButton, total size 1584 17:52:59: 2 objects of class wxBoxSizer, total size 192 17:52:59: 1 objects of class wxObject, total size 28 17:52:59: 3 objects of class wxPyCallback, total size 36 17:52:59: 1 objects of class wxMenuBar, total size 312 17:52:59: 5 objects of class wxMenuItem, total size 620 17:52:59: 1 objects of class wxMenu, total size 112 17:52:59: 1 objects of class wxStatusBar, total size 260 17:52:59: 1 objects of class wxTextCtrl, total size 316 17:52:59: 1 objects of class wxFrame, total size 332 17:52:59: 17:52:59: Number of object items: 30 17:52:59: Number of non-object items: 0 17:52:59: Total allocated size: 4272 17:52:59: 17:52:59: <==== ====> test4.pyw from wxPython.wx import * import os ID_ABOUT=101 ID_OPEN=102 ID_BUTTON1=110 ID_EXIT=200 class MainWindow(wxFrame): def __init__(self,parent,id,title): self.dirname='' wxFrame.__init__(self,parent,-4, title, style=wxDEFAULT_FRAME_STYLE| wxNO_FULL_REPAINT_ON_RESIZE) self.control = wxTextCtrl(self, 1, style=wxTE_MULTILINE) self.CreateStatusBar() # A Statusbar in the bottom of the window # Setting up the menu. filemenu= wxMenu() filemenu.Append(ID_OPEN, "&Open"," Open a file to edit") filemenu.AppendSeparator() filemenu.Append(ID_ABOUT, "&About"," Information about this program") filemenu.AppendSeparator() filemenu.Append(ID_EXIT,"E&xit"," Terminate the program") # Creating the menubar. menuBar = wxMenuBar() menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.OnExit) EVT_MENU(self, ID_OPEN, self.OnOpen) self.sizer2 = wxBoxSizer(wxHORIZONTAL) self.buttons=[] for i in range(0,6): self.buttons.append(wxButton(self, ID_BUTTON1+i, "Button &"+`i`)) self.sizer2.Add(self.buttons[i],1,wxEXPAND) # Use some sizers to see layout options self.sizer=wxBoxSizer(wxVERTICAL) self.sizer.Add(self.control,1,wxEXPAND) self.sizer.Add(self.sizer2,0,wxEXPAND) #Layout sizers self.SetSizer(self.sizer) self.SetAutoLayout(1) self.sizer.Fit(self) self.Show(1) def OnAbout(self,e): d= wxMessageDialog( self, " A sample editor \n" " in wxPython","About Sample Editor", wxOK) # Create a message dialog box d.ShowModal() # Shows it d.Destroy() # finally destroy it when finished. def OnExit(self,e): self.Close(true) # Close the frame. def OnOpen(self,e): """ Open a file""" dlg = wxFileDialog(self, "Choose a file", self.dirname, "", "*.*", wxOPEN) if dlg.ShowModal() == wxID_OK: self.filename=dlg.GetFilename() self.dirname=dlg.GetDirectory() f=open(os.path.join(self.dirname, self.filename),'r') self.control.SetValue(f.read()) f.close() dlg.Destroy() app = wxPySimpleApp() frame = MainWindow(None, -1, "Sample editor") frame.Show(1) <==== From peter at engcorp.com Mon Sep 2 11:57:26 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Sep 2002 11:57:26 -0400 Subject: Must have Python modules? References: <_THc9.42153$vY2.1039887@e3500-atl2.usenetserver.com> Message-ID: <3D738A66.9D78F20D@engcorp.com> "Martin v. L?wis" wrote: > > "Robert Oschler" writes: > > > In C++, which has thousands of libraries, snippets, etc. there were only a > > few that I personally used religiously. > [...] > So if your question includes standard library modules as well: my > absolutely must-have module is "os", followed by "sys". I've written programs that need "sys" but not "os" more often than the other way around(*). "sys" ROOLZ! :-) * By "the other way around", I mean "more often than I write those with only 'os'", not "more often than those programs write me". -too-early-on-a-long-weekend-to-be-serious-ly yr's, Peter From marklists at mceahern.com Tue Sep 10 16:11:25 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 10 Sep 2002 15:11:25 -0500 Subject: "str"(expr)"str" interpolation syntax In-Reply-To: Message-ID: > I was searching for a new interpolation syntax ... You might be interested to: 1. Checkout the PEPs for string interpolation and simple string substitution. 2. Read this thread: http://groups.google.com/groups?selm=ouit4e63fr.fsf%40andlx-anamika.cisco.co m 3. Read the archives from Python-Dev regarding the relevant PEPs. After you do all that, you may reconsider or reframe your suggestion in light of what has been discussed. Or not. Cheers, // m - From marco at reimeika.ca Sat Sep 21 23:34:55 2002 From: marco at reimeika.ca (marco) Date: 21 Sep 2002 23:34:55 -0400 Subject: "time" module under AIX? Message-ID: Hi, I've just compiled python 2.2.1 under AIX and all seemed to go well. However, I'm having some trouble importing a few modules such as "time" and "math" e.g. coxeter% python2 23:11 Python 2.2.1 (#1, Sep 21 2002, 22:32:45) [C] on aix4 Type "help", "copyright", "credits" or "license" for more information. >>> import time Traceback (most recent call last): File "", line 1, in ? ImportError: No module named time >>> Other modules import fine. Compilation appeared to go well, for example: building 'time' extension cc_r -DNDEBUG -O -I. -I/usr/local/src2/marco/Python-2.2.1/./Include -I/usr/local /include -IInclude/ -c /usr/local/src2/marco/Python-2.2.1/Modules/timemodule.c - o build/temp.aix-4.3-2.2/timemodule.o ./Modules/ld_so_aix cc_r -bI:Modules/python.exp build/temp.aix-4.3-2.2/timemodul e.o -L/usr/local/lib -lm -o build/lib.aix-4.3-2.2/time.so building 'operator' extension etc... Any ideas? I'm using AIX 4.3. Thanks! -- marco at reimeika.ca Gunnm: Broken Angel http://reimeika.ca/ From gua81 at XXXyahoo.com Tue Sep 24 20:46:15 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Wed, 25 Sep 2002 10:46:15 +1000 Subject: Strange python and cgi! References: <3D9101AC.842F0513@alcyone.com> Message-ID: what kind of error am I expecting here? .... errrrrrr I don't know how to access the web server error log. > It's likely some other error occurred. Check your Web server error log > for the final word. > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ > __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE > / \ As far as I'm concerned, being any gender is a drag. > \__/ Patti Smith > Kepler's laws / http://www.alcyone.com/max/physics/kepler/ > A proof of Kepler's laws. From quiteblack at yahoo.com Sun Sep 15 23:58:59 2002 From: quiteblack at yahoo.com (black) Date: 15 Sep 2002 20:58:59 -0700 Subject: couldnt find __dic__ Message-ID: <7153651c.0209151958.4099ac3e@posting.google.com> my book told me all dictionaries have __dic__ method but I searched each dictionaries and find nothing, where is it ??? From sadams123 at optushome.com.au Mon Sep 16 21:31:06 2002 From: sadams123 at optushome.com.au (Steven) Date: Tue, 17 Sep 2002 11:31:06 +1000 Subject: wincerapi Message-ID: <3d8685da$0$23169$afc38c87@news.optusnet.com.au> For anyone who needs to get wincerapi up and running on Python 2.2 I've put the necessary dlls and stuff up for download: http://www.tetrica.com/quickdry/wincerapi.zip I've only tried it out on my home machine Python 2.2, XP Pro, so your mileage may vary, but I figured since not everyone has a compiler, and there doesn't seem to be any other way to get wincerapi working... Steven From peter at engcorp.com Mon Sep 2 12:05:08 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Sep 2002 12:05:08 -0400 Subject: Keyerror problem References: <_lyc9.7164$7N.29584@newsfep3-gui.server.ntli.net> <0cFc9.1718$yB6.25319@newsfep1-gui.server.ntli.net> Message-ID: <3D738C34.4E99461B@engcorp.com> davbucko wrote: > > Thanks! I wasn't too sure about what the backticks meant, but I thought > that they might be necessary. Oh well Sounds like a good time to use the interactive prompt to test out the code before/as you write it. Typing name and `name` would quickly show you what the difference was... -Peter From bdesth at nospam.free.fr Sun Sep 8 21:56:07 2002 From: bdesth at nospam.free.fr (laotseu) Date: Sun, 08 Sep 2002 21:56:07 -0400 Subject: Larry Wall's comment on python... References: Message-ID: <3D7BFFB7.4050906@nospam.free.fr> brueckd at tbye.com wrote: > On 6 Sep 2002, Rod Stephenson wrote: > > >>"Python is cool to look at small bits of, but I think the "outline" >>syntax breaks down with larger chunks of code. I'm with Aristotle on >>the structure of discourse--a story should have a beginning, and >>middle, and an end. So should blocks" >> >>I'm not quite sure what he's trying to get at here - I guess that for >>a long heavily indented chunk of code, you could lose track of the >>overall structure, but I don't write code this way. >> >>Any comments? > > > The very idea of Larry Wall lecturing on code readability is hilarious. > > -Dave > > C'mon, if he is able to read Perl code, he surely can say something about readability !-) laotseu From LogiplexSoftware at earthlink.net Mon Sep 16 15:30:31 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 16 Sep 2002 12:30:31 -0700 Subject: IDLE In-Reply-To: References: <3D7D4F84.318CDB0F@bellatlantic.net> Message-ID: <1032204632.17116.249.camel@software1.logiplex.internal> On Mon, 2002-09-16 at 10:43, Thorsten Kampe wrote: > > "Hardware: 386 enhanced, 75MHz, 32MB RAM." This can't be correct. The 386 never hit 75MHz. I'm guessing you're reading what Windows (3.x ?) reports in it's hardware settings which only tells you whether it's running in "386 Enhanced" or "Standard" mode. The actual CPU is either an AMD/Cyrix 486 clone or an early Pentium. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From marklists at mceahern.com Fri Sep 6 18:58:39 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 6 Sep 2002 17:58:39 -0500 Subject: Larry Wall's comment on python... In-Reply-To: <200209062258.g86MwvVm096127@mail.hcsmail.com> Message-ID: [mmaddox at hcsmail.com [mailto:mmaddox at hcsmail.com]] > Of course it does. I need a parser that can decipher the pure randomness > of my own code. Basically, I'd like to run an SHA-512 algorithm against a > poorly-typed text file describing my program. Then, I'd just compile the > message digest. > > Of course, most of my current code has one big block, main(), and I just > cut-and-paste the rest. Your message brought me smiles, tears, and laughter--I haven't had that much fun since watching Heehaw. Cheers, // m - From read-the-signature at send-spam-to-dev-null.com Thu Sep 5 07:20:45 2002 From: read-the-signature at send-spam-to-dev-null.com (read-the-signature at send-spam-to-dev-null.com) Date: Thu, 5 Sep 2002 11:20:45 +0000 (UTC) Subject: newbie problem: use socke lib to retrieve one web page: References: Message-ID: koko wrote: > I write this to retrieve one web page using socket lib. > [snip: code] > s.connect((HOST,PORT)) > s.send(m) > data=s.recv(4096) > print data > s.close() > > ----------- > But I retrieved nothing and the program stuck. Your code probably is _too quick_ for the server. That is, you tried to read data while the server was still busy processing. You could "sleep" a little, before reading. Oh yeah, are you sure that data = s.recv(4096) will _always_ give you all of the data? You might want to take a look at asyncore [1] which provides a nicer way to handle these situations. I'm not sure, but I expect that the Python cookbook [2] also has some interesting things to say about this topic. Good luck! Bas [1] http://www.python.org/doc/current/lib/module-asyncore.html [2] http://aspn.activestate.com/ASPN/Python/Cookbook/ -- b a s {dot} v a n g i l s {at} c s {dot} k u n {dot} n l BOFH excuse #63: not properly grounded, please bury computer From gerhard.haering at gmx.de Sun Sep 22 06:46:41 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 22 Sep 2002 12:46:41 +0200 Subject: Python HTTPSConnection/HTTPResponse Problem In-Reply-To: <9abedeb.0209212200.5c669a50@posting.google.com> References: <9abedeb.0209212200.5c669a50@posting.google.com> Message-ID: <20020922104641.GB3780@lilith.ghaering.test> * Edward Muller [2002-09-21 23:00 -0700]: > I am trying to use HTTPSConnection and HTTPResponse objects [...] Is your Python SSL-enabled? Check with: import socket hasattr(socket, "ssl") Which version of Python are you using? Be sure to use at least version 2.2, as it contains many SSL-related bugfixes. -- Gerhard From loewis at informatik.hu-berlin.de Mon Sep 23 09:22:31 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 23 Sep 2002 15:22:31 +0200 Subject: Python Compiling References: Message-ID: Jacek Generowicz writes: > How would you reconcile the above statements in context of Common Lisp > compilers ? It all depends on the programming language. I would, of course, expect that a C compiler gives a performance improvement over a C interpreter significant enough to make using C compilers worthwhile. Results from one language don't transfer to another. I don't know (really) why Lisp compilers work that well, and what restrictions on the Lisp language had to be made to make them work well. In general, many of the type inference mechanisms done by lisp compilers don't apply to Python. Regards, Martin From steve at ferg.org Wed Sep 11 10:16:20 2002 From: steve at ferg.org (Stephen Ferg) Date: 11 Sep 2002 07:16:20 -0700 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> Message-ID: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > (what Joseph was doing was binding the button to the event, > e.g. mybutton.bind("", afunction)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ That example was mine. It was based on the discussion in John Grayson's book (p. 108), where Grayson says that (for mouse-button events) binding the action to has the same effect as binding using "command". But it seems that really is incorrect. On http://www.tcl.tk/man/tcl8.4/TkCmd/button.htm#M6 it says that the "command is typically invoked when mouse button 1 is released over the button window." So it looks like the correct mouse-button binding to replace "command" would be to bind to . But it sounds like you are saying that even binding to is not standard behavior ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Alas, too true. Button-1 fires when the mouse button is pressed (very nonstandard behavior) and ButtonRelease fires when the mouse button is released even if the mouse is no longer over the Button object. I don't know of any event binding that does a proper job of emulating the standard behavior of pressing a button. Button(command=...) is the way to go for this. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ What is the standard behavior? Not ? Is there any place where definitions or explanations or discussions of standard button behavior are written down and available? A book? A Web page? Do you know if "command" (at least for mouse-button behavior, ignoring its response to keypresses) does anything other than simply respond to ? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Actually, I use a minor variant ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Thanks. This is useful information. Also mucho thanks for something else. I looked at your SUMMARY about a month ago and on your recommendation I picked up a copy of Brent Welch's "Practical Programming in Tcl and Tk". It has been immensely helpful. A good tip! :-) From max at alcyone.com Wed Sep 25 23:53:51 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 25 Sep 2002 20:53:51 -0700 Subject: a python puzzle References: Message-ID: <3D9284CF.2B1161F2@alcyone.com> Lulu of the Lotus-Eaters wrote: > I think the various responders did this "by hand." Probably having > the > Python source code made it even easier to just eyeball. In a more > general sense (just in case anyone doesn't know), the way to solve a > Caesar cipher like this is to start counting letter frequencies. > Comparing the frequencies to well-known English letter frequencies > like: > > http://gnosis.cx/download/letterfrequency.gif > > lets you start matching letters pretty quickly. Of course, if you > don't > know it's English, the frequency table isn't as accurate. This wouldn't have worked as well here, since the encrypted text was so short; furthermore, the fact that it was mostly Python code would have likely skewed the letter frequencies, since Python keywords, modules, and builtin names appear more frequently in Python code than general user-chosen identifiers; the letter frequency of the code would be biased against the letter frequency of the common "words" in Python, which is likely to be somewhat different from English as a whole. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Gods are born and die, but the atom endures. \__/ Alexander Chase Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From amk at amk.ca Tue Sep 10 16:36:16 2002 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 10 Sep 2002 20:36:16 -0000 Subject: Python iCalendar API? References: Message-ID: In article , Gerhard H?ring wrote: > Looks like there is: > http://webcvs.kde.org/cgi-bin/cvsweb.cgi/kdepim/libical/src/python/ This seems to be a copy of the libical library; its official home page is at http://softwarestudio.org/libical/ . --amk From Dick.Zantow at lexisnexis.com Mon Sep 9 09:18:58 2002 From: Dick.Zantow at lexisnexis.com (rzed) Date: Mon, 9 Sep 2002 09:18:58 -0400 Subject: Grumble about too strict an attitude about backward compatibility... References: Message-ID: "Pearu Peterson" wrote in message news:mailman.1031563647.10076.python-list at python.org... > > On 4 Sep 2002, Skip Montanaro wrote: > > > > > I don't want to wake any sleeping dogs, however, as I'm sitting here > > watching a bunch of Fortran function names fly by as SciPy builds, I'm > > reminded of the fairly recent threads about backward compatibility, > > Python-in-a-tie, etc. Here I am compiling with a Fortran 90/95 compiler > > (Sun's Forte thing-a-ma-bob) and see function names like > > > > lpni: > > klvna: > > chgubi: > > cyzo: > > klvnb: > > rmn2so: > > csphik: > > > > spew forth. So, while it's great that this same large library compiles and > > runs on compilers back to at least Fortran 77 (and probably earlier), > > programmers are still stuck with the same cryptic function and data names > > they had to deal with 30+ years ago, all in the name of backward > > compatibility. > > I don't think that its is due to the backward compatibility. > There is huge amount of Fortran 77 code available and if one wants to fix > the cryptic names of functions to something more meaningful, then one has > to switch to newer Fortran standard (that allows longer names) and edit > huge amount of F77 code. I think nobody is willing to take this task due > to enormous amount of work (and it cannot be fully automated, some > brain has to deside what are meaningful names), the backward compatibility > is a secondary issue (if an issue at all). > > > What's the Python connection? Other than a reminder not to get to slavish > > about backward compatibility, I note that these same function names will > > then go on to pollute the Python namespace because all this Fortran code is > > automatically wrapped using f2py. > > The Fortran function names, that you refer to, are visible only in the > extension modules that are wrapping these functions (this is due to how > Python imports shared modules). All functions that f2py generates, > have the f2py_ prefix to avoid name collision with names from Python > or any other library. > So, I don't understand your argument about name pollution. > > And btw, f2py supports mapping function names so that wrapping a Fortran > function with a name `tiarcf' can be accessed in Python side as > `this_is_a_really_cool_function', for example. > > Pearu > > From lpgray at UOP.com Wed Sep 18 16:35:59 2002 From: lpgray at UOP.com (Gray, Lee P.) Date: Wed, 18 Sep 2002 15:35:59 -0500 Subject: Python GUI app to impress the boss? Message-ID: <1181DE2559EBD1118EF000805F57FC9C0426B22B@shvmail1> (Sorry for the screwed up quoting... I have to use Outlook at work. :( ) > From: Christian Tismer [SMTP:tismer at tismer.com] > Sent: September 18, 2002 3:14 PM > To: Lee Gray > Cc: python-list at python.org > Subject: Re: Python GUI app to impress the boss? > > Boa is in fact quite a bit alpha-ish, but after you're > used to the quirks and limitations, it is really great. > Also note that you should use the version from CVS > which is *far* more developed than the downloadable. > > I've written a quite big wizard for 3D image processing > with wxPython, PIL, Stackless. If you like, I can prepare > some screen shots. > [Gray, Lee P.] --------------- Yeah, I tried to download from CVS, but being a complete noob couldn't figure out how, short of tracking down and copying and pasting every updated file. Any tips would be appreciated. Yes, I'd definitely like to see your screenshots. Thanks, Lee From wlfraed at ix.netcom.com Thu Sep 26 03:48:45 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 26 Sep 2002 00:48:45 -0700 Subject: combining mailbox and email modules References: Message-ID: Bob Horvath fed this fish to the penguins on Wednesday 25 September 2002 11:14 pm: > ... and here it the message... > > From mickey at verizon.net Tue Aug 20 10:03:52 2002 > Return-Path: > Delivered-To: bob at horvath.com Is that indent on the "From ..." line really in the file, or just some artifact of pasting it into your post? I just checked my Eudora .mbx files and they don't show an indent on the "From ..." line If it /is/ in the file, that could be the bad line. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From mgarcia at cole-switches.com Wed Sep 18 20:37:18 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: 18 Sep 2002 17:37:18 -0700 Subject: isFloat: Without Exception-Handling References: Message-ID: sismex01 at hebmex.com wrote in message news:... > def isFloat(S): > R = 0 > try: > float(S) > R = 1 > finally: > return R slightly shorter way: def isFloat(x): try: float(x) return 1 except: return 0 def test_print(a): print '%s -> %r' %(a,eval(a)) test_print('isFloat(1)') test_print('isFloat(1.1)') test_print('isFloat("1")') test_print('isFloat("1.1")') test_print('isFloat("a")') test_print('isFloat( [] )') test_print('isFloat( () )') test_print('isFloat( {} )') From thorsten at thorstenkampe.de Sat Sep 14 04:28:30 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 14 Sep 2002 10:28:30 +0200 Subject: Coding Style: Quotes References: Message-ID: * Michael Stenner > On Fri, Sep 13, 2002 at 10:05:45PM +0200, Thorsten Kampe wrote: >> * John Waycott >>> I'm curious if others have adopted any standards for choice of single vs. >>> double quotation marks to delimit strings. A look through the standard >>> library reveals the choice of one over the other is rather arbitrary. I >>> suspect it really makes no difference, but the question has come up during a >>> code review. >> >> Python itself seems to "prefer" single quotes slightly: >> 1: >>> "String" >> 1: 'String' >> 2: >>> > > Just because it uses the single quote doesn't mean it prefers it. It > (or the authors, rather) had to choose. They couldn't just not pick > one. Also, the method you use to input the string IS NOT part of the > string, and so should be dropped after it's role (encoding the string) > is complete. Therefore, your example does not support your statement. > > Of course, I suspect it is for just this reason that you quoted > "prefer". :) The Python interpreter has it's own preferences of outputting/printing objects. So the question "'" versus """ is just a part of a wider discussion. I asked myself the same question when I started four weeks ago. How to put spaces, commas, string delimiter, indent etc.? Instead of doing it my way, I decided to do it the Python way for sake of readability of my code. 1: >>> 1 1: 1 2: >>> { } 2: {} 3: >>> [ 1 , 2 ] 3: [1, 2] Thorsten From op73418 at mail.telepac.pt Fri Sep 6 09:58:55 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Fri, 06 Sep 2002 14:58:55 +0100 Subject: Difference between static method and a function as a class attribute? Message-ID: Hi, What are the differences, if any, between 1 and 2? 1. def funtest(*args): pass class test(object): method = funtest 2. class test(object): def funtest(*args): pass method = staticmethod(funtest) And if there are any differences do they really matter, that is, does anybody has any test cases where 1 and 2 are not interchangeable? TIA and all the best, Gon?alo Rodrigues From pete at shinners.org Sat Sep 28 15:17:48 2002 From: pete at shinners.org (Pete Shinners) Date: Sat, 28 Sep 2002 19:17:48 GMT Subject: pygame.event.Event? References: Message-ID: In article , Max wrote: >I can't generate a QUIT event in pygame: >pygame.event.Event(type, dict, [keyword_args]) -> Event > >What do I have to put in "dict"? i should fix the docs up a little on that. the dictionary argument is optional. it is a way to add any extra attributes to the event. the QUIT event doesn't really have any attributes. you can ignore the argument. also, an easier way to handle the extra attributes is with keyword argument handling. "my_quit = pygame.event.Event(QUIT, fake=1)", and your program could easily later determine if this was a "real" quit event or not. From maxm at mxm.dk Thu Sep 12 12:52:59 2002 From: maxm at mxm.dk (Max M) Date: Thu, 12 Sep 2002 18:52:59 +0200 Subject: Coding Style: Quotes References: Message-ID: <3D80C66B.5020206@mxm.dk> Michael Stenner wrote: > On Thu, Sep 12, 2002 at 02:25:11PM +0000, John Waycott wrote: > >>I'm curious if others have adopted any standards for choice of single vs. >>double quotation marks to delimit strings. A look through the standard >>library reveals the choice of one over the other is rather arbitrary. I >>suspect it really makes no difference, but the question has come up during a >>code review. > > > Since there is no "physical" difference between them, I can't imagine > why it would matter. The only reason there "needs" to be two is for > nested quoting. Sure, it would be annoying to alternate for each > string, but beyond that... It makes about as much sense to standardize the use of double and single quoting in Python as it does do try and genreate personal email adresses in a company from some kind of systematic approach. There will allways be reasons to break the system. Personally I use single quotes as much as possible because it is a direct key on may Danish keyboard. To double quote I have to press shift+2. :-/ regards Max M From ralf_ahlbrink at web.de Sat Sep 21 12:17:21 2002 From: ralf_ahlbrink at web.de (RA) Date: Sat, 21 Sep 2002 18:17:21 +0200 Subject: PyQt setup on Linux Mandrake 8.2 References: <3D8B4898.20808@nospam.attbi.com> Message-ID: <3d8c9b92$0$182$9b622d9e@news.freenet.de> On Sat, 21 Sep 2002 03:59:41 +0000, Armin Steinhoff wrote: > dwelch wrote in message news:<3D8B4898.20808 at nospam.attbi.com>... [Snip] > > I would suggest to dowload the latest version of Qt from the Trolltech > homepage, just for a simple and clean recompilation. Why not install a new compiler for a somewhat cleaner recompilation. And a vanilla kernel... Bulls..t At least if you find that e.g. KDE is working stable. And Mdk 8.2 is _not_ that bad. Unfortunately, Mandrake is somewhat more perl than python biased. > > And do the same with SIP and PyQt from the Riverbank homepage ... Yes. You will need this, because the most recent RPMs are version PyQt-3.1 and sip-3.3.2. Take a look at /Mandrake-devel/cooker/contrib for SRPM files or http://cvs.mandrakesoft.com/cgi-bin/cvsweb.cgi/contrib-SPECS/ just for RPM spec files. If you know a bit about RPM, perhaps you, dwelch, can manage to update these packages (rpm -Uhv xx.src.rpm, a few changes ..., rpm -ba SPECS/sip.spec). Otherwise you could contact me. In about a week I've got time to do this. > > It seems to be better to forget that outdated stuff provided by the > Mandrake distribution ... Mandrake's packages are predominantly rather new versions. But see above. > > Armin > >> >> Installing software on Linux makes me feel like such an idiot! The RPM stuff (or DEB) has got real advantages compared to "setup.exe". And if the offered versions are outdated, fetch the new source, learn from the (e.g.) sip.spec file somewhat about the compilation, and make a new package! >> >> Any help or pointers would be much appreciated. >> >> Don From jubafre at brturbo.com Mon Sep 23 15:40:42 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Mon, 23 Sep 2002 16:40:42 -0300 (GMT-03:00) Subject: writing in a file as binary mode???? Message-ID: <1401166435.1032810042920.JavaMail.nobody@webmail2.brturbo.com> i open the a file for writing in a binary mode, but doesnt work final3=['0020 0000x9', '0030 0000xa', '00B4 0000x8', '0030 0000xb', '00F0', '0001', '0003', '0005'] destino=raw_input("Digite o nome do arquivo .mem: ") f = open(destino,'wb') f.write('\x03AHM ') for i in final3: f.write(i+' ') f.close() just the "f.write('\x03AHM ')" work, i open the file in the notepad and my file appears like a text file and not as a binary file, i dont know why?? >>file.mem AHM 0020 0000x7 0030 0000x8 0010 0000x9 00F0 0003 0002 0000 >>i have the file like this, how?? AHM ? 0 ?  ? ? Juliano Freitas www.gebrasil.hpg.com.br From tjlavoie at mb.sympatico.ca Fri Sep 27 12:41:05 2002 From: tjlavoie at mb.sympatico.ca (Tim Lavoie) Date: 27 Sep 2002 11:41:05 -0500 Subject: mod_python References: Message-ID: <87it0rqtb2.fsf@theasylum.dyndns.org> >>>>> "Uwe" == Uwe Schmitt writes: Uwe> Hi, I tried mod_python these days and found it quite usefull. Uwe> Are there any modules for handling sessions, cookies, and Uwe> persistent data ? Try the Webware toolkit, it has a ton of goodies there. It's at http://www.webware.sourceforge.net. The main piece of it that you would want for now is called WebKit, and it integrates nicely with Apache via a couple of different methods, depending on what works best for you. It feels a lot like Java servlet development to me, without some of the nuisance factor of Java. So, you have persistent servlets, which you can reload on the fly and so on, and which have access to a whole mess of data. As a side benefit, there are hooks to a couple of templating mechanisms, so you don't have to write all the "print ''" bits manually. Cheers, Tim -- Testing can show the presense of bugs, but not their absence. -- Dijkstra From tjreedy at udel.edu Fri Sep 20 09:40:22 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 20 Sep 2002 13:40:22 GMT Subject: general thoughts References: Message-ID: "Benjamin" wrote in message news:ifjloug0dkla5o3lvli464mmou5mbh47d5 at 4ax.com... > i've been learning python not for becoming a programmer > (i study modern languages at the university), but for having > fun. my personal motto is "i want to know how it works". ['but I'm getting bored'] Perhaps you should look into some area of computer-aided language analysis and processing. Something too specialized (and perhaps too difficult for most people) to be in any introductory text. Example: write a program to conjugate any Spanish verb given its infinitive form. If you succeed at that, write another one to de-conjugate any conjugated form back to infinitive form (this is more difficult). If you still need a challenge 8<), write a third program to recognize verbs in Spanish text. Or pick a different language problem of more interest to you. Perhaps a cross-language lexicon comparison. For example, given the words for 'zero' to 'ten' in several languages, devise an 'index of similarity' calculation. (This is also non-trivial). Calculate a similarity matrix and use it to draw some conclusions. I hope these ideas might serve to jog you out of the standard-boring-problem rut you seem to be in. Even if you do not become a 'programmer', you may easily find yourself using programming skills and maybe even Python in particular in many other careers. Terry J. Reedy From Padraig at Linux.ie Fri Sep 6 08:36:03 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Fri, 06 Sep 2002 12:36:03 GMT Subject: tree data structure References: Message-ID: Raymond Hettinger wrote: > There are a number of ways to represent trees: > -- instances of a treenode class > -- a list of lists: [l0, [s2, [s0, [q1]], [s1,[q2]], [s3]]] > -- or, my favorite, a dictionary of lists: > > > original = [('L0','S2'), ('S2','S0'), ('S2','S1'), ('S1','Q2'), ('S0','Q1'), ('S2','S3')] > > tree = {} > for key, value in original: > tree.setdefault(key,[]).append(value) > tree > {'S2': ['S0', 'S1', 'S3'], 'S1': ['Q2'], 'S0': ['Q1'], 'L0': ['S2']} Interesting I didn't know about setdefault. However how would you iterate over the above? I would like to first get L0, then S2, ... So I was thinking of something like: ('L0', ('S2', ('S0', ('Q1', None)), ('S3', None), ('S1', ('Q2', None)))) However I've only started programming python for the first time today and am unsure of how to best acheive this. thanks a lot! P?draig. > "Padraig Brady" wrote in message > news:FM0e9.2860$cP3.6165 at news.iol.ie... > >>Hi, >> >>I've a graph like stucture represented >>by a list of tuples: >> >>[(L0,S2), (S2,S0), (S2,S1), (S1,Q2), (S0,Q1), (S2,S3)] >> >>And would like to convert it to >>a tree structure like: >> >> S0 - Q1 >> / >>L0 - S2 - S3 >> \ >> S1 - Q2 >> >>Any tips appreciated. >> >>Thanks, >>P?draig. >> > > > From goodger at users.sourceforge.net Sun Sep 15 12:59:48 2002 From: goodger at users.sourceforge.net (David Goodger) Date: Sun, 15 Sep 2002 12:59:48 -0400 Subject: ANN: DocFactory wxPython app for Docutils Message-ID: Gunnar Schwant has contributed DocFactory, a wxPython GUI application for Docutils. It is in the preliminary stages. For details, please see http://docutils.sf.net/sandbox/gschwant/docfactory/README.html I have begun a "To Do" list: http://docutils.sf.net/sandbox/gschwant/docfactory/NOTES.html The code is available via CVS or snapshot: http://docutils.sf.net/docutils-sandbox-snapshot.tgz Please try it out. Feedback is welcome: bug reports, patches, feature ideas, etc. -- David Goodger Open-source projects: - Python Docutils: http://docutils.sourceforge.net/ (includes reStructuredText: http://docutils.sf.net/rst.html) - The Go Tools Project: http://gotools.sourceforge.net/ From no at mail.com Tue Sep 17 06:00:52 2002 From: no at mail.com (BT) Date: Tue, 17 Sep 2002 12:00:52 +0200 Subject: Source code References: <3d867f4d$0$23173$afc38c87@news.optusnet.com.au> Message-ID: <3D86FD54.92DD65F2@mail.com> >> True.. that's why I'm planning to obfuscate the code then encrypt it. >you don't want to go overboard with this, people still have to use the >program - where are you going to keep the code that is 'now' (once >decrypted) in plaintext? >[...] >if they're able to run the code, it'd be a fairly solid bet that they'd know >about Python, if not, a quick search on Google would probaly net you all the >info you need to find out just what that file is. After all, in order to run >the program they'd need to at least install Python somehow - unless you're >planning to embed Python in some other app, and run your code in that... Yes, sorry... I forgot to mention I'm planning to embed the encrypted pyc in a standard c application who will load the file in memory and decrypt it. I've read somethig about importing .pye files from a db, but now I am still developing, never tried to do that: I'll try do protect the app when it's completed. For "obfuscate the code" I mean writing (or find) a small app that sobstitute every variable and function name with a random code like 'd93jkm39'. Yes, the software will be usable even in plain text, but I think everyone will waste some time to figure out what's happening. I don't want to waste months to find a way to protect it, a week or two will be sufficient. From wpmelcher at snet.net Mon Sep 30 17:21:41 2002 From: wpmelcher at snet.net (Bill Melcher) Date: Mon, 30 Sep 2002 21:21:41 GMT Subject: PySol: "global name 'win32_gethomedir' is not defined" References: Message-ID: I think Alan's problem is that the Python distribution that he installed does not include the Win32 Extensions. The Python Labs install does not include the extensions. The ActiveState install does. -- Cheers, Bill TANSTAAFL! "Alan Winston" wrote in message news:all3u2$qgm$1 at brokaw.wa.com... > I've been trying to run the PySol 4.81 pyc files under Python 2.2.1 and > WinXP and Win98, with no success. > > The Python window closes much faster than I can read the error message (is > there any way to force the window to stay open?), but I managed to catch it > with the print screen key: > > "global name 'win32_gethomedir' is not defined" > > PySol 4.60 runs fine, installed with the Windows install package, so this is > a low priority for me, but I am still curious. > > > > > Alan Winston > Seattle > > > > > From Padraig at Linux.ie Mon Sep 30 09:12:39 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Mon, 30 Sep 2002 13:12:39 GMT Subject: Find out link location References: <7uf9na-vd9.ln@lbdb01.gsi.de> <3D984AF8.3070908@Linux.ie> Message-ID: <3D984D80.9040509@Linux.ie> Padraig Brady wrote: > Klaus Hoeppner wrote: > >> Hi, >> >> with the os.path module I can use the islink function to check, wether >> a file is symbolic link. But how can I find out, where the link points >> to. E.g. if I have readme.txt --> ../packages/mypackage/readme.txt how >> do I get the "../packages/mypackage/readme.txt" with python? > > import os > filter (lambda x: x.find("link") != -1, dir(os)) To be a little more modern: [x for x in dir(os) if x.find("link") != -1] P?draig. From dag at animagicnet.no Wed Sep 4 08:11:35 2002 From: dag at animagicnet.no (Dag) Date: 4 Sep 2002 12:11:35 GMT Subject: Matching a string up to a word Message-ID: I have a string that contains an ID number a file path and a date, kind of like this: 23545 /this/is a/path/to/a file Sun Sep 7 2002. I want to extract the file name. If I could be sure that the file path had no spaces or if it would be quited it would be easy. Unfortunatly many files will have spaces and changing the format of the output I'm dealing with isn't possible. I do however know that the file name starts after the first whitspace and that it's always followed by a three letter day name (like Mon, Tue etc.) Given this is there an easy way to extract the whole file path from the string. Dag From skip at pobox.com Tue Sep 17 22:09:41 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 17 Sep 2002 21:09:41 -0500 Subject: Python GUI app to impress the boss? In-Reply-To: <96904b50.0209171305.6d65f574@posting.google.com> References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: <15751.57445.514521.644297@12-248-11-90.client.attbi.com> Lee> Can someone point me to a good Python GUI app to demonstrate (other Lee> than IDLE)? Lee, At IPC 10, Michel Sanner from Scripps took home the best paper award for his ViPEr work. References: http://www.python10.org/p10-awards.html http://www.python10.org/p10-papers/10/index.htm http://www.scripps.edu/~sanner/python/viper/index.html -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From erick_papadakis at yahoo.com Sun Sep 15 21:02:17 2002 From: erick_papadakis at yahoo.com (Erick Papadakis) Date: 15 Sep 2002 18:02:17 -0700 Subject: can wxpython do this? Message-ID: <737aefee.0209151702.3f735252@posting.google.com> hi, i am considering learning wxpython and have a few questions before i get into it to make sure it is worth it. 1. what does it give me that java or c++ dont? is it cross-platform too? 2. is it a good platform to develop desktop application in, given that it is a GUI app? how will i distribute it? is there any easy installer that will allow me to install python first on a layman user's computer first, then wxpython, then my own application? is this the concept of wxpython or am i missing something? 3. does it allow me access to windows (or linux x-windows) native APIs? for instance, can i minimize my application to a user's desktop's taskbar and have a right-click context menu on that taskbar entry? 4. do i have something like a browser control built in? i want my desktop app to interact with my web server and display the response just as if it was a browser (BUT with some more client-side richness in features, hence the app to begin with). is this possible? thanks very much for any ideas/resources that i can use to decide. cheers/.ep From martin at v.loewis.de Thu Sep 26 13:53:14 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 26 Sep 2002 19:53:14 +0200 Subject: fcntl module on Linux and nonblocking I/O References: <7e9d8e38.0209260932.ed2c78@posting.google.com> Message-ID: skoranda at uwm.edu (Scott Koranda) writes: > I just installed python 2.2.1 on my RH 7.3 Linux box and noticed > that the fcntl module does not appear to have O_NDELAY, FNDELAY, > or anything that appears similar. [...] > Without such a constant defined in the fcntl module how can I make a > pipe non-blocking? Use os.O_NDELAY. Regards, Martin From ggittings at arraybiopharma.com Fri Sep 6 18:46:54 2002 From: ggittings at arraybiopharma.com (Gabe Gittings) Date: 6 Sep 2002 15:46:54 -0700 Subject: COM/Active X newbie question Message-ID: <5523ec5.0209061446.1404cd10@posting.google.com> I am a newbie to prgramming in Python and programming under windows. I am trying to access an .ocx file. I can access the methods in python after running makePy.py but when I run a test script and try to access a method from the COM object I get this error. Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\Lib\site-packages\win32com\gen_py\7ADCDC5B-D0B6-11D1-AA76-002078136998x0x1x0.py", line 57, in GetRunManagerStatus return self._oleobj_.InvokeTypes(0xa, LCID, 1, (8, 0), (),) com_error: (-2147418113, 'Catastrophic failure', None, None) this is the code I am using import win32com.client.gencache import win32com.client # Use these commands in Python code to auto generate .py support # makes a .py for the Acquisition .ocx via UUID from win32com.client import gencache gencache.EnsureModule('{7ADCDC5B-D0B6-11D1-AA76-002078136998}', 0, 1, 0) xdk = win32com.client.Dispatch('{7ADCDC5E-D0B6-11D1-AA76-002078136998}') print xdk.GetSeqQueuePaused() I am not really sure if .Dispatch is even appropriate in this situation because I need to monitor an already running application which I access through it's .ocx. Hope this makes sense. So in case I wasn't clear there are two questions. 1. why am I getting the error message when I am accessing the COM objects methods? 2. is this how you connect to a client side COM if you want to access an already running app. Thanks From storedmails at gmx.net Mon Sep 23 10:50:23 2002 From: storedmails at gmx.net (beachboy) Date: 23 Sep 2002 07:50:23 -0700 Subject: Sessionhandling Message-ID: Hi! Please can anyone help me. My problem: I'm trying to program a web application with python. This tool has to provide diffrent languages. The user has to choose the language at the beginning. So i have to save the information which language the user chooses. I think this is a perfect example for using sessions. The only problem is I've got no idea how to realise this in python. Please help me as soon as you can because I have to solve this problem very quickly. hoping to hear from you soon beachboy From lists at gregfortune.com Fri Sep 20 02:12:33 2002 From: lists at gregfortune.com (Greg Fortune) Date: Thu, 19 Sep 2002 23:12:33 -0700 Subject: Catching results of an exec References: <3d88f701$0$304$39cecf19@nnrp1.twtelecom.net> <3D88FC6E.59D0DD01@alcyone.com> Message-ID: <3d8aba3c$0$308$39cecf19@nnrp1.twtelecom.net> Erik Max Francis wrote: > Greg Fortune wrote: > >> Is there any way to "catch" the value produced by an exec? I'm >> considering >> things like print statements that don't really assign a value, but do >> send >> a result to stdout. > > The problem is "the value produced by an exec" is ambiguous, because > execs (as don't return values). If you want to capture some subpart of > the execution of a statement, you'll have to handle it case by case. > >> Right now I've got a nasty hack that redirects stdout, uses an >> InteractiveInterpereter from the code module to execute the code, >> writes to >> an output file, reads the result from the file, restores stdout and >> then >> sends the result to the client. Hopefully, that's a terrible way to >> do it. > > That's probably the best way to do it, actually -- or, at least, with an > overridden sys.stdout in the globals dictionary that you're passing to > eval/exec (which doesn't necessarily have to be the same dictionary as > your main script is running). > Thanks, I hadn't thought to use the namespace stuff on exec. That'll clean up a couple more lines.. Greg From jb at cascade-sys.com Mon Sep 30 13:54:22 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Mon, 30 Sep 2002 10:54:22 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: <3D988FCE.6040502@cascade-sys.com> Steve Holden wrote: > wrote... > > >[ ... ] >OK, so don't use whole pennies (or smallest currency) as your >base, use 10,000ths of a penny, but still use integer arithmetic >for your calculations. > Normal Integers aren't big enough. 2^31 / 10K == 215K. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From claird at starbase.neosoft.com Fri Sep 13 16:33:02 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 13 Sep 2002 15:33:02 -0500 Subject: Tkinter listbox clicking problem References: Message-ID: <2D7E3697CF5D1521.5D9711540E657ED8.7EF0451C598438FC@lp.airnews.net> In article , Russell E. Owen wrote: >In article , > "Matthew Bonig" wrote: > >>Right now I have it bound so when a Tkinter listbox gets a >>(lb.bind("", someFunc)) it calls function someFunc. Now, >>someFunc() simply prints the curselection(). The problem is it's lagged... >>if I first select list item 1 (index 0), and then 2, and then 3 (array >>indexes 0,1,2) it prints out themout incorrectly. >>(I have someFunc actually do some try, except stuff so I don't get uncaught >>exceptions) Instead of printing 0,1,2 it prints "nothing selected", 0, 1. >>The function get's called before the listbox updates it's selection markers! >> >>Does anybody know how I could force listbox to update it's selection markers >>so instead of printing "nothing selected, 0,1 it prints 0,1,2 like it >>should? > >I'm hoping somebody has better ideas, but here are some to try: > >Call update_idletasks before you ask for the selection. I have no idea >if this will work, but it might. > >An ugly solution that would probably work: >- extract the y coordinate from the event callback >- call nearest(y_coord) to get the item closest to the mouse click >- explicitly select that index item. You could try skipping this step, >but you risk a possible error between what you think they clicked on and >what is hightlighted. Unfortunately, this step will may be a real pain >for a list that supports multiple selected items. > >Poll for selection changes -- thus it may take a bit of time before your >code notices a change, but it will always be right once it gets there. > >-- Russell Whoa! There's a far easier solution. Read up on 'bindtags' in and elsewhere. has a small example that almost is pertinent. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From jn at who.net Thu Sep 5 10:12:08 2002 From: jn at who.net (john nielsen) Date: 5 Sep 2002 07:12:08 -0700 Subject: psyco is great! Message-ID: <22cc1071.0209050612.7311a89c@posting.google.com> Psyco is a great idea. I just tried it out on _unmodified code_ that parses large logfiles and it doubled the performance. A nice convenince compared to things like swig, is that you don't even need to have a C compiler around. Just point it to the functions you want optimized. import psyco def fred(): print 'stuff here' psyco.bind(fred) fred() john From me at aaronsw.com Wed Sep 4 23:06:53 2002 From: me at aaronsw.com (Aaron Swartz) Date: 4 Sep 2002 20:06:53 -0700 Subject: Graham's spam filter References: Message-ID: I've thought about building something similar too. I don't need the network code, I can just integrate it into my mail path. Here are some useful resources: python-cdb[1] is a Python interface to D. J. Bernstein's cdb package[2], which supports fast lookups (normally just two disk accesses), low overhead (24 bytes per record, no startup cost) and is designed for mission-critical applications like email. In short, it's absolutely perfect for this application. [1] http://pilcrow.madison.wi.us/ [2] http://cr.yp.to/cdb.html Bram Cohen has been thinking of modifications to the algorithm and writing them up in Python[3]. [3] http://www.advogato.org/person/Bram/diary.html?start=17 Hope this helps, Aaron Swartz [http://www.aaronsw.com/] From timr at probo.com Wed Sep 25 01:56:51 2002 From: timr at probo.com (Tim Roberts) Date: Tue, 24 Sep 2002 22:56:51 -0700 Subject: Can't suspend a thread? References: Message-ID: aahz at pythoncraft.com (Aahz) wrote: > >Robert Oschler wrote: >> >>I was hoping to have a master thread that woke up and suspended several >>other threads dynamically, as needed. From the books I have, that seems to >>be impossible in Python? Is this true? If so, is there a workaround? > >Threads suspend themselves; they can be woken up by other threads. It is worth pointing out that this "restriction" is not a Python thing; it is an operating system thing. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From kilaruba at copper.net Wed Sep 18 16:59:58 2002 From: kilaruba at copper.net (bert) Date: Wed, 18 Sep 2002 13:59:58 -0700 Subject: multiple index inconsistency Message-ID: The following line of code >>> a = 3*[range(3)] produces [[0, 1, 2], [0, 1, 2], [0, 1, 2]] If I then write, say, >>> a[0][1] = 3.7 I get [[0, 3.7, 2], [0, 3.7, 2], [0, 3.7, 2]] and not [[0, 3.7, 2], [0, 1, 2], [0, 1, 2]] Now if I write >>> a = [[0, 1, 2], [0, 1, 2], [0, 1, 2]] instead, and then >>> a[0][1] = 3.7 I get the result I expected (and wanted): [[0, 3.7, 2], [0, 1, 2], [0, 1, 2]] Why the inconsistency? Is this a bug or am I missing something? -- Bert From mickey at tm.informatik.uni-frankfurt.de Sun Sep 1 19:40:25 2002 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 2 Sep 2002 01:40:25 +0200 Subject: QPEApplication.setStylusOperation() woes. Message-ID: <3d72a569@nntp.server.uni-frankfurt.de> Hi, I'm using PyQt on Qt/Embedded within a palmtop environment. Although PyQt seems to wrap QPEApplication.setStylusOperation (widget, QPEApplicaiton.RightOnHold), the effect on calling it is nada. Did anyone got this to work? (Already posted on the PyQt-Mailing list, but only got silence - I'm hoping to get a larger audience here). Yours, :M: -------------------------------------------------------------------------- Dipl.-Inf. Michael 'Mickey' Lauer mickey at tm.informatik.uni-frankfurt.de Raum 10b - ++49 69 798 28358 Fachbereich Informatik und Biologie -------------------------------------------------------------------------- From iqbal at colorado.edu Wed Sep 11 13:44:51 2002 From: iqbal at colorado.edu (Naveed Iqbal) Date: 11 Sep 2002 10:44:51 -0700 Subject: Python-FilemakerPro 5.5 Connectivity Message-ID: <6afb9d2c.0209110944.74aeaca2@posting.google.com> Is it possible to connect to a Filemaker pro database from python? If so what are the modules required? and what are the connection parameters? thanks naveed From tim.one at comcast.net Sun Sep 29 13:58:18 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 29 Sep 2002 13:58:18 -0400 Subject: Python's import: why doesn't it work? In-Reply-To: <3d9739c7$0$19818$91cee783@newsreader01.highway.telekom.at> Message-ID: ]Jurie Horneman] > ... > However, I do stand by my criticisms of the Python docs. Every page of the docs sez at the bottom: See About the Python Documentation for information on suggesting changes. which link says, in part, General comments and questions regarding this document should be sent by email to python-docs at python.org. If you find specific errors in this document, please report the bug at the Python Bug Tracker at SourceForge. The docs are exactly as good as volunteers have made them (well, actually better, thanks to Fred ). When you find an explanation inadequate to your needs, suggesting specific improvements in the right place is the only way it will improve. From aleax at aleax.it Fri Sep 20 03:32:47 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 07:32:47 GMT Subject: sorry for this stupid question about struct module References: <3d8a4ae7$0$280$7a628cd7@news.club-internet.fr> Message-ID: Alan Marchand wrote: > Hi all, > > I tryed this : > > e:\temp>python.exe > Python 2.2.1 ( #34, Apr 9 2002, ...................) > ........... >>>> import struct >>>> x = struct.pack( '>I', 10 ) >>>> print repr( x ) > '\x00\x00\x00\n' # why not ! > > How can I obtain the result a expect : '\x00\x00\x00\0A' ? If you need a specific repr that ignores the possibility of representing some characters otherwise than as hex escapes, I think you'll have to code it yourself -- most particularly so if you want some hex escapes to have the x (as in the \x00 occurrences above) and others to lack it (as in the \0A above): how would any standard repr ever be able to guess these reqs?! I don't understand why you need such a weird repr. What are you going to do with it? x is a 4-byte string made up of bytes with numerical values 0, 0, 0, 10 -- repr shows the latter as \n, of course, since 10 is the value of \n -- but why is repr's behavior problematic to you? > Remark : > This, to send a message to a IBM Mainframe in order to start an IMS > transaction ( via IMS CONNECT ). You won't use repr for the purpose of sending that message, thus I'm more and more perplexed about why you think there's a problem here. String x does seem to be what you want to send. Alex From martin at v.loewis.de Sun Sep 22 16:23:13 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 22 Sep 2002 22:23:13 +0200 Subject: Wanted: Tix examples References: <3d8dde58$0$30454$afc38c87@sisyphus.news.be.easynet.net> Message-ID: "Justin" writes: > The module itself mentions the tixwidgets.py demo; > where does one find it? It's in the Demo/tix directory of the Python distribution. Regards, Martin From eric.brunel at pragmadev.com Wed Sep 11 08:17:03 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 11 Sep 2002 14:17:03 +0200 Subject: regular expression for space seperated quoted string References: Message-ID: Padraig Brady wrote: > Hi, I'm trying to split a string that is seperated > by spaces and also contains double quoted words which > can contain spaces: > > For e.g. using: re.split('[ ]*"?([^"]*)"?[ ]*', s1) > on this string: s1='1 "2" "thre e"' > gives: ['', '1 ', '', '2', '', 'thre e', ''] > > Problem with this is the '' entries, but this isn't too bad. > > However using the above re with: s2='1 2 "th ree"' > I get: ['', '1 2 ', '', 'th ree', ''] > > any ideas? What about: >>> p = r'[^ \t\n\v\f"]+|"[^"]*"' >>> re.findall(p, '1 2 3') ['1', '2', '3'] >>> re.findall(p, '1 2 "three"') ['1', '2', '"three"'] >>> re.findall(p, '1 "2" "thr ee"') ['1', '"2"', '"thr ee"'] >>> re.findall(p, '"yeah it seems to be working!" yeah it seems to...') ['"yeah it seems to be working!"', 'yeah', 'it', 'seems', 'to...'] It leaves the double-quotes around the values, but they can be removed quite simply... I also tried to use look-ahead and look-behind features in re's, but it doesn't have the expected result: >>> re.findall(r'(?<=")[^"]*(?=")|[^ \t\n\v\f"]+', '"yeah it seems to be working!" yeah it seems to...') ['yeah it seems to be working!', 'yeah', 'it', 'seems', 'to...'] >>> re.findall(r'(?<=")[^"]*(?=")|[^ \t\n\v\f"]+', '1 2 3') ['1', '2', '3'] >>> re.findall(r'(?<=")[^"]*(?=")|[^ \t\n\v\f"]+', '1 "2" "thr ee"') ['1', '2', ' ', 'thr ee'] The " " between 2 and three is also matched... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From henrik.motakef at web.de Thu Sep 19 11:27:26 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 19 Sep 2002 17:27:26 +0200 Subject: strong/weak - dynamic/static [Was: Getting started] References: Message-ID: <87ofaut2xt.fsf@pokey.henrik-motakef.de> "Mark McEahern" writes: > $ python > Python 2.2.1 (#1, Jun 25 2002, 10:55:46) > [GCC 2.95.3-5 (cygwin special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> class foo: > ... def fooize(self): > ... print self.__class__.__name__ > ... > > >>> class bar: > ... def barize(self): > ... print self.__class__.__name__ > ... >>> f = foo() >>> b = foo() >>> b.__class__ = bar >>> f.fooize() foo >>> b.barize() bar >>> type(f) == type(b) 1 >>> type(f) >>> There's a difference between a type and a class, I guess... From djc at object-craft.com.au Fri Sep 20 22:35:49 2002 From: djc at object-craft.com.au (Dave Cole) Date: 21 Sep 2002 12:35:49 +1000 Subject: saving state in Python/CGI References: <5.0.0.25.2.20020920134912.00ad3230@hms.harvard.edu> Message-ID: >>>>> "Tim" == Tim Churches writes: Tim> Frank Gibbons wrote: >> Hi, >> >> I've been using Python (and Jython) for about 5 months now. So far, >> so great. I'm building a CGI app that has about 5 different stages, >> and I need to maintain state between them. Specifically, it's a >> scientific tool that requires the user to upload a (possibly quite >> large) datafile, processes it, does some computation, then hands it >> back (formatted) with results. >> >> I need access to the data on each page, yet don't want to pass it >> as a hidden field, because of its potential size. In Perl, I could >> just use the save() method from CGI.pm to save the form on the >> server side, pass a session key in a hidden field, then retrieve >> the data using the key. For the life of me, I can't find an >> equivalent way in Python. cgiFormStorage looks like a dictionary, >> but it's immutable, so you can't retrieve data from disk and add it >> to the form. cgi.py appears to have no analog to CGI.pm's save() >> method, at least not that I've been able to find. I've tried >> pickling the form, but that doesn't work either (it saves something >> to disk alright, but not the large data retrieved from a multi-part >> form file upload). >> >> Perhaps I've missed something. Maybe that's just not how you do >> things in Python. Can anyone help? Tim> You need to use one of the (many) Python Web app frameworks which Tim> help (to greater or lesser degrees) with storing state and other Tim> typical Web app tasks. There is a list of such frameworks Tim> available at Tim> http://www.python.org/cgi-bin/moinmoin/WebProgramming Tim> Of these, I have only used Albatross, but I can heartily Tim> recommend it - it was specifically designed with highly stateful Tim> applications in mind, is elegantly designed and well written and Tim> has excellent documentation and the authors are very helpful. We Tim> use it for a range of quite complex epidemiological applications. Tim> However, many of the other frameworks list on the above site are Tim> also reputed to be very good and you should consider all of them Tim> before making a choice. I am one of the authors Tim is referring to. The application you have described has very similar data capture and processing requirements to Tim's application. Albatross was developed specifically with that type of problem in mind. If you have the time you should try a few of the toolkits to see which most suits the way you like to solve problems. One of the big features that Albatross has going for it is the ability to expose deeply nested recursive data structures to HTML form input. Read point 3 of the following page for a description of the alias feature: http://object-craft.com.au/projects/albatross/albatross/tag-input-alias.html - Dave -- http://www.object-craft.com.au From gmuller at worldonline.nl Sun Sep 22 14:56:51 2002 From: gmuller at worldonline.nl (GerritM) Date: Sun, 22 Sep 2002 20:56:51 +0200 Subject: How to get memory usage on Windows? References: Message-ID: "Wolfgang Strobl" schreef in bericht news:f51sou8o4j9pkilhc3g6jevkqmkk7jr3pl at 4ax.com... > "GerritM" : > > >Searching in books , documentation (a.o. win32api) and net did not yet help > >I found this article on the net: > >http://www.developeriq.com/Magazinestories/02jul29memory.php3 > >but how to call this function from Python? > > I guess thanks to Mark Hammond you already have everything you need. > > Have a look at \Python22\Lib\site-packages\win32\Lib\win32pdhutil.py, > uncomment the test function, run it. > > I snarfed the following snippet straight from win32pdhutil.py: <...snip...> > -- > Wir danken f?r die Beachtung aller Sicherheitsbestimmungen Wolfgang, thanks. I think this will work only on NT. Here at home I have "only" windows98, which gives the following message: "RuntimeError: The pdh.dll entry point functions could not be loaded." I will have to try this at work, on a windows2000 machine. regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From oren-py-l at hishome.net Sun Sep 1 02:19:38 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sun, 1 Sep 2002 02:19:38 -0400 Subject: python slowdown after a longish time of running (garbage collector) In-Reply-To: <87adn2o7op.fsf@nospam.eml.cc> References: <20020829152040.GA3061@foof.i3.cz> <20020830133244.V3893@prim.han.de> <3D701C6F.6010402@ob_scure.dk> <87adn2o7op.fsf@nospam.eml.cc> Message-ID: <20020901061938.GA9528@hishome.net> On Sun, Sep 01, 2002 at 12:49:29AM +0000, Mahesh Padmanabhan wrote: > I don't know how GC is implemented in Python, but GC by its very > can only guarantee that it will close the socket eventually - it > cannot guarantee *when*. The GC is implementation-dependent. For Jython it uses the garbage collector of the underlying JVM. CPython uses a combination of reference counting and cycle garbage collection. In CPython the reference counting means that unless you create a cyclic reference an object will be garbage-collected immediately when there are no more references to it. It is unportable to rely on this behavior but apparently many programmers do. Oren From aleax at aleax.it Thu Sep 19 12:41:04 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 18:41:04 +0200 Subject: strong/weak - dynamic/static [Was: Getting started] In-Reply-To: References: Message-ID: On Thursday 19 September 2002 05:51 pm, sismex01 at hebmex.com wrote: [snip: my code showing how an object can dynamically change type] > > If you find a way to name this behavior "static", you'll be well > > placed for the yearly Humpty Dumpty award. ... > Maybe you're being a bit rash, Alex? Maybe, and maybe not. [snip: sixmex01's code showing how not ALL dynamic type changes are allowed] > The behaviour you expounded does not blindly work, it seems. Of course, and, had I claimed Python is "BLINDLY dynamic", then I'd have been "a bit rash". As I cleverly omitted the damning adverb, I'm safe. An object's type can be changed at runtime *as long as* this doesn't alter the "layout" (__slots__ isn't the only example: you can't, for example, dynamically change the type of a list to be a dictionary, etc, etc). This still leaves Python vastly more dynamic than the great majority of languages, where an object's type is determined, at the latest, at object-creation time. (SOME languages may indeed be even slightly more dynamic: I think Ruby is, for example; but the fact that SOME F1 drivers are even faster than Mr Barrichello -- one Mr Shumaker comes to mind -- hardly means one is "being a bit rash" if one deems Mr Barrichello a deucedly fast driver indeed). Alex From gmcm at hypernet.com Fri Sep 13 08:00:55 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 13 Sep 2002 12:00:55 GMT Subject: how can i make a executable program with a python2's script References: <3D7924BF.805@motorola.com> Message-ID: jgm2163 wrote: [...] > sorry,i want to make a release program on the computer that donot > install python2.1 (because that python1.5 was installed on the redhat > 7.2 defaultly). Installer http://www.mcmillan-inc.com/installer_dnld.html will do that, as long as the libc's are compatible. -- Gordon http://www.mcmillan-inc.com/ From danb_83 at yahoo.com Tue Sep 3 03:03:14 2002 From: danb_83 at yahoo.com (Dan Bishop) Date: 3 Sep 2002 00:03:14 -0700 Subject: Python to surpass C performance by 2030 References: Message-ID: Erno Kuusela wrote in message news:... > just for fun i ran pystone under python versions since 1.5.2 to > current cvs. here are the results: > > [benchmark results snipped] > > since 1.5.2 is about 4 years old, the improvement per year is about > 13.2% on average. if we assume that 1.5.2 is 50 times slower than > C (probably conservative?), then at 13.2% per year since 1998 it > will add up to 53x improvement in 32 years. > > i wonder if this would be a good application for the time machine... > > learn python today, and in 28 years you will have a job writing > the speed-critical parts of c programs in python :) Before that could ever happen, the Python interpreter would have to be written in something other than C. From eric.brunel at pragmadev.com Thu Sep 26 08:45:37 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 26 Sep 2002 14:45:37 +0200 Subject: Multiple file open dialog References: <3d92dce4$0$1286$cc9e4d1f@news.dial.pipex.com> Message-ID: Nick B wrote: > Hi, > > Can anyone advise on how to get a list of multiple file names from a GUI > dialog. I am working exclusively in Win32 but so far only have GUI > experience with Tkinter. What I would like is access to the standard > Win32 shift-click and control-click conventions. > > Tkinter's askopenfilename can only return a single filename (?). There should be a "multiple" option on askopenfilename that allows to select multiple files. However, it seems that's it's quite recent (didn't succeed in making it work with Tk 8.3.2). But maybe it works for you? Just do: askopenfilename(..., multiple=1, ...) HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From max at alcyone.com Wed Sep 25 02:34:28 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 24 Sep 2002 23:34:28 -0700 Subject: Strange python and cgi! References: Message-ID: <3D9158F4.F826F039@alcyone.com> Tim Roberts wrote: > If you are running Linux, check the log file at > /var/log/httpd/error-log. The problem is that the log location depends entirely on how Apache is configured, which in turn depends upon the version, the distribution (which often choses different locations for different log files), and the local configuration. It could be /var/log/error_log, /var/log/errors, /var/log/apache/errors, etc. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Music washes away from the soul the dust of everyday life. \__/ Berthold Auerbach 7 Sisters Productions / http://www.7sisters.com/ Web design for the future. From pete at shinners.org Thu Sep 12 11:19:30 2002 From: pete at shinners.org (Pete Shinners) Date: Thu, 12 Sep 2002 15:19:30 GMT Subject: "str.contains(part)" or alternatives? References: Message-ID: <6g2g9.295995$aA.51455@sccrnsc02> Delaney, Timothy wrote: > In fact, this was the deciding factor in Guido changing his position on 'if > s1 in s2'. A string has sequence-like behaviour (e.g. it is iterable, > individual characters can be indexed), but also has its own behaviour (e.g. > substring containment, all elements are single-character strings). does this mean we can also now do this? if so, nifty >>> 1,2,3 in range(10) 1 >>> 3,2,1 in range(10) 0 From raskpetersen at hotmail.com Tue Sep 24 09:05:57 2002 From: raskpetersen at hotmail.com (Anders R) Date: 24 Sep 2002 06:05:57 -0700 Subject: =?ISO-8859-1?Q?Decoding_url_with_country_specific_chars_(like_=E6=F8=E5)?= Message-ID: <547475ee.0209240505.1c27bc9f@posting.google.com> Hi, i had a fustrating experience while doing some url decoding on a unicode string that contains country specific chars: The original string (unicode, so it might look strange here): TestProduct?, opdateret 27/8 Pr?ver lige en umlaut: ? The string in encoded form: TestProduct%26%238482%3B%2C%20opdateret%2027/8%20Pr%C3%B8ver%20lige%20en%20umlaut%3A%20%26%23228%3B the output i get when i decode it with urllib.unquote_plus(var): TestProduct™, opdateret 27/8 Pr%C3%B8ver lige en umlaut: ä in case special chars are escaped: TestProduct&#8482;, opdateret 27/8 Pr%C3%B8ver lige en umlaut: &#228; So instead of '?' in the (danish) word 'Pr?ver' isn't decoded correct, in fact it looks like Python (version 2.1) totally leaves the '%C3%B8' alone... Can anyone explain this behaviour? It seems like unicode *is* supported fine, since the TM sign and the ? (a with umlaut) is translated fine! Maybe its only us danes getting discriminated ;-O please help :-S //Rask From exarkun at meson.dyndns.org Thu Sep 12 09:14:22 2002 From: exarkun at meson.dyndns.org (Jp Calderone) Date: Thu, 12 Sep 2002 09:14:22 -0400 Subject: class variable won't icrement! In-Reply-To: <7647A9F4B298E74DB6793865DA67285004ADF4@exchange.adrembi.com> References: <7647A9F4B298E74DB6793865DA67285004ADF4@exchange.adrembi.com> Message-ID: <20020912131422.GB29027@meson.dyndns.org> On Thu, Sep 12, 2002 at 12:18:32PM +0200, Roman Yakovenko wrote: > Hi it is simple just change > self.id = self.id + 1 > > To > > test.id += 1 > > Roman > Actually, that turns out not to be the case. += behaves differently depending on its arguments - sometimes rebinding the name, sometimes mutating in place. For integers, it can not mutate in place (ints are immutable, of course!) so "self.id = self.id + 1" is exactly the same as "self.id += 1". Were 'id' a mutable type, say a list, then the above solution would work (assuming you changed 1 to something iterable). Jp -- It is practically impossible to teach good programming style to students that have had prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration. -- Dijkstra -- 9:00am up 114 days, 9:53, 4 users, load average: 0.02, 0.01, 0.00 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 248 bytes Desc: not available URL: From charlotte at henkle.com Tue Sep 17 18:23:09 2002 From: charlotte at henkle.com (Charlotte Henkle) Date: 17 Sep 2002 15:23:09 -0700 Subject: boolean searching with keywords Message-ID: <8f49f05a.0209171423.743c1383@posting.google.com> Hello; I'm trying to add some new functionality to a program I've written in Python. This is the first program I've ever written in Python, so please forgive my newbieness. I wouldn't be at all shocked if I haven't picked the easiest solution to various problems. ;) This is how the program currently works. The first thing the program does when it starts is open a pop connection to see if there's any mail in its mailbox. If there's mail, it pulls down the first message. It parses the message looking for URL, pulls them out and appends them to a URL list. One it has a URL list, it begins to follow the URLs so that it can pull down the HTML. The program also has a list of key words. The keywords text file is a CR deliminated list of words to look for in the HTML. If the program finds ANY of the keywords, it sends off an email with a copy of the HTML it's found. Here are the important functions: def generateKeywords(): f = open('Keywords_Business.txt', 'r') keys = map(lambda s: s[:-1],f.readlines()) return keys def followURLs(): for eachLine in urlList: print("Following this URL:" +eachLine) data=urllib.urlopen(eachLine) myData=data.read() text=stripper(myData) # stripper strips out javascript, Etc if checkData(text): print('FOUND ONE!') htmldata=urllib.urlopen(eachLine) def checkData(d): regexp = r'\b(' + '|'.join(keys)+ r')\b' newsearch = re.compile(regexp) found = newsearch.search(d) if found: global subject subject = found.group() return 1 else: return 0 So far, so good (although if you can see improvements in this, please let me know). This works fine for single words on a line in a file. However, now I want to add a Boolean search capability. IE, instead of searching for "Frogs" or "Green" or "Lizards", I'd like to be able to search for "frogs NOT green" or "Lizards AND green" or "green AND scaly". As before, if any of the phrases are found, I want to break out of the search and send mail. I'm not sure how to do this. I considered making a tree structure, and then walking the tree, but I was unable to get it working correctly. Additionally, I was unsure if this was making the problem too complex: Is there an easier way to get the functionality I want? I would appreciate any help. Thank you! From peter at engcorp.com Thu Sep 5 08:37:47 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 05 Sep 2002 08:37:47 -0400 Subject: Matching a string up to a word References: <3d75ffaa$1@news.sentex.net> <3d76c1f7$1@news.sentex.net> Message-ID: <3d775000$1@news.sentex.net> Bengt Richter wrote: > On Wed, 04 Sep 2002 22:31:46 -0400, Peter Hansen wrote: > >>I was thinking of something like that. This should do it then: >> >> filename = ' '.join(field.split(' ')[1:-4]) >> >>That is, provided you never expect to see more than one consecutive >>space in your filenames... > > Why should that hurt, if the head and tail items are consistently separated > by single spaces? > > >>> line = '12345 /some weird/path with multiple- -spaces Wed Sep 4 2002.' > >>> line.split(' ') > ['12345', '/some', '', 'weird/path', 'with', 'multiple-', '', '', '', '-spaces', 'Wed', 'Sep', '4', '2002.'] > >>> line.split(' ')[1:-4] > ['/some', '', 'weird/path', 'with', 'multiple-', '', '', '', '-spaces'] > >>> ' '.join(line.split(' ')[1:-4]) > '/some weird/path with multiple- -spaces' Oops! I was going by the behaviour with just .split(), which I tried originally (but which does other whitespace too), and didn't realize the explicit .split(' ') would do what it does. Cool. :) -Peter From dsavitsk at e-coli.net Fri Sep 13 10:36:24 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 13 Sep 2002 14:36:24 GMT Subject: Newbie Looking for direction References: <0Akg9.3474$WV.3470@fe03> Message-ID: "Steve Holden" wrote in message news:0Akg9.3474$WV.3470 at fe03... > "mowestusa" wrote ... > > I have never programmed in a language before. > > I have developed complex databases with Access (Office 95 version) just > with > > the visual tools. > > > Languages are the only way. Graphical manipulations such as report > generation in Access are all very well, but you hit the limits sooner or > later. > > > I would like to learn a computer language or database as a hobby that I > > would use to keep track of things in my real job. > > I have worked through "Non-programmer's Tutorial for Python". > > I'm reading "Programming Python (First Edition, got cheap)" right now. > > > "Programming Python" is a good book, but its focus is perhaps a little > narrow. There are many online tutorials you can add to your book with, so > you shouldn't *need* to buy anything else. > > > Most of the programs that I would like to develop would be relatively > simple > > databases. > > Nothing wrong with that. You can create them visually if that's easier. You > just need to learn how to use DB-API modules. For Access I'd recommend > mxODBC, which doesn't have to be licensed for personal use. > * * * > Steve Holden also note that Access is easy to communicate with/control w/o installing 3rd party tools. You can easily use ADO, DAO, etc with python. see http://www.e-coli.net/pyado.html for help/examples. I will leave the debate over the merits of one method as opposed to another for elsewhere. -doug From martin at v.loewis.de Tue Sep 24 01:48:40 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Sep 2002 07:48:40 +0200 Subject: PyXML Building on OS X? References: Message-ID: Jarrett Wold writes: > extensions/expat/lib/xmlparse.c:3056: warning: `regparm' attribute directive > ignored I see. Please edit internal.h to replace #if defined(__GNUC__) #define FASTCALL __attribute__((stdcall, regparm(3))) #elif defined(WIN32) #define FASTCALL __fastcall #else #define FASTCALL #endif with #define FASTCALL > cc -L/sw/lib -bundle -flat_namespace -undefined suppress > build/temp.darwin-5.5-Power Macintosh-2.2/pyexpat.o > build/temp.darwin-5.5-Power Macintosh-2.2/xmlparse.o > build/temp.darwin-5.5-Power Macintosh-2.2/xmlrole.o > build/temp.darwin-5.5-Power Macintosh-2.2/xmltok.o -o > build/lib.darwin-5.5-Power Macintosh-2.2/_xmlplus/parsers/pyexpat.so > -flat_namespace > /usr/bin/ld: -undefined: unknown argument: -lbundle1.o > error: command 'cc' failed with exit status 1 Very strange. Can you please invoke cc -L/sw/lib -bundle -flat_namespace -undefined suppress build/temp.darwin-5.5-Power Macintosh-2.2/pyexpat.o build/temp.darwin-5.5-Power Macintosh-2.2/xmlparse.o build/temp.darwin-5.5-Power Macintosh-2.2/xmlrole.o build/temp.darwin-5.5-Power Macintosh-2.2/xmltok.o -o build/lib.darwin-5.5-Power Macintosh-2.2/_xmlplus/parsers/pyexpat.so -v on the command line, and report the output? Regards, Martin From dsavitsk at e-coli.net Mon Sep 23 13:11:05 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Mon, 23 Sep 2002 17:11:05 GMT Subject: Session handling References: Message-ID: "Andreas Ulbrich" wrote in message news:amn7dp$6cn$1 at mamenchi.zrz.TU-Berlin.DE... > beachboy wrote: > > Hi! > > Please can anyone help me. > > My problem: > > I'm trying to program a web application with python. This tool has to > > provide diffrent languages. The user has to choose the language at the > > beginning. So i have to save the information which language the user > > chooses. I think this is a perfect example for using sessions. > > The only problem is I've got no idea how to realise this in python. > > Please help me as soon as you can because I have to solve this problem > > very quickly. > > > > hoping to hear from you soon > > beachboy > > Whenever I need to write a web-application I do use jython and write > servlets. This combines the power of Servlet/JSP with the worlds best > programming language. > > a jython servlet would look like this: > > from javax.servlet.http import HttpServlet > > class MyServlet(HttpServlet) : > > def doGet(self, request, response) : > > session = request.getSession(1) > lang = session.getAttribute('language') > if not lang : > # initialise the session (i.e. choose language) > > # produce output suitable to lang > if lang == 'DE' : > print >> res.writer, "Hallo Welt!" > else : > print >> res.writer, "Hello World!" > > There are other solutions. I believe that Zope offers session-management > too. If the only state that needs to be maintained is a language variable, this seems like a lot of work when a cookie will work fine. -d From aleax at aleax.it Tue Sep 24 09:22:02 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 13:22:02 GMT Subject: list problem References: Message-ID: <_FZj9.158106$pX1.5692316@news2.tin.it> Duncan Booth wrote: > Alex Martelli wrote in > news:tCYj9.157570$pX1.5675986 at news2.tin.it: > >>> If you are going to use reduce, then you would be better off writing: >>> >>> import operator >>> reduce(operator.add, x) >> >> Maybe (marginally). But timing things is often a good idea: > > Apologies for not being clearer. I actually felt that using operator.add > read more cleanly than using a lambda. I should have made it more obvious > that was what I meant. I wouldn't particularly worry which is faster > unless one was actually proven to be a bottleneck, at which point the OP > might well find the best way to optimise would be to not end up with > nested lists in the first place. My apologies in return -- you're perfectly right in your overall attitude, and I even agree with you that lambda isn't clearest. I don't know why I focused on performance in answering this thread -- must have been on my mind for other reasons. I _do_ think that reduce(operator.__add__, ...) is the only really frequent use of reduce, with such dominance that it might even be worth having as a built-in -- clearest and fastest. It might even specialcase _strings_ in particular, turning the op into a ''.join in this case... just musing... But I did like the nested list comprehension better in this case as an issue of style, anyway. You DID write "If you are going to use reduce", being impeccable on this point too. So, sorry again for appearing to pick on your post for no good reason. Alex From carner at tscnet.com Sat Sep 14 15:12:15 2002 From: carner at tscnet.com (Richard Kessler) Date: Sat, 14 Sep 2002 12:12:15 -0700 Subject: Converting a string to time - simple task but don't know how to do it! Message-ID: <7A6D2E53461F2BF2.AC83A3D5E1A01468.48CC780BD6530537@lp.airnews.net> I have a string returned from a database expressing the time i.e. 2002-09-14 10:30:34. I need to compare this value to the current time to determine the amount of time elapsed between the two. I get the current time using time.time() but I cannot find a way to convert the string from the database into a time value (seconds from epoch) to do the simple subraction to find seconds elapsed. Help please...from anyone knowing how to do this simple task. Thanks very much in advance. Richard From pknotz at sandia.gov Thu Sep 26 13:56:45 2002 From: pknotz at sandia.gov (Pat Notz) Date: 26 Sep 2002 10:56:45 -0700 Subject: How do you pronounce "__" (double underscore)? Message-ID: <525eaba.0209260956.72bf6786@posting.google.com> @ = "at" ! = "bang" . = "dot" * = "star" Is there a short (one or two syllable) pronounciation for "__" (double underscore). "Underscore underscore" and "double underscore" are kind of long. Somthing like "splat"? Anyone? Pat From mikemccand at bigfoot.com Tue Sep 24 17:05:33 2002 From: mikemccand at bigfoot.com (Mike McCandless) Date: 24 Sep 2002 14:05:33 -0700 Subject: how to check if a function signature "matches" without calling the function? Message-ID: Does Python 2.2.1 make it possible for me to see some details about the expected arguments that a function takes, without actually calling the function? Specifically, if I have a function or method object, and I have a tuple + dict of arguments I'd like to apply it on, is there a function I can call that would check if the tuple + dict can be properly "coerced" to the formal parameters? Browsing through the Python source it looks like this capability is not cleanly factored out of the "ext_do_call" function in Python/ceval.c? Thanks!! Mike From gerhard.haering at opus-gmbh.net Thu Sep 5 03:17:41 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 5 Sep 2002 07:17:41 GMT Subject: newbie-question: Nested functions and variable scope References: <7a7157fd.0209041503.7b9a0f44@posting.google.com> Message-ID: Leonardo Boiko wrote: > Hi, I'm a Python newbie. ... and using something older than Python 2.2, it seems. > I'm writing a program that uses expat. Some code looks like this: > > def generate_main(filename="main.xml", (...)): > (...) > outfile = open (filename, "w") > in_reply = 0 # true if we are inside "reply" element > > def start_element(name, attrs): > if name == "reply": > in_reply = 1 > [...] > UnboundLocalError: local variable 'in_reply' referenced before > assignment - Python < 2.1 doesn't have nested scopes; you'd have to play tricks with lambda IIRC; but then, I consider Python < 2.1 obsolete - Python 2.1 has nested scopes, if the first import statement in a module is "from future import nested_scopes". - Python 2.2 and later always use nested scopes > If I put "in_reply" outside everything and use "global in_reply" > inside each nested function, it works, but that's evil! What would be > a better way of doing it? Just put a "from __future__ import nested_scopes" at the top of your module and it should just work. -- Gerhard From sross at connectmail.carleton.ca Wed Sep 18 21:37:55 2002 From: sross at connectmail.carleton.ca (Sean Ross) Date: 19 Sep 2002 01:37:55 GMT Subject: Splitting a list of strings References: Message-ID: Okay, then. For those still interested, here's several implementations of sieving, based on peoples suggestions, plus a sample time trial. The trial is on a file with over 8000 lines to process. class ARFF: "Holds the lines of a *.arff file" def __init__(self, filename): file = open(filename) self.__lines = file.readlines() file.close() # used by sieve2() def __classify(self, char): "Returns classification index for attributes, comments, and data" if char == "@": return "attr" elif char == "%": return "comm" else: return "data" # based on suggestion by Emile van Sebille def sieve(self): "Sorts lines into data, attributes, or comments" results = [[],[],[]] #[data, attributes, comments] for line in self.__lines: # classify line as attribute, comment, or data by testing first char results["@%".find(line[0]) + 1].append(line) # discard first and last attribute results[1] = results[1][1:-1] return results[:-1] # discard comments # based on suggestion by Alex Martelli def sieve2(self): "Sorts lines into data, attributes, or comments" results = {} for line in self.__lines: # classify line as attribute, comment, or data by testing first char results.setdefault(self.__classify(line[0]), []).append(line) # discard first and last attribute results["attr"] = results["attr"][1:-1] del results["comm"] # discard comments return results # my original solution augmented with suggestion by Anthony Tuininga def sieve3(self): "Sorts lines into data, attributes, and ignores comments" attributes = [line for line in self.__lines if line[0] == "@"] data = [line for line in self.__lines if not line[0] in ("%", "@") ] return data, attributes[1:-1] # using filters and lambda def sieve4(self): "Sorts lines into data, attributes, and ignores comments" attributes = filter(lambda line: line[0]=="@", self.__lines) data = filter(lambda line: not line[0] in ("%", "@"), self.__lines) return data, attributes[1:-1] # Emile's idea again, with a list comprehension def sieve5(self): "Sorts lines into data, attributes, or comments" results = [[],[],[]] #[data, attributes, comments] [results["@%".find(line[0]) + 1].append(line) for line in self.__lines] # discard first and last attribute results[1] = results[1][1:-1] return results[:-1] # discard comments # based on Mark McEachern's suggestion def sieve6(self): attribute = "@" comment = "%" attributes = data = [] for line in self.__lines: line = line.strip() if not line or line.startswith(comment): continue elif line.startswith(attribute): attributes.append(line) else: data.append(line) return data, attributes[1:-1] if __name__ == "__main__": import time arff = ARFF('./mushroom.arff') t0=time.time() data, attr = arff.sieve() t = time.time()-t0 print "sieve time: %r seconds" % (t) t0=time.time() result = arff.sieve2() t = time.time()-t0 print "sieve2 time: %r seconds" % (t) t0=time.time() data2, attr2 = arff.sieve3() t = time.time()-t0 print "sieve3 time: %r seconds" % (t) t0=time.time() data3, attr3 = arff.sieve4() t = time.time()-t0 print "sieve4 time: %r seconds" % (t) t0=time.time() data4, attr4 = arff.sieve5() t = time.time()-t0 print "sieve5 time: %r seconds" % (t) t0=time.time() data5, attr5 = arff.sieve6() t = time.time()-t0 print "sieve6 time: %r seconds" % (t) ==================================================== Trial Time: sieve time: 0.05000007152557373 seconds sieve2 time: 0.12999999523162842 seconds sieve3 time: 0.069999933242797852 seconds sieve4 time: 0.081000089645385742 seconds sieve5 time: 0.069999933242797852 seconds sieve6 time: 0.20000004768371582 seconds In case you're curious, I'm probably just going to use sieve3(). It's not much slower than sieve(), and it's very easy to understand what's happening without a lot of commenting. OK, so, there you are. Thanks to everyone for your time and suggestions, Sean Ross From gerhard.haering at gmx.de Tue Sep 10 12:46:30 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 10 Sep 2002 16:46:30 GMT Subject: Python iCalendar API? References: Message-ID: Erik Price wrote in comp.lang.python: > Is there a Python module that provides capability of processing files > in .ics (iCalendar) format? I found nothing concrete on Google or at > python.org ... Looks like there is: http://webcvs.kde.org/cgi-bin/cvsweb.cgi/kdepim/libical/src/python/ I don't know how easy it is to rip that out of kdepim. -- Gerhard From skip at pobox.com Mon Sep 9 17:29:28 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 9 Sep 2002 16:29:28 -0500 Subject: how to build wxPython w/ Sun's C++ compiler? Message-ID: <15741.4792.752356.107952@12-248-11-90.client.attbi.com> wxPython uses distutils to build. I'm trying to build it on a Solaris system using Sun's C and C++ compilers (cc & CC, respectively). When I execute python setup.py build it tries to use "cc" instead of CC to compile C++ code, with predictable results: running build_ext building 'wxc' extension cc -DNDEBUG -O -DSWIG_GLOBAL -DHAVE_CONFIG_H -DWXP_USE_THREAD=1 -Isrc -I/home/skip/local/SunOS/include/python2.2 -c src/helpers.cpp -o build/temp.solaris-2.8-sun4u-2.2/src/helpers.o -I/home/skip/local/SunOS/lib/wx/include/gtk-2.3 -I/home/skip/local/SunOS/include -DGTK_NO_CHECK_CASTS -D__WXGTK__ -D_REENTRANT -I/home/skip/local/SunOS/include/gtk-1.2 -I/home/skip/local/SunOS/include/glib-1.2 -I/home/skip/local/SunOS/lib/glib/include -I/usr/openwin/include cc: No input file specified, no output generated error: command 'cc' failed with exit status 1 How do I convince it to use CC for files with .cpp extensions. Thx, -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From see_reply_address at something.invalid Thu Sep 19 22:00:38 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 20 Sep 2002 14:00:38 +1200 Subject: Tkinter: scrolling the canvas items AND widgets References: <3d06fae9.0209191255.63def2eb@posting.google.com> Message-ID: <3D8A8146.3030506@something.invalid> jmdeschamps wrote: > This code lets me scroll the graphical items but the widgets stay put > using PythonWin 2.2.1 on Windows 2000 > > for i in range(1): > f=Entry(canvas) > f.place(x=10,y=10) I think you need to create a window item on the canvas, with the window attached to it, something like this : f = Entry(canvas) canvas.create_window(10, 10, window = f) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From ws at mystrobl.de Sat Sep 21 03:30:27 2002 From: ws at mystrobl.de (Wolfgang Strobl) Date: Sat, 21 Sep 2002 09:30:27 +0200 Subject: Nokia 3310 SMS Application, done:connecting to serial port(linux/win), done:reading some hex like \x00 . . ., problem:write/send command! noresponse References: <52facf1d.0209190533.3048e62c@posting.google.com> Message-ID: ptbjrii at hotmail.com (Polerio Babao Jr.II): >I tried almost three weeks writing or sending a command to the >cell-phone but this gives me no response. I'm talking here about the >nokia 3310 connected to my serial port. The command that I send is the >AT command. From my pyserial I made an initialization like this >ser=serial.Serial('/dev/ttyS1',19200) >ser.readline() >ser.write() >ser.read() > >When I connect to the port for the first time I get the ser.read() >output like this \x00\x0c I think. But that's two response is what I >get on my first connect. After that when I envoke ser.read() again, I >get nothing. Something like import serial ser=serial.Serial(0,19200,timeout=3) print ser.portstr ser.write("ATZ\r") print "got" line=ser.read(10) print line ser.close() worked on the first try on my w2k box, when connected to a Siemes S25 via COM1. I bet it will would with the Nokia, too, because "ATZ" is almost universally understood. :-) My wife had asked me to dump all her phonebook numbers from her handy for backup purposes. Siemens only sold an somewhat expensive program for the S25, which I didn't buy. A program that I've got with a newer S45 unfortunately didn't even recognize the S25. The following qick&dirty snippet did the trick, and it works with both the s25 and the s45. # Strobl 19.9.2002 $Id: s25.py,v 1.3 2002/09/21 07:16:12 cvsroot Exp $ # read phonebooks from Siemens S25 or S45 import serial,re def readuntilok(s): ol=[] while 1: c=s.read() if not c: break ol.append(c) ostring="".join(ol) if len(ol)>3 and ostring[-4:]=="OK\r\n": break return ostring def cmd(s,cmd): s.write(cmd+"\r") r=readuntilok(s) r=r.split("\n") for i in range(len(r)): r[i]=r[i][:-1] return r def showbook(ser,book): select= cmd(ser,'AT+CPBS='+book) if select[1]=="ERROR": print "Error in showbook" print return booksize=cmd(ser,"AT+CPBR=?")[1] print booksize siz=re.compile(r"\+CPBR: \((\d+)-(\d+)\)") von,bis= siz.match(booksize).groups() von=int(von) bis=int(bis) print "Phonebook",book for i in range(von,bis+1): buch=cmd(ser,"AT+CPBR=%d,%d"%(i,i)) if buch[1]!="OK": print repr(buch[1]) print ser=serial.Serial(0,19200,timeout=3) print ser.portstr ser.write("ATZ\r") print "sent" line=ser.read(10) print line typ=cmd(ser,"AT+CGMI")[1] print typ, typ=cmd(ser,"AT+CGMM")[1] print typ, typ=cmd(ser,"AT+CGMR")[1] print "Model",typ print "IMSI",cmd(ser,"AT+CIMI")[1] print "IMEI",cmd(ser,"AT+CGSN")[1] uhrzeit=cmd(ser,"AT+CCLK?") print "Uhrzeit",uhrzeit[1] booksstring= cmd(ser,"AT+CPBS=?")[1] print "Phonebooks",booksstring for b in re.compile(r'"\w\w"').findall(booksstring): print "----Now reading book",b showbook(ser,b[1:-1]) print cmd(ser,"ATZ") print cmd(ser,'AT+CPBS=SM') print "writable",cmd(ser,"AT+CPBW=?") print "Done" ser.close() ------------------------ >pythonw -u s25.py COM1 sent ATZ OK SIEMENS S45 Model 23 IMSI xxxxxxxxxxxxxxxxxx IMEI xxxxxxxxxxxxxxxxxx Uhrzeit +CCLK: "02/09/21,09:11:57" Phonebooks +CPBS: ("FD","SM","ON","ME","LD","MC","RC") ----Now reading book "FD" +CPBR: (1-10),20,16 Phonebook FD ----Now reading book "SM" +CPBR: (1-125),20,16 Phonebook SM '+CPBR: 1,"xxxxxxxxxxxxxx",129,"xxxxx!"' '+CPBR: 2,"xxxxxxxxxxxxxxxx",145,"xxxxx"' etc. ['ATZ\r', 'OK', ''] ['AT+CPBS=SM\r', 'OK', ''] writable ['AT+CPBW=?\r', '+CPBW: (1-125),20,(128-255),16', '', 'OK', ''] Done >Exit code: 0 -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From rjones at ekit-inc.com Sun Sep 1 07:51:22 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sun, 1 Sep 2002 21:51:22 +1000 Subject: ANN: New PEP Format: reStructuredText In-Reply-To: <200209012145.51274.rjones@ekit-inc.com> References: <200209012145.51274.rjones@ekit-inc.com> Message-ID: <200209012151.22766.rjones@ekit-inc.com> On Sun, 1 Sep 2002 9:45 pm, Richard Jones wrote: > On Sun, 1 Sep 2002 6:46 pm, Robin Becker wrote: > > In article , Richard > > Jones writes > > > > >This is done in the docutils sandbox under the richard/pythonpoint > > > directory. I had this working ages ago (back in March, I think) but > > > hadn't updated it when David merged the dps and restructuredtext > > > projects to form the docutils project. That's done now. > > > > > > > > > Richard > > > > So does this appear as a CGI somewhere or should I go ahead and make a > > working demo? > > No, there's no CGI. The pythonpoint script in the sandbox is a "working > demo". Pass it a rest file as a command-line arg, and it'll spit out > pythonpoint XML (read the example for limitations though). ps. yes, it should be possible to merge the processing into one tool that spits out PDF, but I simply didn't get that far back in March, and "make" did a pretty good job... I had a presentation deadline to meet, and rest/pythonpoint were a huge help in getting there. No polish though :) pps. not so sure about overcoming the limitations of the PDF layout - though again I really didn't have enough time when I wrote it to investigate Richard From skip at pobox.com Tue Sep 3 23:02:21 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 3 Sep 2002 22:02:21 -0500 Subject: Coredumps (Python 1.4) In-Reply-To: <3D7579F1.1090500@nospam.yahoo.com> References: <3D7579F1.1090500@nospam.yahoo.com> Message-ID: <15733.30653.991781.186828@12-248-11-90.client.attbi.com> Anton> ... I coredump on this line ever since I linked with Electric Anton> Fence memory debugging lib. Any ideas why? Not off the top of my head... Anton> This is with Python 1.4 on SCO. Any know issues with memory Anton> allocation there? I'm building 2.2 now, but it will take a while. Give up on 1.4. It took me awhile (an hour or so) several months ago to get Python 2.1 (I think) to build on SCO. You'll be better off solving 2.2 build problems than struggling with what might be a bug in 1.4. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From henrik.motakef at web.de Mon Sep 23 15:33:21 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 23 Sep 2002 21:33:21 +0200 Subject: Dynamic loading of modules References: Message-ID: <87sn00zeke.fsf@pokey.henrik-motakef.de> "Andreas Lydersen" writes: > Hi, > I'd like to load a set of modules from a directory. I have tried to use the > __import__(...) statement to do so, but with no success. > ? > The static approch works (of course), but the dynamic does not! > > static: > import plugins.Password > > dynamic atttempt: > __import__("plugins.Password") __import__ doesn't really import the module, it returns a module object. So do something like >>> pwd = __import__("plugins.Password") >>> pwd.spam() Spam! hth Henrik From tdelaney at avaya.com Wed Sep 25 20:09:52 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 26 Sep 2002 10:09:52 +1000 Subject: a python puzzle Message-ID: > From: Erik Max Francis [mailto:max at alcyone.com] > > Michal Wallace wrote: > > > Here's a python puzzle. Solve it and you win a prize. :) > > tr hokdrafwfezxtculyjqmbipsvHIFg importsysngadfzjehulvcwbxICSk > > I started by decoding the (obvious) Python source, which made the job > considerably easier. Trivially easy in fact - since it's just a substitution cypher, you've already got a lot of information just from the first line of python code - the first line obviously starts as import sys and cdr kmxhe, irwka he uhk(farhez.myaayrf, ihkjyr): ^^^ ^^ is trivially for kmxhe, irwka in uhk(farhez.myaayrf, ihkjyr): ^^^ ^^ which gives you a few more letters. In fact, by that stage you already have 12 out of 26 characters. I suspect it took Holger somewhat less than half an hour to solve ... 5 minutes at most, and most of that is writing the decryption code ;) Tim Delaney From tim.one at comcast.net Mon Sep 16 18:29:32 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 16 Sep 2002 18:29:32 -0400 Subject: Difflib question In-Reply-To: <886c5e4b.0209161208.25012958@posting.google.com> Message-ID: [Robin Siebler] > Is there a way to get difflib to output *only* the lines that are > different (instead of all of the lines)? Read the docs for Sequence_Matcher.get_opcodes(), and ignore 'equal' tuples. From aleax at aleax.it Thu Sep 26 10:00:50 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 14:00:50 GMT Subject: List/Tuple bug or feature? References: Message-ID: Dennis Lee Bieber wrote: > sismex01 at hebmex.com fed this fish to the penguins on Tuesday 24 > September 2002 03:12 pm: > >> It's one of python's features :-) >> >> For when you wanna write a long string, SQL for example: >> >> Query = "SELECT what, when, where, why " >> "FROM t1, t2, t2 " >> "WHERE t1.id = t2.id_t1 and t3.id_t2 = t2.id and t1.id_t2 = >> t3.id " "AND t1.answer = 'OK'" (Needs parenthese around it, or \ at line ends, of course). > What's wrong with... > > query = """select what, when, where, why > from t1, t2, t3 > where t1.id = t2.id_t1 > and t3_id2 = t2.id ...etc """ You can't intersperse comments in this way -- not a problem when the string is simple enough, but some SQL queries can be pretty complicated AND not all SQL dialects let you insert comments in the query itself. Alex From lozinski at openstepnews.com Mon Sep 16 18:41:14 2002 From: lozinski at openstepnews.com (lozinski at openstepnews.com) Date: Mon, 16 Sep 2002 15:41:14 -0700 (PDT) Subject: Python.jobmart.com Server Upgrade In-Reply-To: <20020916221626.13483.93466.Mailman@mail.python.org> Message-ID: <1020916154114.212AAC/w.lozinski@maya> The python jobmart now allows for full text searches of the embedded resumes. So hiring managers can find just the right person with whatever specialty skill is required. Your feedback is appreciated. Regards Chris 1-510-740-6486 lozinski at openstepnews.com lozinski at jobmart.com From kowk at earthlink.net Wed Sep 25 13:47:03 2002 From: kowk at earthlink.net (Kow K) Date: Wed, 25 Sep 2002 10:47:03 -0700 Subject: how to change font and its size in IDLE (in UNIX)? In-Reply-To: <200209250852.27535.mfranklin1@gatwick.westerngeco.slb.com> Message-ID: Hi Martin, your pointer was quite useful. Thanks -- Kow On Wednesday, September 25, 2002, at 01:52 AM, Martin Franklin wrote: > On Wednesday 25 Sep 2002 5:22 am, Kow K wrote: >> Hi all, >> >> I'm trying to figure out how to change the font and its size in IDLE. >> It's Courier in 10pt. I don't like Courier, and what's worse, >> 10pt is too small for me. I wish I could change it to Fixed 7x13. >> >> Any input will be appreciated. >> >> Kow > > Take a look here (from http://groups.google.com/advanced_group_search) > > > http://groups.google.com/groups?q=font+size+idle&hl=en&lr=&ie=UTF-8&scoring= > r&selm=3a942c61_4%40corp.newsfeeds.com&rnum=1 > > > Cheers > Martin > > -- > ### Python Powered Signature > I started writting this email on > Wed Sep 25 08:51:33 2002 > From joec at mill.co.uk Mon Sep 2 12:09:50 2002 From: joec at mill.co.uk (Joe Connellan) Date: Mon, 02 Sep 2002 17:09:50 +0100 Subject: compiling extensions on linux Message-ID: <3D738D4E.35B6C712@mill.co.uk> I'm trying to port an extension of mine from windows to linux and am not sure how to include the myExtension.def file in the compile - I'm using g++ eg if I use g++ -shared -o myextension.so it compiles fine but I get the following error when importing it into python >>> import myextension Traceback (most recent call last): File "", line 1, in ? ImportError: dynamic module does not define init function (initmyextension) >>> Thanks Joe From cnetzer at mail.arc.nasa.gov Wed Sep 25 19:58:01 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Wed, 25 Sep 2002 16:58:01 -0700 Subject: a python puzzle In-Reply-To: References: Message-ID: <200209252358.QAA25171@mail.arc.nasa.gov> On Wednesday 25 September 2002 16:26, Andy Salnikov wrote: > "Gary Herron" wrote in message > > The fact that this puzzle was easy to decrypt says something (good) > > about Python: > > C'mon, "the fact that this puzzle was easy to decrypt says" that > "encription" was really trivial. Yes, it was meant to be easy, because it is basically a slightly disguised SPAM message. There was nothing "pythonic" about this puzzle at all, except a rather routine piece of code. If I has bothered to 'decrypt' it, I would be pissed. (Reminds me of little Ralphie, in "A Christmas Story", waiting weeks to get his secret decoder wheel, only to find the secret message is 'Be sure to drink your Ovaltine') -- Chad Netzer cnetzer at mail.arc.nasa.gov From martin at v.loewis.de Thu Sep 19 02:45:26 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Sep 2002 08:45:26 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: Greg Ewing writes: > So, the only way to find out whether a particular > extension is safe to use in Stackless is to try > it. That is not true. It is more reliable to inspect the source code. In general, it is very easy to do so: if there are no callbacks to Python, the module is stackless-safe. > That's why I say that I would be nervous about > using Stackless. Not to say that would stop me > from using it, but I'd feel nervous while I was > doing it! :-) That is perfectly fine with me. The question is whether incorporation of Stackless Python in the core distribution would already make you nervous. I can see no rational reason for that. > Yes, I understand that, and I acknowledge that it > won't cause any harm to have Stackless in the core > if the Stackless stuff is switched off by default. It is better than that: it does not need to be "switched off". Even if switched on (at build time), it won't start copying slices of the stack. An application actively has to import one of the modules, and to call a function in those modules, before you need to get nervous. Regards, Martin From martin at v.loewis.de Wed Sep 4 03:09:50 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Sep 2002 09:09:50 +0200 Subject: Memory fault - core dumped while compiling 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> Message-ID: Andrew Koenig writes: > Looks like the same symptom I had. > > If you are using binutils 2.13, try going back to 2.12.1 and > see if that fixes the problem. Alternatively, use the system C compiler - Python does not support gcc on SCO, apparently (or else it would not try to pass -belf). It is probably easy to add gcc support - just adjust the OpenUnix fragments in configure.in to SCO. Regards, Martin From gmuller at worldonline.nl Mon Sep 2 11:18:47 2002 From: gmuller at worldonline.nl (GerritM) Date: Mon, 2 Sep 2002 17:18:47 +0200 Subject: Must have Python modules? References: <_THc9.42153$vY2.1039887@e3500-atl2.usenetserver.com> Message-ID: "Robert Oschler" schreef in bericht news:FCIc9.30407$FJ1.5585669 at e3500-atl1.usenetserver.com... <...snip...> I want to know what the other favorites are "out there". > > thx > win32com, HTMLgen I am still looking for a whois module, for ReverseNameLookup. Some snippets exist, so far I did not yet find a reliable and complete module. regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From Dick.Zantow at lexisnexis.com Wed Sep 18 12:31:59 2002 From: Dick.Zantow at lexisnexis.com (rzed) Date: Wed, 18 Sep 2002 12:31:59 -0400 Subject: Python doesn't suck! References: Message-ID: "Domenico" wrote in message news:e34e8ce6.0209180737.49868d9f at posting.google.com... > http://www.theperlreview.com/at_a_glance.html > > According to the most accurate algorithm, Python is the second > less-sucking language. Behind PHP (?!) if I read the charts right. Says a lot about the languages. -- rzed From cotabas at earthlink.net Sun Sep 1 15:46:05 2002 From: cotabas at earthlink.net (CotaBas) Date: Sun, 01 Sep 2002 19:46:05 GMT Subject: Executable Python Programs References: <1rtc9.108$LI2.7238@newsread2.prod.itd.earthlink.net> Message-ID: <18uc9.160$LI2.13183@newsread2.prod.itd.earthlink.net> "CotaBas" wrote in message news:1rtc9.108$LI2.7238 at newsread2.prod.itd.earthlink.net... Thank you, I will check the FAQ before I post again ;-) --------------------------- -CotaBas From loewis at informatik.hu-berlin.de Sun Sep 15 14:10:08 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 15 Sep 2002 20:10:08 +0200 Subject: Will xml.dom work with HTML docs? References: <877khntzvt.fsf@pokey.henrik-motakef.de> Message-ID: Henrik Motakef writes: > > if not is there a good parser module for HTML docs? > > See the htmllib module in the standard library. Alternatively, see PyXML. It parses an HTML document into a DOM tree. It does so by knowing the HTML DTD, ie. it silently inserts missing closing tags whereever needed. Regards, Martin From peter at engcorp.com Fri Sep 6 08:58:25 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Sep 2002 08:58:25 -0400 Subject: Zope Status? References: Message-ID: <3d78a657$1@news.sentex.net> Bo wrote: > I apologise if this isn't the proper forum to do this in. > > 1) Can anyone tell me roughly if\when Zope is moving to python 2.2? > > 2) Also any idea when they might release Zope 3? > > 3) Anyone close to the Zope team who is willing to shed some light on the > near future for things Zope? Very likely, going to http://dev.zope.org would answer these questions. From ahmad at NOSPAMbitbuilder.com Sat Sep 7 03:36:15 2002 From: ahmad at NOSPAMbitbuilder.com (Ahmad Baitalmal) Date: Sat, 07 Sep 2002 07:36:15 GMT Subject: Converting python object reference to int and back Message-ID: <3D79AC95.1000000@NOSPAMbitbuilder.com> Hi, I need to keep references to python objects in a tree control's item. The items can hold an integer as data. How can I get an id (pointer/reference) from a python object and then get that object back using that integer? -- - - -- ---- ----------------------------------------- --- -- - - *Ahmad Baitalmal*** *BitBuilder*** web: http://www.bitbuilder.com - - -- ---- -------------------------------------------------------------- --- -- - - From aahz at pythoncraft.com Sat Sep 21 12:32:37 2002 From: aahz at pythoncraft.com (Aahz) Date: 21 Sep 2002 12:32:37 -0400 Subject: Destructor never called ??? References: Message-ID: In article , Tim Peters wrote: > >Since you and I are approximately the only two people on the newsgroup >whose heads haven't exploded from trying to understand exactly what the >hell I'm talking about there , I think it's a Positive Good that >Neil skipped all the SCC complications. "Cycles and destructors: don't >even think about mixing them" is much easier to remember, and has never >done me any harm in real life. As long as you're talking about approximations, make it three people; I'm of the opinion that I understand roughly half of what you're talking about and if I count as half a person, you can just round up. I did try to understand the rest and my brain didn't explode, but it's probably leaking around the edges. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From prema at prema.co.nz Sat Sep 28 14:07:37 2002 From: prema at prema.co.nz (Mike) Date: Sat, 28 Sep 2002 18:07:37 GMT Subject: py2exe and a single exe file? References: <3D792351.3070008@motorola.com> Message-ID: Hi Stephen ! I've been doing some builds quite successfully using this script from the ASPN Cookbook. I name it Build.py and it sits in my tools folder. Take a copy and put it in with your source folder then run Build.py NewApp.py Hope it helps Best regards Mike Stephen Boulet wrote: > I'm trying to get py2exe to work for me, and I must be doing something > wrong. > > I have a script that uses easygui (which uses Tkinter) and Numeric. It > also imports a small module from the same directory that the script > resides in. > > I try building it like this: > > python setup.py py2exe -d N:\ -i easygui > > It builds and runs, but only with the other stuff in the build directory > with the generaged exe. The other stuff is: > > tcl directory containing tcl8.3 and tk8.3 directories > _numpy.pyd > _sre.pyd > _tkinter.pyd > multiarray.pyd > umath.pyd > > What I would like to accomplish is just having a single exe file lumping > everything together. Is this possible? > > -- Stephen > From manuel at hendel.net Tue Sep 17 04:39:58 2002 From: manuel at hendel.net (Manuel Hendel) Date: Tue, 17 Sep 2002 10:39:58 +0200 Subject: two or more whitespace regular expression? In-Reply-To: References: Message-ID: <20020917083958.GE23629@partagas.as.de.cw.net> On Sun, Sep 15, 2002 at 07:33:50AM +0000, Alex Martelli wrote: > import re > twoormorewhites = re.compile(r'\s\s+') ^ What is the "r" for? I tried to find something about this in the docs (Regular Expression HowTo , etc.) but I couldn't find anything. manuel -- When you teach your son, you teach your son's son. -The Talmund From Padraig at Linux.ie Mon Sep 9 06:13:05 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Mon, 09 Sep 2002 10:13:05 GMT Subject: tree data structure References: Message-ID: Padraig Brady wrote: > Raymond Hettinger wrote: > >> There are a number of ways to represent trees: >> -- instances of a treenode class >> -- a list of lists: [l0, [s2, [s0, [q1]], [s1,[q2]], [s3]]] >> -- or, my favorite, a dictionary of lists: >> >> original = [('L0','S2'), ('S2','S0'), ('S2','S1'), ('S1','Q2'), >> ('S0','Q1'), ('S2','S3')] >> >> tree = {} >> for key, value in original: >> tree.setdefault(key,[]).append(value) >> tree >> {'S2': ['S0', 'S1', 'S3'], 'S1': ['Q2'], 'S0': ['Q1'], 'L0': ['S2']} > > How would you iterate over the above? To complete this thread, Guido wrote an essay on how to manipulate graphs like that generated above: http://www.python.org/doc/essays/graphs.html P?draig. From whisper at oz.net Tue Sep 17 06:22:20 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 17 Sep 2002 03:22:20 -0700 Subject: More on Protecting Source Code In-Reply-To: <20020917062412.GA85457@hishome.net> Message-ID: Oh yeah, and my views of intellectual property seems to be a lot closer to the law of the land then yours. Dave LeBlanc Seattle, WA USA From cliechti at gmx.net Sun Sep 1 17:32:58 2002 From: cliechti at gmx.net (Chris Liechti) Date: 1 Sep 2002 23:32:58 +0200 Subject: del(instance.attr) -- no attribute References: Message-ID: Lee Harr wrote in news:un512ii7hjgq22 at corp.supernews.com: > Is this a bug? no >>>> class C: > ... a = 1 > ... >>>> c = C() >>>> c.a > 1 >>>> del(c.a) > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: C instance has no attribute 'a' >>>> hasattr(c, 'a') > 1 yes, but >>> del(C.a) works > I can see that maybe del(c.a) should not be allowed to delete > the attribute, but I think the error message is misleading. but the message is true. the instance has no attribute named "a", it's an attribute of the class "C". maybe "hasattr" is missleading to you, because it's showing class and instace attributes, including those of base classes. but deleting has to occour in the correct spot. chris -- Chris From SBrunning at trisystems.co.uk Thu Sep 19 10:52:13 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 19 Sep 2002 15:52:13 +0100 Subject: strong/weak - dynamic/static [Was: Getting started] Message-ID: <31575A892FF6D1118F5800600846864DCBD82B@intrepid> > From: Jacek Generowicz [SMTP:jacek.generowicz at cern.ch] > Could someone provide a serious reference (i.e. something which would > have gone through some sort of editorial/peer/technical review, rather > than someone's random opinions on the web) explaining or defining the > concepts of weak, strong, dynamic and static typing. Words can mean anything that you want them to mean, and I don't know if there is any such thing as definitive definitions of these words in this context. Having said that, I know what *I* mean when I use them - see . (Bottom of the page.) Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From tdelaney at avaya.com Mon Sep 23 20:05:09 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Tue, 24 Sep 2002 10:05:09 +1000 Subject: conditional expressions Message-ID: > From: Lulu of the Lotus-Eaters [mailto:mertz at gnosis.cx] > > "Delaney, Timothy" wrote previously: > |This type of thinking is one very good reason why bool() is > a Good Thing > |(TM). A large number (my guess is the majority) of Python > users do not know > |about operator.truth(). > > Well... Python users won't necessarily innately know about > bool() when > it is available in 2.3 (or 2.2.x). In either case, users No - however it will be documented as a core feature rather than a (to many) obscure library. For current uers, it will appear as a new feature (immediately bringing it to attention). For new users, it will be in an easily accessible part of the documentation - the same place that integers and other built-in types are discussed. Tim Delaney From mwh at python.net Fri Sep 27 06:21:39 2002 From: mwh at python.net (Michael Hudson) Date: Fri, 27 Sep 2002 10:21:39 GMT Subject: if...else on the same line? References: Message-ID: David Garamond writes: > i'm sorry for this terrorizingly basic question, but is it possible at > all to write an if ... else statement on a single line in python? No. easy-ones-are-the-quickest-ly y'rs M. -- > Emacs is a fashion statement. No, Gnus is a fashion statement. Emacs is clothing. Everyone else is running around naked. -- Karl Kleinpaste & Jonadab the Unsightly One, gnu.emacs.gnus From gua81 at XXXyahoo.com Mon Sep 30 21:01:55 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Tue, 1 Oct 2002 11:01:55 +1000 Subject: PROBLEM with form in cgi References: Message-ID: sorry it's "invalid syntax" not "syntax error" Cheers. "CheapSkate" wrote in message news:anas2k$i2b$1 at lust.ihug.co.nz... > HI, > I'm having problem trying to figure out what is wrong with my cgi script. > here's the code that's creating the problem in the apple.cgi > print """
""" > ^ > it keeps on saying invalid syntax in the action(as indicated) > and if I try to change it to this > print """""" > ^ > it gives the error at action. > Please help. From sismex01 at hebmex.com Thu Sep 26 18:24:10 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 26 Sep 2002 17:24:10 -0500 Subject: Question about select() Message-ID: Does select() work on bound sockets, to detect incoming connections? I'd like to be able to have a timeout when accepting connections from a server socket. Thanks! -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From max at alcyone.com Tue Sep 17 17:14:58 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 17 Sep 2002 14:14:58 -0700 Subject: CGI question References: Message-ID: <3D879B52.BD293951@alcyone.com> Ian Bicking wrote: > Look at cgi.FieldStorage. Something like: > > f = cgi.FieldStorage(keep_blank_values=1) > > Will save these values. (I don't know why it isn't set by default... > by > default you shouldn't throw information away, but FieldStorage does in > this case) It actually is not unreasonable. If form elements exist but are left blank, such as a text field, they will appear in the form submission even though you may not care about them. Since when you're receiving a form submission, presumably you know what elements were in the form, you always know what to look for and can simply default to something reasonable if it isn't present. Note that what he's trying for is something different than a mere blank value; a blank value would look something like `?blank=' whereas what he's talking about is `?blank'. I don't know offhand if keep_blank_values will accept this form; I'm hoping you tested it before suggesting it. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ It's like being on a diving board that you know is too high. \__/ Sade Adu Kepler's laws / http://www.alcyone.com/max/physics/kepler/ A proof of Kepler's laws. From cliechti at gmx.net Wed Sep 18 17:54:01 2002 From: cliechti at gmx.net (Chris Liechti) Date: 18 Sep 2002 23:54:01 +0200 Subject: Python GUI app to impress the boss? References: Message-ID: "Gray, Lee P." wrote in news:mailman.1032381445.13579.python-list at python.org: >> Boa is in fact quite a bit alpha-ish, but after you're >> used to the quirks and limitations, it is really great. >> Also note that you should use the version from CVS >> which is *far* more developed than the downloadable. > > Yeah, I tried to download from CVS, but being a complete noob > couldn't figure out how, short of tracking down and copying and pasting > every updated file. Any tips would be appreciated. you're on windows right? then grab http://tortoisecvs.sf.net and install the latest version. after that right click on an empty folder in the windows explorer and select "cvs checkout", copy and paste the "CVSROOT" in the dialog. you can find the cvsroot, or at least how it looks like on the "browse cvs" page that you have apparently found. the home of cvs is http://www.cvshome.org and these are interesting sites: http://www.loria.fr/~molli/cvs-index.html, http://cvsbook.red-bean.com/ chris -- Chris From robin at execulink.com Sat Sep 14 21:34:03 2002 From: robin at execulink.com (robin at execulink.com) Date: Sat, 14 Sep 2002 21:34:03 -0400 Subject: html template system? References: Message-ID: <0ro7ouskb8ctv6f846gb8cfpqtl5vs1avc@4ax.com> ":B nerdy" wrote: >what are good templating systems avaliable for python? You have so many options, documented here: http://www.python.org/cgi-bin/moinmoin/WebProgramming These include my Wasp. -- robin From teaandbikkie at aol.com Sat Sep 14 16:44:31 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 14 Sep 2002 20:44:31 GMT Subject: Skipping Parts of a For Loop References: Message-ID: <20020914164431.23208.00000400@mb-fp.aol.com> >> Is there a way to skip some parts in a for loop? >> >> >> for i in range(3): >> print "i before", i >> i=2 >> print "i after", i >> An alternative to Alex's great suggestion, you could use an if statement: for i in range(3): if 0 Message-ID: On Sun, 8 Sep 2002 01:47:12 -0400, "Wayne R" wrote: >This is a multi-part message in MIME format. Why? > >------=_NextPart_000_0039_01C256D9.B8CB5320 >Content-Type: text/plain; > charset="us-ascii" >Content-Transfer-Encoding: 7bit > > >I am trying to write a python program that will run as a deamon and >watch a file for data to arrive and then wake up and perform duties on >that data. I found ways to make a python program run as a deamon but I >am at a loss to find anything related to watching a file for data so >that it can then process the data. I didn't really want to do a sleep >loop or something like, I am sure there is a better way. > >Any ideas or links to more info? > Don't annoy people you want help from, for starters. What system are you targeting? (Outlook in the headers says you're on windows generating this abominable mix of actual message and useless cruft). >------=_NextPart_000_0039_01C256D9.B8CB5320 >Content-Type: text/html; WHY?!! Regards, Bengt Richter From benji_75 at hotmail.com Thu Sep 12 08:15:39 2002 From: benji_75 at hotmail.com (Ben Gerblich) Date: Thu, 12 Sep 2002 21:45:39 +0930 Subject: Fatal Python error: PyThreadState_Get: no current thread Message-ID: Hi All, My code has just started crashing. I get the message: Fatal Python error: PyThreadState_Get: no current thread Aborted (core dumped) Is there a way to turn on debug mode or something that will allow me to see where/why my app is crashing. "python2 -d main.py" does not shed any light. It seems as though the app crashes because of threads. I have found parts of my code that when commented out, the app does not crash. BUT, if i leave this code in, and put some 'print' statements above it, then just (eg)3 out of the 10 prints will execute before the app crashes. Thanks, Ben. Im using: Red Hat Linux 7.1 python2-2.1-5.i386.rpm python2-devel-2.1-5.i386.rpm python2-tkinter-2.1-5.i386.rpm python2-tools-2.1-5.i386.rpm wxPython-2.3.2.1-1-Py21.i386.rpm wxGTK-2.3.2-1.i386.rpm wxGTK-devel-2.3.2-1.i386.rpm _________________________________________________________________ MSN Photos is the easiest way to share and print your photos: http://photos.msn.com/support/worldwide.aspx From lee100 at sport.rr.com Sat Sep 21 10:03:13 2002 From: lee100 at sport.rr.com (Lee Gray) Date: Sat, 21 Sep 2002 14:03:13 GMT Subject: pyrhon and oracle References: <5b8834c2.0209201412.50e77861@posting.google.com> Message-ID: Satheesh Babu wrote: > cx_Oracle might be the *easiest* to use. I use DCOracle while working > with Zope, but for standalone development, cx_Oracle is tops. > > Download the driver from > http://www.computronix.com/utilities.shtml > > go to Python DB-API specs > http://www.python.org/topics/database/DatabaseAPI-2.0.html > > Here's an example using DB-API > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 > > vsb > http://vsbabu.org/ > I'm just looking into Python, so these articles don't mean much to me yet... Does all this mean that Python doesn't talk to an Oracle DB "out of the box"? For Windows, can Python use ADO? Thanks, Lee From aleax at aleax.it Sun Sep 15 12:59:12 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 15 Sep 2002 16:59:12 GMT Subject: Tkinter in PyRun_SimpleString(char* s) References: <_OWg9.109539$pX1.3874894@news2.tin.it> Message-ID: Torsten Mohr wrote: > Hi, > > thanks for that hint. > >> As you can see, the problem is with sys.argv, which you have >> not set. You can set it up from the Python code you execute, >> before you import Tkinter, or with C-API call PySys_SetArgv. ...which needs to be called AFTER Py_Initialize -- I think that may be your problem: > /* C code */ > Py_SetProgramName(argv[0]); > PySys_SetArgv(argc, argv); > > Py_Initialize(); > PyRun_SimpleString(script); > > Py_Finalize(); Try switching the 2nd and 3rd ones of these five calls. Alex From loewis at informatik.hu-berlin.de Thu Sep 26 05:27:42 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 26 Sep 2002 11:27:42 +0200 Subject: unicode woes References: Message-ID: Ulli Stein writes: > Some weeks ago the management decided to deploy unicode so that we can > handle every charset uniformly. The problem which showed at first: we > realized that we cannot change the encoding in site.py afterwards, i.e. we > have to specify the encoding all the way. You mean, every time? Not necessarily. If you want to write Unicode to a file, I recommend to use codecs.open. > It got worse and worse because > the unicode encoding spread like a virus through all the source code. > Simple Exceptions which we wanted to print to the console throw another > Exception: > UnicodeError: ASCII decoding error: ordinal not in range(128) I cannot understand this problem. I get >>> def foo(): ... raise Exception(u"\u20ac") ... >>> foo() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in foo Exception>>> So even though it doesn't print the Unicode string, it does not cause a UnicodeError, either. > Furthermore, in Python you have no way to detect, which encoding a > special unicode string atually is. We ended up having our own u() > function. What do you mean, 'actually'? A single Unicode string can be encoded in many encodings, e.g. u"Hallo" can be encoded in ascii, latin-1, koi-8r, or utf-8. Every Unicode string can be encoded in utf-8. > The problem with that: we have to pass _every_ string through > it. Ouch! Again, I cannot understand the problem. Can you please show a bit of code that demonstrates how you use that u() function, and what it does? > Now our source code is as ugly as our program is slow. Isn't there > another way? Not sure what problem you are trying to solve, so it is hard to tell whether there is another way to solve it. > When will the types string and unicode merged together like in Java? If > this is not changing and we do not find another way, we will have to port > _all_ source code to C++. Don't despair; I'm certain that there is an easier way. Try to follow the following principles: - Never mix byte strings and Unicode strings (unless the byte strings are restricted to bytes <127, perhaps). - In a Unicode application, convert all byte strings to Unicode as early as possible. - Convert all Unicode data back to byte strings as late as possible. - If you need to be sure that something can be printed for diagnostic output, use repr. - For normal output, use an codecs.StreamWriter. > def u(obj): I'm not quite sure what this u function is supposed to do. If this is meant to be an equivalent of str() which returns a Unicode object, I recommend that you implement this as def u(obj): try: return unicode(obj) except UnicodeError: return unicode(obj, getEncoding()) > encoding = getEncoding() > if encoding == None: > raise EncodingNotInitialized("There was no encoding defined previously.") This is quite inefficient. Why is it that no encoding could be defined previously? There is alway the system default encoding. Also, can't you arrange encoding to be global, and change every time the encoding changes? That would avoid the function call. > > if type(obj) == types.StringType: > return unicode(obj, encoding) I recommend to put the most frequent case first. I also recommend to avoid type tests. Instead, just invoke return unicode(obj, encoding) and catch the exception you get if that fails (TypeError) > elif type(obj) == types.UnicodeType: > # As we can't be sure what encoding the unicode object has we receive, > # we will simply re-encode it. > return unicode(obj.encode(encoding), encoding) What good does that do? You perform a roundtrip conversion, so that either fails (with a UnicodeError), or you get back the same object. I recommend to write return obj instead. If you really think you need the UnicodeError if the Unicode string cannot be encoded in encoding, write obj.encode(encoding) return obj That saves atleast one of the conversions. However, it is not clear to me why you need the UnicodeError at all. > elif type(obj) == types.IntType or type(obj) == types.LongType: > return unicode("%d" % obj, encoding) > elif type(obj) == types.FloatType: > return unicode("%f" % obj, encoding) > elif type(obj) in [ types.TupleType, types.ListType, types.Dic > tType, types.DictionaryType ]: > return unicode(str(obj), encoding) These can be summarized as return unicode(obj) It is not clear why you special-case None; if this is a string conversion function, returning None is just as surprising. Instead, I would expect u(None) to work as >>> unicode(None) u'None' > >>> "????%s"%unicode("???", "iso8859-15") > Traceback (most recent call last): > File "", line 1, in ? > UnicodeError: ASCII decoding error: ordinal not in range(128) What do you expect to happen? You have a byte string, and you want to insert a unicode string. Those two cannot be mixed unless you convert one form to the other. For that, you need to know what encoding to use; Python uses the default encoding, which only converts ASCII in the standard installation. If you follow the suggestion to never mix byte strings and Unicode strings, this would not happen. Regards, Martin From max at alcyone.com Fri Sep 20 23:30:08 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 20 Sep 2002 20:30:08 -0700 Subject: Python about file I/O References: Message-ID: <3D8BE7C0.80853072@alcyone.com> Ken wrote: > 1.) How do you list the filenames within a given directory so user can > choose which file to open? Use os.listdir. > 2.) How do you ensure the program doesn't crash if I specify a > filename to > open but the file doesn't exist? (I.E. how to check if file exist > before > opening the file?) It doesn't "crash," it throws an error. Simply catch the error and do something meaningful: try: inFile = file('soandso.txt') ... except IOError: print >> sys.stderr, "Couldn't open file" -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Woman was God's _second_ mistake. \__/ Friedrich Nietzsche The laws list / http://www.alcyone.com/max/physics/laws/ Laws, rules, principles, effects, paradoxes, etc. in physics. From max at alcyone.com Tue Sep 24 05:05:14 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 24 Sep 2002 02:05:14 -0700 Subject: instance creation References: <265e380f.0209240052.4c2988f3@posting.google.com> Message-ID: <3D902ACA.1188B5AE@alcyone.com> Paul MG wrote: > - Having two constructors seems to be illegal - or at least the second > overwrites the first. That's correct. Python does not allow overloading functions with the same name but different argument lists. > - Assigning to 'self' in the load method seems to really not work! Indeed, and you shouldn't have expected it to. self is a variable like anything else, and in Python, variables are merely bindings, not reseatable references. Assignment just rebinds the name, it doesn't affect the bound object. > - Putting the create() method outside of the class works fine - but I > want it to be a class method on Appointment, goddammit!:) Is there no > way to do this? Later versions of Python have a staticmethod function for this. You'd use it like this: class C: def f(x): # note, no self argument ... f = staticmethod(f) This allows f to be called as C.f or even c.f, if c were an instance of C. > Any help would be appreciated, basically i am looking for the python > idiom to do this, as my C++ and Smalltalk idiom's clearly aren't in > the grain of the language! Depending on your tastes, a module function might make more sense. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ I wish you well but / Right now I'm just bitter \__/ Chante Moore Alcyone Systems' CatCam / http://www.catcam.com/ What do your pets do all day while you're at work? Find out. From jylimd at yahoo.com Wed Sep 18 17:30:54 2002 From: jylimd at yahoo.com (J. Li) Date: Wed, 18 Sep 2002 17:30:54 -0400 Subject: [Help]: mailbox classes Message-ID: Hi, I am trying to extract a message from a unix mailbox file. Python does provide few classes for easy and uniform access. So it says! After having read the libiary references, I went nowhere. Can anyone give me an example as how to use these mailbox classes and what is it relationship with email.message classes. thanks From sholden at holdenweb.com Thu Sep 12 00:04:39 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 12 Sep 2002 00:04:39 -0400 Subject: [FEEDBACK] Is this script efficient...is there a better way? References: <4ZRf9.1782$Lg2.248733@news2.news.adelphia.net> <3hSf9.168947$l_4.98525@atlpnn01.usenetserver.com> <8PSf9.1796$Lg2.257378@news2.news.adelphia.net> Message-ID: <_oUf9.170870$l_4.126599@atlpnn01.usenetserver.com> "Bob X" wrote ... [ ... ] > > > Thank you very much...your shorter script did work. The keywords are all > "normal" english words that would not have any special characters. I > only added a re.IGNORECASE (since case doesn't matter to me) after a > quick search of the python docs. > Was there any significant difference in the timings for the two different methods, and how does the number of different keywords affect the timings? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From peter at engcorp.com Mon Sep 2 12:16:34 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Sep 2002 12:16:34 -0400 Subject: Newbie's unsurmountable pb with IO stream trick References: Message-ID: <3D738EE2.3A8756D@engcorp.com> Spendius wrote: > > I'm about to give up learning Python because I've met > insurmountable problems. I'm a newbie just having begun > teaching myself this language a few days ago, and I > already stall against unsolvable (at least to me) issues: > so could you please help me and *show me* I'd be wrong > giving up ? > > I tried to rewrite something I wrote in Java, trying to > communicate with an OS process (SQL*Plus in this occurence), > but big time bucked against > - the lack of methods of the so-called 'file objects' (if > there was an equivalent to java.io.InputStream.available() !) > - the fact you don't declare variables: you just assign > values to them => I immediately hit against the 'global' > keyword issue (rather a global mess) and gave up... Sounds like you're creating a few problems for yourself all at once here. For one thing, why are you trying to use global variables at all when the original code was in Java, which doesn't have such things? And what does not declaring variables have to do with the "global keyword issue" (whatever that is)? If you have an SQL database to access, why not use one of the standard DBAPI modules to get to it? You might be doing a lot of extra work when you don't have to. If you're just learning Python, you've taken on a fairly complicated and large task right at the beginning. Why not spend some time learning to use it for simpler tasks before you jump in head first? Finally, from the description of what you're trying to do with InputStream.available(), you might have a few options including opening the file in non-blocking mode or using the select module, or something from the win32all package if you're running under Windows (you didn't say). -Peter From max at alcyone.com Fri Sep 20 01:48:13 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 19 Sep 2002 22:48:13 -0700 Subject: newbie seeks advise. References: <77c84db2.0209192137.51167ebb@posting.google.com> Message-ID: <3D8AB69D.52A45E72@alcyone.com> akirasugiura wrote: > I've been learning python for about a month. I had no prior knowledge > of programming. > > My question is, I have a tuple which is, data = (69, 40, 74, 41, 56, > 57, 38, 58, 26, 55). How I can make a function that picks up a largest > number > from this "data" tuple. If "data" was a 'List' I would be able to > use "sort" but since sort doesn't work with tuple. I am stuck here. You could always convert the tuple to a list with the list function: data = (69, 40, 74, 41, 56, 57, 38, 58, 26, 55) dataAsList = list(data) and then do what you intended. Note that there is a max function which already exhibits this behavior (which will work on any sequence): largest = max(data) You could always do it manually; walk through the sequence, and keep a tally of the largest one you've seen so far. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Man is preceded by forest, followed by desert. \__/ (graffiti written during French student revolt) Bosskey.net / http://www.bosskey.net/ A personal guide to online multiplayer first person shooters. From nospam at horvath.com Fri Sep 27 22:02:37 2002 From: nospam at horvath.com (Bob Horvath) Date: Sat, 28 Sep 2002 02:02:37 GMT Subject: combining mailbox and email modules References: <1fj6jb2.62mx08f47amsN%fgranger@alussinan.org> Message-ID: <158l9.428169$kp.1216679@rwcrnsc52.ops.asp.att.net> Fran?ois Granger wrote: > Bob Horvath wrote: > > >>The problem is that it looks good to me. I've played around with >>it, and if I take out the MIME gunk (It actually is a Klez virus), >>it parses ok. > > > I have had difficulties with the handling of multipart message with the > email package. I did not found a solution yet. > Actually I did get it working by using the HeaderParser class in Parser.py. It doesn't parse the body. All I needed was the headers, and be able to recreate the body. This one worked great. From syver-en+usenet at online.no Sat Sep 14 07:17:05 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Sat, 14 Sep 2002 11:17:05 GMT Subject: Calling Python from C# - please help References: <6de16ac9.0209130508.5d1b56c6@posting.google.com> <0iCg9.2350$Ee4.6516@news-server.bigpond.net.au> <3D82FA5B.3050003@mxm.dk> Message-ID: Max M writes: > Mark Hammond wrote: > > > I have no examples of this, but I should. I'm co-authoring a .NET > > book which is nearly out :) - > > > That sounds great. I enjoyed the win32 book, and still use it as a > reference. > > Are you by any chance still developing Pyhton .NET, or has it > completely stopped? > > regards Max M Now that J# (Java .NET) has been released, I was wondering about the possibility of compiling Jython with the MS J# compiler to create a Jython .NET. Has anyone considered the possibility? -- Vennlig hilsen Syver Enstad From printers at sendme.cz Wed Sep 11 09:14:30 2002 From: printers at sendme.cz (A) Date: Wed, 11 Sep 2002 15:14:30 +0200 Subject: Paradox table Message-ID: <3D7F5DD6.8814.1363983@localhost> Hi, Is there a module for reading Paradox database (.DB) files with Python? I need to run the script under Linux, so I can not use ODBC. Any suggestion would be appreciated Thanks for help Ladislav I look forward to hearing from you soon. Best regards, Ladislav Blazek( Mr.) BMA TRADING Ltd. email: export at sendme.cz email2: export at bmatrading.com Fax:/Tel +420 506 447921 Tel:+420 506 447920, +420 602 849309 From mertz at gnosis.cx Thu Sep 26 21:11:05 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Thu, 26 Sep 2002 21:11:05 -0400 Subject: indexing and searching pdf files References: Message-ID: Rajarshi Guha wrote previously: |I have a load of pdf files and I would like to index them so that I can |serach them for keywords. I was thinking of using pdftotext to generate |the textfile and then create the index from that. |My question - is there already something like this with python? |Another question which is slightly off topic is, does anybody know of any |articles/pages that talk about indexing text files efficiently - index |generaion algorithms etc? Carlo Bifulco created a program called PdfSearch do just what you want. Its homepage is at: http://pdfsearch.sourceforge.net/ I have not tried the latest version, but I remember the project because Carlo uses my indexer.py module as part of his project. In terms of my indexer.py module, I wrote an article about full text indexing at: http://gnosis.cx/publish/programming/charming_python_15.html This was extended to cover XPATH indexing of XML documents in: http://gnosis.cx/publish/programming/xml_matters_10.html The latter isn't your interest, but in concept it is somewhat similar to Carlo's extension. -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From sabineellen at aol.com Fri Sep 27 19:57:22 2002 From: sabineellen at aol.com (Sabineellen) Date: 27 Sep 2002 23:57:22 GMT Subject: windows xp command prompt References: Message-ID: <20020927195722.29739.00005390@mb-mb.aol.com> restarting the machine in windows xp includes all windows and programs shutting down and restarting anew; he did that already From pyth at devel.trillke.net Wed Sep 4 20:22:33 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 5 Sep 2002 02:22:33 +0200 Subject: Python parser for cross references In-Reply-To: ; from howard@eegsoftware.com on Wed, Sep 04, 2002 at 10:34:08PM +0000 References: Message-ID: <20020905022233.P3893@prim.han.de> Howard Lightstone wrote: > I would like to use Source Navigator to (re)examine a largish application. > It parses the C, C++,assembly and Python jobs I am working right now and > has outputs that *statisfy* the naive QA people who think tables and > diagrams are *documentation*. > > The Python parser for it was written by Thomas Heller (thank you very > much). > > However, it does not emit cross reference information. Of course, I first > thought "why not just add one?". I can see why Mr. Heller did not. > > A cross reference parser has to track scope....and determine function calls > within argument lists.....and track just 'name' references which are passed > around...and on and on. > Is there a (C) parser for Python around which does a "just-good-enough" > parsing job to be adapted for this? I don't think you could do this with a parser. It requires getting type information and that is only possible if you run a program. You probably would have to trace a program to get information which names refer to which object type(s). regards, holger From skip at pobox.com Thu Sep 26 11:49:01 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 26 Sep 2002 10:49:01 -0500 Subject: off topic -- spam assassin In-Reply-To: <200209261407.g8QE76Wo028975@ratthing-b246.strakt.com> References: <200209261407.g8QE76Wo028975@ratthing-b246.strakt.com> Message-ID: <15763.11373.573554.830138@12-248-11-90.client.attbi.com> Laura> On the advice of several of you here, I installed spam assassin, Laura> and had a pleasant six months of nearly spam free mail. Thank Laura> you, each and every one of you who recommmended it. Alas, the Laura> spammers have got smarter, and I am now getting 25+ pieces of Laura> spam that aren't caught by spam assassin every day again. :-( Laura> What's new for our side of the arms race? Laura, The tension between spammers and the people who develop spam-fighting software can be likened to an arms race. It's fairly clear the spammers use tools like SA to make their mailings more likely to get through. If you installed SA six months ago, I'd suspect you're running 2.20 or thereabouts. Since then 2.31 and 2.41 have been released. You might want to upgrade. Skip From fredrik at pythonware.com Thu Sep 5 13:27:16 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Sep 2002 17:27:16 GMT Subject: str() of a tuple References: Message-ID: Douglas Zongker wrote: > Why, oh why does the str() of a container use the repr()s of the > objects inside? This seems to violate what the docs claim str() does > -- "return a nicely printable representation of an object." "an object" refers to the container itself, not the objects in the container. From bokr at oz.net Wed Sep 4 21:58:50 2002 From: bokr at oz.net (Bengt Richter) Date: 5 Sep 2002 01:58:50 GMT Subject: Memory fault - core dumped while compiling python 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> <3D765A05.6030004@nospam.yahoo.com> <3D768753.8030302@nospam.yahoo.com> <3D76A139.1030304@nospam.yahoo.com> <3D76BC56.7020503@nospam.yahoo.com> Message-ID: On Wed, 04 Sep 2002 19:07:18 -0700, Anton Graph wrote: >Bengt Richter wrote: >> On Wed, 04 Sep 2002 17:11:37 -0700, Anton Graph wrote: [...] >> >> How about >> cc -v >> ? >> >> what does >> >> which cc >> >> give you? And >> >> which cc | xargs -ld >> ? > > > >$ which cc >/bin/cc >$ /bin/cc -v >Usage: cc [ options ] files ... >$ which cc | xargs -ld >xargs: d is not a valid number of lines, must be a positive integer > Oops, sorry, that should have been which cc | xargs ls -ld Regards, Bengt Richter From mhouck at eecs.tufts.edu Thu Sep 12 12:48:53 2002 From: mhouck at eecs.tufts.edu (mike) Date: Thu, 12 Sep 2002 16:48:53 GMT Subject: dynamic includes from classes... Message-ID: Okay two questions... First, is there a better way than exec to dynamically include a module? i.e. importvar = "foo" exec("from %s import %s" % (importvar, importvar)) And, if there isn't, I tried the above code in a class that I wrote. But, it seems that the imported class foo is only visible inside the class, if I send importvar to another function and do a = eval(importvar)(args) #btw is there a better way to do this too? it gives the error "Foo" undeclared. Any suggestions on how to do this whole thing better, or how to make the exec include global? mike From jdavis at empires.org Tue Sep 24 21:37:09 2002 From: jdavis at empires.org (Jeff Davis) Date: Wed, 25 Sep 2002 01:37:09 GMT Subject: readlines() and "binary" files References: <3d90cacf$0$30457$afc38c87@sisyphus.news.be.easynet.net> Message-ID: <9r8k9.46422$V7.11170409@twister.socal.rr.com> I think readlines() is just a shortcut for a very common task. Since your task isn't quite as common, I think it would be a better idea to use read() to read the whole thing, splitting the lines up by the 0x0d 0x0a pair (CR NL). If it's a really large amount of data you can try to process it in chunks. Regards, jeff davis Justin wrote: > Hi, > > I have excel data with occasional multi-line fields, > which when dumped to CSV translates to embedded CR's > within a line, whereas the records/lines themselves > are delimited by the CR+NL pair (this is MS-land). > What I'd like to do is read those files and split every > line apart on the semi-colon field separator. But it > seems that whether the file is opened as text or not, > (x)readlines() still considers the lone CR as a line > delimiter and so not all my lines end up with the same > number of fields as they should. Is there a way to handle > this, or is readlines just not meant to work with anything > but proper text files? > > f = open('testdata.csv','rb') > for line in f.xreadlines(): > fields = line.split(';') > print len(fields) # should always be the same value From whisper at oz.net Tue Sep 17 03:31:49 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 17 Sep 2002 00:31:49 -0700 Subject: More on Protecting Source Code In-Reply-To: <3d86b4a0$0$23173$afc38c87@news.optusnet.com.au> Message-ID: > > Python may be easy to use, but if it's also easy to steal > software written > > in it, that's an impediment to it's being widely used in commercial > > products, especially shrink-wrapped products. Perhaps that's a > reason why > > there seems to be so few commercial products in Python, beyond > those that > > are fairly closely licensed and/or have substantial parts of the app > written > > in C/C++. > > but if you're worried about protecting your IP, then wouldn't your package > be under a closed license? > > > I suppose one solution is to modify the Python interpreter with > different > > op-codes and that ought to make it somewhat painful for the average > hacker. > > A better solution is to make a .pyc file approximately as hard > as a binary > > .exe file to decompile - however that could be done. > > From what I've read of that thread, the gist of it was > > "once its released, a determined person can, to some extent get your code" > > and > > "Security through obscurity is no security against a determined attacker" > > So, someone who is willing to hacka nd hack and hack away at your > code, can > get at it, and this is true for things coded in assembler, C, Python or > Befunge. Most people aren't determined attackers, they're simply > Joe Average > who needs to get a job done. > > An operating system is a complex beast, compiled into machine > code its even > more complex, how many people out there are using an unlicensed copy of > Windows or Office? they didn't decompile, that would take skill, they just > copied it bit for bit and posted the registration key. > > Do a very very simple risk analysis. Who is your target audience, what is > the price of your software, will people bother going through your > bytecode, > or will they just post the registration key to a website? Will stolen > software lead to a loss in revenue - or will those pirate users be people > who would never have bought it in the first place? (yes, the pirate users > are annoying, and you would feel ripped off, but OTOH you haven't lost > money, and you've gained a bunch of users) > > Steven Well, I think of it this way: machine coded binaries are more like a 128 bit key and Python is more like a 40 bit key. I agree that nothing is safe from reverse engineering; it's a matter of how much pain and money it takes to unscrut the inscrutable. Python could do better - how I'm not totally sure. Dave LeBlanc Seattle, WA USA From jdavis at empires.org Tue Sep 24 05:31:37 2002 From: jdavis at empires.org (Jeff Davis) Date: Tue, 24 Sep 2002 09:31:37 GMT Subject: how to build up a guest book with python ? References: Message-ID: http://python.org/doc/current/lib/module-cgi.html might help you out. It's not the best tutorial out there I'm sure, but hopefully it can get you started. Regards, Jeff black wrote: > > Hi,all~ > > I'm learning python for almost 1 month and decide to build up a guest > book with it, but I really know nothing about web programming, any > tutorials for me please ? > > > > --------------------------------- > Do you Yahoo!? > New DSL Internet Access from SBC & Yahoo! From grabiller at 3dvf.net Wed Sep 25 12:03:35 2002 From: grabiller at 3dvf.net (Guy Rabiller) Date: Wed, 25 Sep 2002 18:03:35 +0200 Subject: Newbie References Question -> Exemple References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> <3d91d2cf$0$1484$79c14f64@nan-newsreader-01.noos.net> <3d91d7ab$0$13192$79c14f64@nan-newsreader-03.noos.net> Message-ID: <3d91de4e$0$1485$79c14f64@nan-newsreader-01.noos.net> Sorry I should have said: Thanks to Gustavo, not sismex :-) -- guy rabiller 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net Guy Rabiller wrote: > Ok I solved it, thanks to sismex. > > If I want to change a coordinate, I have yo write: > > p[0][:] = [5,5] > > and not > > p[0] = [5,5] > > I understand that in the first case, the reference pointed ( via > dictionary ) by p[0] is lost, a new value is created and rebinded to > p[0], so quad and p[0] are not synchonised anymore. > > In the second case, the reference pointed by p[0] is updated with a > new value. p[0] and quad are still synchronised. > > Is my understanding correct ? > > Thanks a lot to all. > > > Guy Rabiller wrote: >> Ok, >> >> thanks for your answers, I understand now that a variable name is >> 'just' a name in a dictionary, and not a container. >> >> What I want to do is simple, and I suppose that this is my 'way of >> thinking' regarding Python that is wrong. >> >> I have a list of points, and a list of polygons that should contain >> 'references' to points. >> >> So for me: >> -> points list: >> p = [] >> p.append([0,0]) >> p.append([0,1]) >> p.append([1,1]) >> p.append([1,0]) >> -> polygon: >> quad = [] >> quad.append(p[0]) >> quad.append(p[1]) >> quad.append(p[2]) >> quad.append(p[3]) >> >> But now, if I change the coordinate of one point: >> p[0] = [5,5] >> I will have: >>>>> p >> [[5, 5], [0, 1], [1, 1], [1, 0]] >> but: >>>>> quad >> [[0, 0], [0, 1], [1, 1], [1, 0]] >> >> For me the quad list of point is not 'updated' with the change of one >> of its point. >> >> What I want to do is that, quad keeps a list of 'references' to >> points coordinates. >> Then if I change one point coordinates, the change is reflected in >> the quad list of points. >> >> I have no clue how to do this. >> >> >> Guy Rabiller wrote: >>> Hi, >>> >>> let say I have: >>> i1 = 1 >>> i2 = 2 >>> and >>> p = [i1,i2] >>> >>> How can I have: >>> p=[*i1,*i2] >>> rather than >>> p=[**i1,**i2] as it is curently ? >>> >>> ( Sorry for this nasty hybrid syntax ) >>> >>> Textualy, how if I want that p[0] refere to the 'i1' container, and >>> not to the refererence it contains ? >>> >>> What I want is that if now I set: >>> i1 = 4 >>> that automaticaly: >>> p -> [4,2] >>> and not keeping [1,2] >>> >>> Thanks in advance. From sebastian.wangnick at eurocontrol.int Mon Sep 2 03:44:27 2002 From: sebastian.wangnick at eurocontrol.int (Sebastian Wangnick) Date: 2 Sep 2002 00:44:27 -0700 Subject: stylistic question -- optional return value References: Message-ID: <30292041.0209012344.ab2d4@posting.google.com> > Andrew Koenig wrote: > > > Hans> Still, I believe that rewriting the function (or splitting it up) > > > Hans> might be a better idea. <0.3 wink> > > > > I've considered that, and I really don't think it works in this case. > > > > You might think of the optional result as being similar to debugging > > information -- you really don't want to put the code that getnerates > > debugging information into a separate function, because then it will > > surely diverge from the code about which it is providing the informatio If I understand you correctly then you'd like to be able to provide, under circumstances determined by your function, additional information back to your caller. Additionally, an "innocent" caller should not be bothered with the additional information. Why not create an additional optional *argument* (say a list, or a function), to which you optionally provide your debug information? def func(x,y,debug=None): if debug!=None: debug("func") return x+y e = [] z = func(3,4,lambda info:e.append(info)) print z,e Regards, Sebastian PS: I learned Python only last week, so take my posting with a grain of salt. From ahmad at NOSPAMbitbuilder.com Mon Sep 9 07:06:01 2002 From: ahmad at NOSPAMbitbuilder.com (Ahmad Baitalmal) Date: Mon, 09 Sep 2002 11:06:01 GMT Subject: xml.minidom is stripping out my CRLF's in attrib values!! Message-ID: <3D7C80C4.9070204@NOSPAMbitbuilder.com> Hi, I'm parsing an XML string which has nodes, the nodes has attributes, the attribute values have CRLFs. The string has the CRLFs before I parse, After I create my DOM the values come back with no CRLFs at all! What's the deal, is there a setting I can set? Thanks -- - - -- ---- ----------------------------------------- --- -- - - *Ahmad Baitalmal*** *BitBuilder*** web: http://www.bitbuilder.com - - -- ---- -------------------------------------------------------------- --- -- - - From martin at v.loewis.de Fri Sep 6 12:11:10 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Sep 2002 18:11:10 +0200 Subject: help needed creating xml document with xml.dom References: Message-ID: Brian Lalor writes: > Good morning, all. Several times, now, I've used xml.dom.minidom to create > raw XML documents, but I don't think I've ever really done it the "right" > way. I think that trying to create valid XML documents with DOM is inherently wrong. Use print statements instead. > I blame that on my seeming inability to find documentation on the > "right" way to do it in Python, or in any language, for that matter. > Pointers to said documentation are welcomed. :-) Unfortunately, the DOM does not provide a way to create a Document with an internal subset. > Using minidom, I cannot seem to get either the namespace or doctype > to print out. Adding namespaces should be possible; adding a DOCTYPE declaration is not. > # is this the right way, instead of directly importing xml.dom.minidom? > DOM = xml.dom.getDOMImplementation() Yes, that's correct. > index_page.documentElement.setAttribute('xml:lang', 'en') > index_page.documentElement.setAttribute('lang', 'en') If you want namespaces, you should use the namespace API: setAttributeNS, createElementNS. > Is this a bug in minidom, or (more likely) am I doing something wrong? Call it a bug. It's really a feature missing in DOM - while it *may* work for an external DTD, there is no way to get it work with an internal subset. Again, using plain print statements will be easier. Regards, Martin From duncan at NOSPAMrcp.co.uk Mon Sep 2 04:47:05 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 2 Sep 2002 08:47:05 +0000 (UTC) Subject: Executable Python Programs References: <1rtc9.108$LI2.7238@newsread2.prod.itd.earthlink.net> Message-ID: Gerhard H?ring wrote in news:mailman.1030908003.28854.python-list at python.org: > My personal opinion is that py2exe/Installer/etc. are for > intermediate/advanced Python programmers. The reason is that it's > sometimes difficult to fix the dependencies manually, if these tools are > unable to hunt them down automatically for you. I think you may be overstating the difficulty here. The vast majority of programs run through py2exe etc. with no problems at all. I can only think ot a couple of times that I have even had to think about the dependencies: I had a case recently with py2exe was when it found some extra dependencies that I didn't want: I was using jabber.py which for not very good reasons imports site.py which indirectly imports a whole load of stuff such as tkinter. Explicitly excluding site.py fixed this. Admittedly it took me a little while to track down which import was the problem. An option to py2exe to dump out why it decided to pull in each module would have been helpful. The only time I had trouble with an import that wasn't being found was when I used py2exe on a program using PIL. PIL demand loads a lot of converters for different graphics formats which was beyond py2exe's capabilities. Explicitly importing all the formats I wanted into the main program fixed that one. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From jb at cascade-sys.com Sat Sep 14 04:09:34 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Sat, 14 Sep 2002 01:09:34 -0700 Subject: threads or queue for this task References: Message-ID: <3D82EEBE.5050405@cascade-sys.com> robin at execulink.com wrote: >I wish to have a server continually cycle (until interrupted by >keyboard, signal, or whatever). It needs to perform several (say 6) >different tasks, each of which may take significantly different >lengths of time to perform. > I can think of two approaches that may solve your problem. It sounds like you have a single stream of input requests which you wish to distribute among multiple service threads. One way is to have your main thread read the input stream, parse the incoming commands and then launch a separate thread to handle each incoming request. It would NOT wait for the threads to complete or otherwise try to regulate the number of threads. Plus side is maximum parallelism. Down-side is if commands come too fast you may exceed the maximum thread count and the app will fail. Another alternative is to launch a single thread for each of your service routines. Also create a Queue for each thread and have the threads each read commands from their respective queue. Service threads would loop forever, reading and executing commands. Main program reads input as before and feeds commands to the appropriate thread VIA each threads' respective queue. Again, the main thread does NOT wait for any threads to complete. Thus it will service requests as fast as possible using exactly N helper threads. The degree of parallelism 0..N would depend on the input commands arrival rates. If this is unacceptable -- if you need to enforce some ordering on the execution of commands, then things get a lot more complicated. E.g., if you want to dispatch N commands, one to each helper thread, and then wait for them all to complete before doing anything else -- you need to consult the "threading" module (the one following "thread" in the library ref). If it's truly that simple (read N and then execute N in parallel) your main program could enforce this discipline, adding a threading.Semaphore() object to synchronize on the completion of all N threads. Threading includes various synchronization functions that allow you to do this and more. E.g., you also could do things like maintain a maximum of M[i] parallel instances of thread i (more than 1 but a different limit for each command). If the threads themselves access common data structures then you need to synchronize their access so they don't garble the results. The thread module itself has a locking mechanism that's sufficient for implementing regions of mutual exclusion. If you're new to concurrent programming then you may need to consult some books on the subject, as it's a bit tricky. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From eugene1977 at hotmail.com Sun Sep 15 21:31:01 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Mon, 16 Sep 2002 01:31:01 +0000 Subject: two or more whitespace regular expression? References: Message-ID: thank you that worked.. From manuel at hendel.net Wed Sep 25 03:54:16 2002 From: manuel at hendel.net (Manuel Hendel) Date: Wed, 25 Sep 2002 09:54:16 +0200 Subject: problems defining an empty list In-Reply-To: <200209250040.12209.shalehperry@attbi.com> References: <20020925070654.GB57911@partagas.as.de.cw.net> <200209250040.12209.shalehperry@attbi.com> Message-ID: <20020925075416.GC57911@partagas.as.de.cw.net> On Wed, Sep 25, 2002 at 12:40:12AM -0700, Sean 'Shaleh' Perry wrote: > it sounds like you have a hidden piece of whitespace. Perhaps the code is > indented when it should not be? If the code is not in a loop, class, if > structure, etc then it should not be indented. Actually it is in a ... structure. [....] # empty list for lines per all domains linesperdomains = [] for domain in domains: # empty list for lines domainlines = [] for neededline in neededlines: if domain == neededline[0]: domainlines.append(neededline) print len(domainlines) # empty list for lines per domain linesperdomain = [] linesperdomain = [domain, domainlines] print linesperdomain [....] This ist just a part of the script. Manuel -- I am two with nature. -Woody Allen From phr-n2002b at NOSPAMnightsong.com Sun Sep 29 23:19:33 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 29 Sep 2002 20:19:33 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> Message-ID: <7xelbcgo56.fsf@ruckus.brouhaha.com> "Chris Gonnerman" writes: > > >>> (.70 * .05) + .000000001 > > > > rounds to the right thing. > > Cool. Now PROVE that's right in all cases. What do you mean by "right"? What do you mean by "all cases"? > Like I said, decimal arithmetic is STILL the only choice. I'm not convinced decimal arithmetic is "right in all cases". From mhammond at skippinet.com.au Wed Sep 18 08:57:58 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 18 Sep 2002 12:57:58 GMT Subject: PythonScript References: Message-ID: Gavin Tomlins wrote: > Greetings, > > Firstly apologies if this is slightly out of the scope of the mailing list > but after searching the web, archives I've been unable to find references of > PythonScript with its use with the activescript engine. I own March Hammond > & Andy Robinson's Python Win32 Programming and have gone over there chapter > of active scripting though there examples focus more on python and > activescripting via the command shell. > > The problem I seem to be hitting is utilising python in applications that > embed an ActiveScript Engine. To date I am unable to get one python script > to execute. Other languages vbscript, jscript,perl etc, work in the same > environment so I'm left wondering if its a configuration problem or > something that I might be overlooking. If anyone could give me pointers, > url's, snippets etc. it would be interested. The product I specifically > having problems is FinalBuilder (http://www.atozedsoftware.com) though have > seen this problem in other applications as well. > It is likely to be some strange interaction between PythonScript and the host. Python works fine in all MS hosts, and quite a number of 3rd party ones. What application is it? Mark. From arosado at softhome.net Sat Sep 7 20:59:15 2002 From: arosado at softhome.net (Andres Rosado) Date: Sat, 07 Sep 2002 20:59:15 -0400 Subject: Why Python? Message-ID: <5.1.0.14.0.20020907205827.00bbcc38@mail.softhome.net> At 05:51 AM 9/4/2002 -0400, you wrote: >I just begun to learn how to program. And I choosed Python for >doing that. surfing around the web i found an article about this >language, they said it's the ideal language for beginners to the >world of programming. and i admit it, the syntax is very clear making >the code very readable, i learn easily the concepts of programming >and i soon wrote some nice programs. but since i finished my >newbie-tutorial, i am wondering about one question: is it worth to go >deeper into python? i talked to a friend of mine, he told me that i >should try php.. >what should i do?? ^_^ in other words: what is python good for? >why should i continue with python? Just because you learn something new, it doesn't mean that you should forget the "old". Programming languages are like tools for a carpenter. Just because you got a new hammer, you don't have to throw the old screwdriver. Each programming language has it advantages and disadvantages. Learning to use them correctly is as important as learning one. Definetely I won't use Python for any low level programming (C is great here). But for other areas, Python can shine like (or better) than others. Also, I started recently to learn PHP. I wouldn't recommend it for a newbie at programming, unless he/she needs it. ----------------------------------- Andres Rosado Email: andresr at despammed.com ICQ: 66750646 Homepage: http://andres980.tripod.com/ Life is a yo-yo, and mankind ties knots in the string. From jwbaxter at spamcop.net Sat Sep 7 12:08:08 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Sat, 07 Sep 2002 09:08:08 -0700 Subject: None or 0 References: Message-ID: In article , Michael Stroder wrote: > >>> repr(0 or None) > 'None' > >>> repr(None or 0) > '0' > >>> repr('' or None) > 'None' > >>> repr(None or '') > "''" > >>> > > Is it guaranteed to work like this or should that be avoided? It seems very convenient to implement or (and and) by returning the first object which decides the answer. My guess is that enough people are counting on the behavior that even if the underlying hardware or implementation language were to shift enough to make this implementation quite inconvenient, it would nonetheless survive. Having said that, I tend not to like counting on it, because it stretches the extra-Python definition of the operators quite a bit. Particularly on the "and" side: >>> print 5 and 1 1 Go into (English-speaking) classrooms, and you're going to hear chants of "5 and 1 is 6" not "5 and 1 is 1". --John From TomH at optiscan.com Tue Sep 3 20:31:48 2002 From: TomH at optiscan.com (Tom Harris) Date: Wed, 4 Sep 2002 10:31:48 +1000 Subject: Excluding specific module from import Message-ID: <7796875278c69d8306b528e1cf7d4f5d3d755479@optiscan.com> Greetings I have a library that tries to import mx.DateTime, and on failure uses its own implementation. The problem is that I am building an executable, and I would much rather not have mx imported, as it increases the size of the executable by a factor of two. Could someone give me an idea how to frob things so that import will fail to import mx.*. I cannot frob sys.path as it only contains a path to site-packages. I would sooner not rewrite the library. Thanks Tom Harris, Software Engineer Optiscan Imaging, 15-17 Normanby Rd, Notting Hill, Melbourne, Vic 3168, Australia email tomh at optiscan.com ph +61 3 9538 3333 fax +61 3 9562 7742 This email may contain confidential information. If you have received this email in error, please delete it immediately,and inform us of the mistake by return email. Any form of reproduction, or further dissemination of this email is strictly prohibited. Also, please note that opinions expressed in this email are those of the author, and are not necessarily those of Optiscan Pty Ltd. From marklists at mceahern.com Fri Sep 13 22:45:14 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 13 Sep 2002 21:45:14 -0500 Subject: Restricting methods in derived classes In-Reply-To: Message-ID: [Huaiyu Zhu] > But seriously, your first solution actually contains all I needed. Here's > what I adopted in the end: [snip] > Maybe there is a simple way to wrap up restrict() in a metaclass, so that > instead of restrict(foo) we can say class foo(dict, restricted): ... > I'm still not so used to metaclasses to figure that out, however. I like the solution you adopted and I used it to simplify (imo, anyway) my metaclass approach (see below), which I still prefer, but I'm not quite sure why. One thing I don't quite understand is why you'd want to bother messing with magic methods at all (which you're _common suggests you do). That seems like an invitation to disaster--but that's a statement that comes more from ignorance than experience on my part. In the code I attached, if you wanted to suppress magic methods, you would simply remove the is_magic test. Thanks for this opportunity to improve my understanding of metaclasses. Cheers, // mark #!/usr/bin/env python import inspect def make_undefined(cls, attr): def undefined(self, *args, **kwargs): msg = "'%s' object has no attribute '%s'" % (cls.__name__, attr) raise AttributeError(msg) return undefined def is_magic(attr): prefix = suffix = '__' return attr.startswith(prefix) and attr.endswith(suffix) class Restricted(type): common = ['__class__', '__defined__', '__dict__', '__doc__', '__getattribute__', '__init__', '__new__'] def __new__(cls, classname, bases, classdict): defined_key = 'defined' defined = classdict.get(defined_key, []) + Restricted.common # If a non-magic attribute from any base class is not in common or # defined, hide it with a method that raises a descriptive # AttributeError (mimicking Python). for base in bases: for k, v in inspect.getmembers(base): if not is_magic(k) and k not in defined: classdict[k] = make_undefined(cls, k) return type.__new__(cls, classname, bases, classdict) class RestrictedDict(dict): __metaclass__ = Restricted defined = ['put', 'get', 'keys', 'items', 'values'] f = RestrictedDict() print f.keys print f.keys() f['a'] = 'b' print f.keys() try: f.clear() except AttributeError: pass print f.keys() - From aleax at aleax.it Tue Sep 17 18:39:06 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Sep 2002 22:39:06 GMT Subject: Will "Python in a Nutshell" be too short? References: Message-ID: Steve Holden wrote: ... > I wil be very surprised if Alex' book does not become the canonical > reference for the language, since his treatment is exceptionally thorough > and (even for him) more than usually precise. Thanks -- I do appreciate this. >> packages that had to be left out of the book's 380 pages (htmllib, >> telnetlib, urllib2, CongigParser, unittest, tkinter, xml, etc.). >> > They clearly aren't "Essential" :-) It's a hard judgment in each and every case. I think unittest is (is it ever!), for example -- somebody not quite as keen on testing might not agree with me though. > It's far too late into the production process for such pleas to be > effective, no matter what the individuals concerned may think of their > merits. It's probably at the printers already... Not quite (and the delays of SOME technical reviewers in supplying the technical reviews MIGHT be part of it... hint, hint...), but it IS in the final-editing stage. Alex From imbosol at vt.edu Mon Sep 30 14:03:43 2002 From: imbosol at vt.edu (Carl Banks) Date: Mon, 30 Sep 2002 14:03:43 -0400 Subject: rank-0 arrays? References: <3d988160.79509684@news> Message-ID: brobbins333 at shaw.ca wrote: > In Numeric Python, what are rank-0 arrays? > Must not arrays have at least 1 dimension? Well, in mathematics, a rank-0 array is a scalar, which is considered a degenerate array. The reason rank-0 arrays exist is because there are some operations that produce arrays of various rank depending on the rank of the operands, and in many cases these operations can produce arrays of rank 0. For example, consider cartesian tensors, which can be represented by Numeric arrays. Cartesian tensors have an operation called inner product, which multiplies a rank-n tensor by a rank-m tensor to produce a tensor of rank abs(n-m). (I'm probably simplifying this too much.) Anyways, suppose you want the inner product of two rank-1 tensors (i.e., vectors). The result is a rank-0 tensor, i.e., a scalar. Another example is a trace operation, which takes a tensor of rank n, and produces a tensor of rank (n-2). The trace of a rank-2 tensor is, as with matrices, a scalar. Evidently, Numeric supports rank-0 arrays to allow these operations to be done consistently, without special exceptions to handle degenerate cases. However, IIRC, it is good advice not to play around too much with rank-0 arrays in Python. They should be converted to regular Python floats if you're going to do something non-Numeric with them. -- CARL BANKS http://www.aerojockey.com From jkraska at san.rr.com Sat Sep 28 00:11:05 2002 From: jkraska at san.rr.com (Courageous) Date: Sat, 28 Sep 2002 04:11:05 GMT Subject: What does Python fix? References: Message-ID: >I'm curious to read a bit more about why Tim Peters (and presumably >others) think that Lisp-inspired languages (even non-prefix ones) are >doomed to eternal obscurity. Would anyone care to comment and/or give >me some pointers to commentary on the subject? Shrug. Lisp trades one form of complexity for another. By reducing the solution to a universal grammar, they increase the symbolic load on the user, who is awash in a page full of very similar symbols. This is intimidating in particular to novices, for whatever reason, who are instantly alienated. Without sweeping in novices, you lack a grass roots movement, and without a grass roots, a language is dead. The parts of lisp that really matter to the community have since been adopted in part by many other languages. Lisp is dead. Long live Lisp. C// From mcherm at destiny.com Tue Sep 17 12:58:59 2002 From: mcherm at destiny.com (Michael Chermside) Date: Tue, 17 Sep 2002 12:58:59 -0400 Subject: Q: handling exceptions References: Message-ID: Karsten Weinert wrote: > The problem is: how can I access the > message string of the exception? Does this help? Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> def raiseit(): raise Exception, 'This is the message string' >>> try: raiseit() except Exception, s: print "Message is '%s'." % s Message is 'This is the message string'. >>> -- Michael Chermside From duncan at NOSPAMrcp.co.uk Tue Sep 24 05:07:31 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 24 Sep 2002 09:07:31 +0000 (UTC) Subject: Three dumb questions (ordered by dumbness descending) References: Message-ID: Thorsten Kampe wrote in news:amnvit$7kqdt$1 at ID- 77524.news.dfncis.de: > 1. Why is 'zip(zip(x)) != x' (should be the same because it's the > transposed) Because zip(x) doesn't transpose x. BUT, zip(*x) does transpose x. So the question is what zip(*zip(*x)) does? >>> x = [(1, 2), (3, 4), (5, 6)] >>> x == zip(*zip(*x)) 1 Provided x is a list of tuples, and you expand the list into separate arguments when calling zip, it is indeed its own inverse. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From bloke at ii.net Sat Sep 28 02:42:42 2002 From: bloke at ii.net (Rob Hall) Date: Sat, 28 Sep 2002 14:42:42 +0800 Subject: urllib2.urlopen(req).info() object References: Message-ID: <3d954f50$0$11909@echo-01.iinet.net.au> I used ClientCookie. Rob. eli li wrote in message news:an3fhi$3jr$1 at news.iucc.ac.il... > The call "urllib2.urlopen(req).info()" returns an object similar to the > dictionary, but it can have muliple values for some key. For example: > > Content-Type: text/html > Set-Cookie: A=M > Set-Cookie: WEBTRENDS_ID=192.168.120.21 > Set-Cookie: SINFO=ca9e > Via: 1.1 colosus1 (NetCache NetApp/5.3R2D4) > > How can I retrive all values related to 'Set-Cookie' key? > > From sholden at holdenweb.com Thu Sep 26 08:40:19 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 26 Sep 2002 08:40:19 -0400 Subject: Getting started References: <3D920950.323B25B3@alcyone.com> Message-ID: "James J. Besemer" wrote in message news:mailman.1033012423.27861.python-list at python.org... > [attempts to be "WORTHY" enough ...] > You can lead a pig to pearls.... > > Regards > but-you-can't-stop-it-being-a-swine-ly y'rs - steve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From bdesth at nospam.free.fr Sun Sep 8 23:09:34 2002 From: bdesth at nospam.free.fr (laotseu) Date: Sun, 08 Sep 2002 23:09:34 -0400 Subject: Why Python? References: <4f49d232.0209050418.7668c21@posting.google.com> <3D77FB95.3070300@nospam.free.fr> Message-ID: <3D7C10EE.3000509@nospam.free.fr> Skip Montanaro wrote: [snip] > Alas, to even get to a phone screen these days, it appears you need "at > least five years experience" with a buzzword language on your resume. In > most cases, neither Lisp nor Python qualify. > Which would make me laugh it wasn't true :( laotseu From edwardam at interlix.com Sun Sep 22 23:10:42 2002 From: edwardam at interlix.com (Edward Muller) Date: 22 Sep 2002 20:10:42 -0700 Subject: Python HTTPSConnection/HTTPResponse Problem References: <9abedeb.0209212200.5c669a50@posting.google.com> <9abedeb.0209221343.74d27ad1@posting.google.com> Message-ID: <9abedeb.0209221910.7fb75f6f@posting.google.com> I *think* I found the problem. Using m2Crypto and urllib I was able do process the transaction through Authorize.net's ADC Direct Response mechanism and it *looks* like their server replied first with a .. HTTP/1.1 100 Continue and then with a ... HTTP/1.1 200 OK I don't know if this is valid or not (and I sent the same info to Authorize.net). Maybe someone else with more HTTP knowledge will know. I'd be willing to test any patches or provide more data if anyone is interested in looking at this. Thanks, Edward Muller edwardam at interlix.com (Edward Muller) wrote in message news:<9abedeb.0209221343.74d27ad1 at posting.google.com>... > I thought I had posted this already, sorry if it sorta doubles. > > I can't use python 2.2, the latest I can use is python 2.1 because in > the end this will be done with zope and zope currently only supports > python 2.1.3 and earlier. > > And yes, my python is SSL enabled. > > Gerhard H?ring wrote in message news:... > > * Edward Muller [2002-09-21 23:00 -0700]: > > > I am trying to use HTTPSConnection and HTTPResponse objects [...] > > > > Is your Python SSL-enabled? Check with: > > > > import socket > > hasattr(socket, "ssl") > > > > Which version of Python are you using? Be sure to use at least version > > 2.2, as it contains many SSL-related bugfixes. > > > > -- Gerhard From chris.walsh at real-sense.com Wed Sep 11 12:28:59 2002 From: chris.walsh at real-sense.com (Chris Walsh) Date: 11 Sep 2002 09:28:59 -0700 Subject: Getting __builtins__ into my local dictionary Message-ID: <1691b372.0209110828.31501d82@posting.google.com> Hi All, I know this may sound like I am repeating a much discussed topic but I want to create a multiple environments within the one Python interpreter so that each envronment contains it's own local defs and attributes but also understands functions such as str() (e.g. contains __builtin__ module). This is how I think I should do it: ================START=OF=CODE================ PyObject *pMyMod = PyModule_New("unique000"); PyObject *pMyDict = PyModule_GetDict(pMyMod); PyDict_SetItemString(pMyDict, "__builtins__", PyEval_GetBuiltins()); PyObject *pResultT; pResultT = PyRun_String("dir()\n", Py_eval_input, pMyDict, pMyDict); DumpAndRelease("dir()", pResultT); pResultT = PyRun_String("dir(__builtins__)\n", Py_eval_input, pMyDict, pMyDict); DumpAndRelease("dir(__builtins__)", pResultT); =================END==OF=CODE================ The results I get from my Dump module (which just throws out the contents of pResultT) is: ================START=OF=DUMP================ dir() List of 3 items: ['__builtins__', '__doc__', '__name__'] dir(__builtins__) List of 37 items: ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'popitem', 'setdefault', 'update', 'values'] =================END==OF=DUMP================ But... if I do a "dir(__builtins__)" from the Python interpreter there are 118 items (not 37) including amongst other stuff, the str() function. How do I create my own module/dictionary which contains the __builtin__ module which contains all the handy functions that "dir(__builtins__)" shows up from the interpeter? Kind Regards, Chris. From g_will at cyberus.ca Fri Sep 20 13:50:01 2002 From: g_will at cyberus.ca (Gordon Williams) Date: Fri, 20 Sep 2002 13:50:01 -0400 Subject: httplib 'getaddrinfo failed' Message-ID: <026b01c260ce$24e23850$7507e640@wnt20337> Hi All, I recently got a DSL line to connect to the internet and my code is now broken. Could this be due to the DSL being different from a dialup connection? I'm using python 2.2 on W2000. This is the traceback from the 2.2 httplib: Traceback (most recent call last): File "G:\Python Files\Mutual Fund Updater\GetPrice.py", line 103, in ? f = u.open(url) File "G:\PROGRA~1\PYTHON22\lib\urllib.py", line 178, in open return getattr(self, name)(url) File "G:\PROGRA~1\PYTHON22\lib\urllib.py", line 288, in open_http h.putrequest('GET', selector) File "G:\PROGRA~1\PYTHON22\lib\httplib.py", line 452, in putrequest self.send(str) File "G:\PROGRA~1\PYTHON22\lib\httplib.py", line 394, in send self.connect() File "G:\PROGRA~1\PYTHON22\lib\httplib.py", line 362, in connect for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): IOError: [Errno socket error] (2, 'getaddrinfo failed') This is the traceback from the httplib in CVS that I got today. Traceback (most recent call last): File "G:\Python Files\Mutual Fund Updater\GetPrice.py", line 103, in ? f = u.open(url) File "G:\PROGRA~1\PYTHON22\lib\urllib.py", line 178, in open return getattr(self, name)(url) File "G:\PROGRA~1\PYTHON22\lib\urllib.py", line 292, in open_http h.endheaders() File "G:\PROGRA~1\PYTHON22\lib\httplib.py", line 695, in endheaders self._send_output() File "G:\PROGRA~1\PYTHON22\lib\httplib.py", line 581, in _send_output self.send(msg) File "G:\PROGRA~1\PYTHON22\lib\httplib.py", line 548, in send self.connect() File "G:\PROGRA~1\PYTHON22\lib\httplib.py", line 516, in connect socket.SOCK_STREAM): IOError: [Errno socket error] (2, 'getaddrinfo failed') Same problem. Any ideas? I'm using Sympatico high speed edition which was developed by Efficient Networks Inc. - if that is any help. Regards, Gordon Williams From maxm at mxm.dk Mon Sep 2 08:46:20 2002 From: maxm at mxm.dk (Max M) Date: Mon, 02 Sep 2002 14:46:20 +0200 Subject: Must have Python modules? References: <_THc9.42153$vY2.1039887@e3500-atl2.usenetserver.com> Message-ID: <3D735D9C.9060607@mxm.dk> Robert Oschler wrote: > I want to know what the other favorites are "out there". win32all (if os in windows), mx*, PIL, reportlab, Nummeric + the standard library :-) regards Max M From martin at v.loewis.de Sat Sep 21 06:56:57 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Sep 2002 12:56:57 +0200 Subject: Embedding Python in C++ and get rid of it again References: Message-ID: Manuel Klimek writes: > I'm coding on xpermud, a scriptable mud client. > This one features multiple scripting languages > (perl and python at the very moment). For problems like this, it is not that helpful if you report what your program does, but instead, how you have organized your program. Like: - I have a Solaris 8 32-bit binary foo, which I generated with gcc 2.95.2. - I also have linked libpython22.a to that binary. - I have compiled the bar.so extension module - when I try to import bar, I get the error message "foobar not found" > So why does python want to have "hard"-exported symbols in .so > libraries? I don't understand the question. What is a "hard"-exported symbol, and why do think Python wants it? Also, why do you think any of the Python symbols interfere with Perl? > Special question: Is there a different way to > get the python modules find the symbols they > need, some magic internal undocumented python > function we could call on the C++ side...? What symbols are you referring to? Regards, Martin From duncan at NOSPAMrcp.co.uk Tue Sep 3 05:05:33 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 3 Sep 2002 09:05:33 +0000 (UTC) Subject: string reading bug in ActiveState Python 2.2 ? References: <3D74757D.1010405@molgen.mpg.de> Message-ID: Axel Kowald wrote in news:3D74757D.1010405 at molgen.mpg.de: > I'm using ActiveStates Python 2.2.1 under win2000 to read in the > attached text file and it seems that python is only reading part of the > string. After > > fp = open("bla.txt") > z = fp.read() > print len(z), z > > I see that only 11 of the 15 characters have been read. I know they are > non-printable characters, but that shouldn't matter, should it ? Using > another python on one of our unix machines everything works as expected > and all 15 chars are read in. Is that there something special about > windows that I should know, or is this a bug in ActiveStates Python ? Python is doing exactly what you asked it to do. Please read the documentation for the 'file' builtin (of which 'open' is an alias): '''Modes 'r+', 'w+' and 'a+' open the file for updating (note that 'w+' truncates the file). Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files (else it is ignored). If the file cannot be opened, IOError is raised. If mode is omitted, it defaults to 'r'. When opening a binary file, you should append 'b' to the mode value for improved portability. (It's useful even on systems which don't treat binary and text files differently, where it serves as documentation.)''' Windows is a system that differentiates between binary and text files, so without the 'b' in the mode argument you are asking the system to read the file in text mode. In text mode Windows will drop carriage return characters when followed by linefeed, and will stop reading when it hits a control-Z character. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From martin at v.loewis.de Mon Sep 16 11:58:51 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Sep 2002 17:58:51 +0200 Subject: Mutable Stings References: Message-ID: "Griebel, Peer" writes: > So my question: Is this correct - or did I overlook something? You are not overlooking anything: Your analysis is correct, the code is wrong. Feel free to submit a patch to SF. Regards, Martin From rnd at onego.ru Tue Sep 3 13:30:57 2002 From: rnd at onego.ru (Roman Suzi) Date: Tue, 3 Sep 2002 21:30:57 +0400 (MSD) Subject: more Re: Peculiar ImportError traceback In-Reply-To: Message-ID: On Tue, 3 Sep 2002, John J. Lee wrote: BTW, I had something similar with different modules: Python 2.2.1 (#1, May 21 2002, 09:12:04) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import email >>> email.message_from_file(open("000.msg")) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/site-packages/PIL/__init__.py", line 35, in message_from_file # ;-) File "/var/tmp/python2-2.2.1-root/usr/lib/python2.2/email/Parser.py", line 41, in parse File "/var/tmp/python2-2.2.1-root/usr/lib/python2.2/email/Parser.py", line 134, in _parsebody File "/var/tmp/python2-2.2.1-root/usr/lib/python2.2/email/Parser.py", line 45, in parsestr File "/var/tmp/python2-2.2.1-root/usr/lib/python2.2/email/Parser.py", line 40, in parse File "/var/tmp/python2-2.2.1-root/usr/lib/python2.2/email/Parser.py", line 81, in _parseheaders email.Errors.HeaderParseError: Not a header, not a continuation - I have no idea why PIL/__init__.py is even mentioned here! I am pretty sure email package can't depend on it in any way. My sys.path is like: >>> sys.path ['', '/usr/lib/python2.2', '/usr/lib/python2.2/plat-linux2', '/usr/lib/python2.2/lib-tk', '/usr/lib/python2.2/lib-dynload', '/usr/lib/python2.2/site-packages', '/usr/lib/python2.2/site-packages/Numeric', '/usr/lib/python2.2/site-packages/PIL'] Something is broken. (the directory /var/tmp/python2-2.2.1-root doesn't exist) >>>> from mx import DateTime >*** You don't have the (right) mxDateTime binaries installed ! >Traceback (most recent call last): > File "", line 1, in ? > File "mx/DateTime/__init__.py", line 8, in ? > from DateTime import * > File "mx/DateTime/DateTime.py", line 9, in ? > from mxDateTime import * > File "/usr/local/lib/python2.2/site-packages/reportlab/__init__.py", line 13, in ? > myDir = os.path.split(__file__)[0] >ImportError: No module named mxDateTime >>>> from mx.DateTime import mxDateTime >>>> > > >Two obvious problems: > >1. Bizarre last line of traceback involving reportlab (whose >__init__.py I list in full below). Reportlab and mxDateTime, AFAIK, >are entirely unrelated! > >2. mxDateTime's __init__.py (mx/DateTime/mxDateTime/__init__.py) does >an import mxDateTime, which then fails, causing the error message >about mxDateTime's binaries (ie. mxDateTime.so) to be printed. >Obviously, Python isn't finding the library, but I can't remember how >extension modules are located, nor could I find anything in the Python >docs on this -- could anyone point it out for me? > >Even better, explain why on earth I get that line about reportlab! Up >until now reportlab has sat in /usr/local/lib/python2.2/site-packages >quietly minding its own business. The egenix-mx-base `mx' directory >(2.0.3) is also in the same site-packages directory. Grepping through >reportlab, I see that one of its demos making use of mxTextTools, but >I don't think that's relevant. > > >John > >#copyright ReportLab Inc. 2000-2001 >#see license.txt for license details >#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/__init__.py?cvsroot=reportlab >#$Header: /cvsroot/reportlab/reportlab/__init__.py,v 1.16 2001/08/13 12:17:12 rgbecker Exp $ >__version__=''' $Id: __init__.py,v 1.16 2001/08/13 12:17:12 rgbecker Exp $ ''' >__doc__="""The Reportlab PDF generation library.""" >Version = "1.09" > >def getStory(context): > if context.target == 'UserGuide': > # parse some local file > import os > myDir = os.path.split(__file__)[0] > import yaml > return yaml.parseFile(myDir + os.sep + 'mydocs.yaml') > else: > # this signals that it should revert to default processing > return None > > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by Linux RedHat 7.2 aaro at onego.ru <- not to be mailed to From eric.brunel at pragmadev.com Mon Sep 23 04:05:15 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 23 Sep 2002 10:05:15 +0200 Subject: Why does Tkinter do this? References: Message-ID: Mark Wright wrote: > I'm trying to create a resizeable Label with an image. bind()ing to > the configure event allows me to resize the image whenever the label > is resized, but if I set the size of the image to the new size of the > label, it is too big (which produces cascading 'configure' events and > a steadily expanding Label). OK, so I try subtracting the borderwidth > - which is no good either. But if I subtract the borderwidth *times > two*, it works. Can anyone explain this to me? Errrr, because the border is on both sides...? -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From claird at starbase.neosoft.com Fri Sep 6 14:23:24 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 6 Sep 2002 13:23:24 -0500 Subject: Project idea References: <3d77c0b4$1@news.nz.asiaonline.net> Message-ID: <84246AF492892BD2.EEDDE31C3CDD0FDF.E45EA739B6484CC6@lp.airnews.net> In article <3d77c0b4$1 at news.nz.asiaonline.net>, Colin Brown wrote: >Hi > >If you are interested in a Windows platform project for automated testing >then read on. > >There is an excellent freeware package "AutoIt" available from >http://www.hiddensoft.com/AutoIt/ >that provides a DLL module that could be readily interfaced to Python. > >"AutoIt" is a simple tool that can simulate key presses, mouse movements and >window commands (maximize, minimize, wait for, etc.) in order to automate >any windows based task (or even windowed DOS tasks). . . . To encourage those who are considering this opportunity, I observe that illustrates a simple Tcl binding. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From fb at frank-buss.de Sun Sep 1 13:09:46 2002 From: fb at frank-buss.de (Frank Buss) Date: Sun, 1 Sep 2002 17:09:46 +0000 (UTC) Subject: A "for" with "list" question. References: <3b55ea60.0208311330.4608ae71@posting.google.com> Message-ID: Sean 'Shaleh' Perry wrote: > oddballs = [] > for item in b: # iterate over one list > if item in a: # test if it is in the other list > print item > else: > oddballs.append(item) > > for item in oddballs: > print item That's wrong, because you won't get 0, which is in a, but not in b. Derived from the nice solution from Graham I would write: >>> a = [0,1,2] >>> b = [1,2,3] >>> inBothLists = [item for item in a if item in b] >>> inOneListOnly = [item for item in a+b if item not in inBothLists] >>> print inBothLists [1, 2] >>> print inOneListOnly [0, 3] -- Frank Bu?, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From martin at v.loewis.de Thu Sep 5 03:38:23 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 05 Sep 2002 09:38:23 +0200 Subject: Is it okay to compile 2.2.1 with gcc 2.96? References: <3D769ACE.7000801@nospam.yahoo.com> Message-ID: Anton Graph writes: > My question is this. Is gcc 2.96: > > Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/2.96/specs > gcc version 2.96 20000731 (Red Hat Linux 7.3 2.96-112) > > considered to be a stable compiler for the purpose of compiling 2.2.1? Certainly, yes. Regards, Martin From DennisR at dair.com Wed Sep 25 13:39:51 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Wed, 25 Sep 2002 17:39:51 GMT Subject: ANN: comments on Python Windows EXE Factory Message-ID: I have put up a page at http://www.autorunning.com/arpyexe.cgi which allows building Python CGI interface programs over the web. Drop your Python code into a 50,000 character capacity text and press a "submit" type button. Your Windows EXE is built and can be downloaded. The default EXE comes prebuilt with 24 of the most common lib modules required. It also comes with python22.dll built in so that the EXE runs on any Win 98 or later system and does not require that Python be installed. Up to 3 additional lib modules can be installed. The size of the sample download is 432 Kb. This web page is a fully functional demo for a possible commercial product. The commercial product would run entirely on your local machine (no submitting your code to my web page) and is likely to have greater capacity. I have tested this and know about the following limitations. I would appreciate help in fleshing out any more: 1) Will not run on Win 95 which has never had IE 4.0 or greater installed (shell problem). That is why I only claim Win 98. 2) Running program times out in Opera if run in MIDI mode (one or more simultaneous documents partially fills client area). It works fine if the browser window is first maximized within the client area (not same as maximizing Opera to fill entire screen and which is not required). Have I picked the right libraries to include? What else would you recommend to build on this approach? Thanks to the great Python community. -- Dennis Reinhardt http://www.dair.com From sam-nospam- at totallynerd.com Mon Sep 23 11:58:37 2002 From: sam-nospam- at totallynerd.com (Sam Alexander) Date: 23 Sep 2002 08:58:37 -0700 Subject: Zope Documentation and example sites Message-ID: <503511c2.0209230758.74a64a3d@posting.google.com> Hi all, I've just installed Zope, and now I'm trying to find reesources to learn it. I have a few questions along these lines... 1) What online resources are out there to help a newbie learn Zope? I've downloaded the Zope Book, but it's a bit technical for my taste. I'm looking for something with examples or tutorials showing how to do some basic stuff from scratch. Any suggestions? Either online or books ??? 2) What sites are using Zope? I've noticed most if not all the Zope sites I've seen don't mention they're using Zope. Can someone give me some examples of sites which use Zope so I can get a better idea of the type of layouts I can do with Zope? I know it's very programmable, but other then the Plone site (which is great), I'm not sure what other sites use Zope. 3) Finally, I've never used Python, but I'm seasoned in Linux and in web/app programming (Perl, PHP, C++, Cold Fusion, etc). How long would it take to learn Zope/python well enough to create a production site? Thanks for your help and suggestions. From kodokuchef at yahoo.com Fri Sep 20 08:25:48 2002 From: kodokuchef at yahoo.com (akirasugiura) Date: 20 Sep 2002 05:25:48 -0700 Subject: newbie seeks advise. References: <77c84db2.0209192137.51167ebb@posting.google.com> Message-ID: <77c84db2.0209200425.4c723344@posting.google.com> Thank you very much. I didn't know there is such a "max" function. ("max" is a function isn't it). I also tried "min" to find a smallest number(lol) and it worked. "list(data)" also worked. Thanks again. From hst at empolis.co.uk Fri Sep 20 07:06:22 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Fri, 20 Sep 2002 12:06:22 +0100 Subject: finding last match in a file Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F41D@hendrix.empolisuk.com> > In article <87r8fplvq4.fsf at smtp.blueyonder.co.uk>, Keith > O'Connell wrote: > > Dag writes: > > > >> I have a number of very large files where I have to find > the last line > >> which matches a certain experssion. Currently I'm simply > opening the > >> file and looping through it noteing each time a line > matches and at the > >> end of the loop I see which was the last match. However > this is very > >> slow and inefficient. Is there some way to read through the file > >> backwards and simply find first match starting from the > end of the file. > >> The files are really too big to read the entire thing into memory. > > > > > > Would you not be able to use grep with the "-n" option. It will list > > all your matches with the lines numbered so you can see the > last match > > having the highest line number. If you then use wc on the > file you will > > get the total number of lines. Take one from the other and > you can see > > how far from the end your last match is. > > > > That seems to easy - Have I misunderstood you question? > > The problem is that greping through large files with a fairly complex > regexp is taking far too long, esp. when I know that the last > occurance is > almost always within the last 100 lines. > > Dag It's not clear to me whether you need the number of the last line that matches, or just the contents of the last line. If you don't need the number then the following might be useful as a basis. def lastlinematching(fileobj, aregex): # assume initially match will be in about the last 8K of the file fileobj.seek(-8192, 2) lines = fileobj.readlines()[1:] #throw away possible incomplete line lastline = None for line in lines: if aregex.search(line): lastline = line if lastline is None: #not in last 8k, start again from the beginning fileobj.seek(0, 0) for line in fileobj.xreadlines(): if aregex.search(line): lastline = line return lastline Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From mal at lemburg.com Wed Sep 25 12:08:50 2002 From: mal at lemburg.com (M.-A. Lemburg) Date: Wed, 25 Sep 2002 18:08:50 +0200 Subject: ANN: eGenix.com mx EXPERIMENTAL Package 0.7.0 Message-ID: <3D91DF92.4010603@lemburg.com> ________________________________________________________________________ ANNOUNCING: eGenix.com mx EXPERIMENTAL Extension Package for Python Version 0.7.0 Experimental Python extensions providing important and useful services for Python programmers. ________________________________________________________________________ WHAT IS IT ?: The eGenix.com mx Experimental Extensions for Python are a collection of alpha and beta quality software tools for Python which will be integrated into the other mx Extension Packages after they have matured to professional quality tools. Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. ________________________________________________________________________ WHAT'S NEW ? This release fixes a few minor bugs and solves the distutils problem with mxNumber. It also comes with an updated distutils setup which installs the RPMs into /usr/ rather than /usr/local/. ________________________________________________________________________ EGENIX.COM MX EXPERIMENTAL PACKAGE OVERVIEW: mxNumber - Python Interface to GNU MP Number Types mxNumber provides direct access to the high performance numeric types available in the GNU Multi-Precision Lib (GMP). This library is licensed under the LGPL and runs on practically all Unix platforms. eGenix.com has ported the GMP lib to Windows, to also provide our Windows users with the added benefit of being able to do arbitrary precision calculations. The package currently provide these numerical types: 1. Integer(value) -- arbitrary precision integers much like Python longs only faster 2. Rational(nom,denom) -- rational numbers with Integers as numerator and denominator 3. Float(value[,prec]) -- floating point number with at least prec bits precision 4. FareyRational(value, maxden) -- calculate the best rational represenation n/d of value such that d < maxden mxTidy - Interface to HTML Tidy (HTML/XML cleanup tool) mxTidy provides a Python interface to a thread-safe, library version of the HTML Tidy. command line tool. HTML Tidy helps you to cleanup coding errors in HTML and XML files and produce well-formed HTML, XHTML or XML as output. This allows you to preprocess web-page for inclusion in XML repositories, prepare broken XML files for validation and also makes it possible to write converters from well-known word processing applications such as MS Word to other structured data representations by using XML as intermediate format. mxURL - A URL Datatype mxURL provides a new datatype for storing and manipulating URL values as well as a few helpers related to URL building, encoding and decoding. The main intention of the package is to provide an easy to use, fast and lightwheight datatype for Universal Resource Locators (note the W3C now calls these URIs). mxUID - A UID Datatype mxUID provides a fast mechanism for generating universal identification strings (UIDs). The intent is to make these UIDs unique with high probability in order to serve as object or data set identifiers. A typical use lies in generating session IDs. Other areas where unique IDs play an important role are RPC-implementations, ORBs, etc. ________________________________________________________________________ WHERE CAN I DOWNLOAD IT ? The download archives and instructions for installing the packages can be found at: http://www.egenix.com/ Note that in order to use the eGenix.com mx EXPERIMENTAL package you will first need to install the eGenix.com mx BASE package which can be downloaded from the same location. ________________________________________________________________________ WHAT DOES IT COST ? The EXPERIMENTAL packages uses different licenses in its subpackages. Please refer to the subpackage documentation for details. Some of them may be integrated into the BASE package, others will be integrated into the COMMERCIAL package. The package comes with full source code ________________________________________________________________________ WHERE CAN I GET SUPPORT ? Commercial quality support for these packages is available from eGenix.com. Please see http://www.egenix.com/files/python/eGenix-mx-Extensions.html#Support for details about our support offerings. ________________________________________________________________________ Enjoy, -- Marc-Andre Lemburg CEO eGenix.com Software GmbH ______________________________________________________________________ Company & Consulting: http://www.egenix.com/ Python Software: http://www.lemburg.com/python/ From tim.one at comcast.net Mon Sep 16 01:07:39 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 16 Sep 2002 01:07:39 -0400 Subject: Source code In-Reply-To: Message-ID: [Terje Johan Abrahamsen] > If I would like to write some code that would not be possible for > others to read, after I distribute the program, would Python be > suitable? No, but I don't know of a language that would be. Unless you're also going to supply a restricted CPU that prevents stepping through the machine code, you can't really hide anything from a determined reverse-engineerer of ordinary skill. > ... > or should I look for a compiled language instead? It's very easy to reverse-compile Python bytecode. It's not so easy to disassemble compiled machine code, but if you think there aren't lots people who can read machine language almost as easily as high-level source, you're in for a surprise. Compilers follow predictable patterns too. You could try writing directly in highly obfuscated assembler; that would raise the bar high enough to discourage almost everyone, although it would also attract a class of cracker who would feel challenged to outwit you. If you didn't know all that already, you're playing a game you can't win. A better idea is to question why you want to play it at all . From bondpaper at earthlink.net Mon Sep 30 21:11:45 2002 From: bondpaper at earthlink.net (Tom) Date: Tue, 01 Oct 2002 01:11:45 GMT Subject: Reloading a module Message-ID: I'm developing some python mini applets on a Mac (using os 9 and the 2.1.1 Python IDE), and I've found it impossible to delete and/or reload a module after making changes to the code during the debugging/verification process. Is there an easy and/or effective way to do this? If I execute: del mymodule and then execute a print dir(mymodule), it shows up as nonexistent. Then, when I execute: import mymodule followed by a print dir(mymodule), the changes do not show up. Thanks for the help. Tom From rajarshi at presidency.com Thu Sep 26 18:05:37 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Thu, 26 Sep 2002 18:05:37 -0400 Subject: indexing and searching pdf files Message-ID: Hi, I have a load of pdf files and I would like to index them so that I can serach them for keywords. I was thinking of using pdftotext to generate the textfile and then create the index from that. My question - is there already something like this with python? Another question which is slightly off topic is, does anybody know of any articles/pages that talk about indexing text files efficiently - index generaion algorithms etc? Thanks, From ianholmes01 at lycos.com Thu Sep 5 07:54:18 2002 From: ianholmes01 at lycos.com (Ian Holmes) Date: 5 Sep 2002 04:54:18 -0700 Subject: Psyco testing feed-back wanted References: Message-ID: "Jimmy Retzlaff" wrote in message news:... > Wow!!! > > I've seen raves about Psyco, but I hadn't tried it myself until today. > My test case was a function that tests if a point is in a polygon. I > timed several runs with different approaches. All tests are whether 1 > point is in a polygon made up of 5,000,000 points. The timing was done > on just the function call itself. Here are some results: > I had never heard of it before reading the "Python to exceed C in 2030" thread but as soon as it was mentioned I had to test it :) I saw 3-5x speed increases on a big list / for loop (test data only) that ran for 8s without psyco. top product - code used as follows (fairly trivial I admit) ---- import string,time,random,psyco from strings import * #imports a list of 4 strings LOOPS = 100000 def method_one(body, x): for a in range(0, LOOPS): body.append(strings[x]) x = random.randint(0,3) return body print "Starting test one" body = [] x = 0 START_TIME = time.time() text = string.join(method_one(body,x)) print "append method (list) =>", time.time()-START_TIME,"s" strlen = len(text) string_size = strlen / 1024 print "Size is",string_size,"KB" print 'starting psyco' meth1 = psyco.proxy(method_one) print "Starting test Two" body = [] x = 0 START_TIME = time.time() text = string.join(meth1(body,x)) print "append method (list) =>", time.time()-START_TIME,"s" strlen = len(text) string_size = strlen / 1024 print "Size is",string_size,"KB" From gua81 at XXXyahoo.com Mon Sep 23 20:07:16 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Tue, 24 Sep 2002 10:07:16 +1000 Subject: Python quote in cgi Message-ID: Hi, this might have been discussed b4, can someone clarify for me, when writing cgi script in python, does ' = """ eg print """Main""" From lyle at users.sourceforge.net Mon Sep 9 10:38:35 2002 From: lyle at users.sourceforge.net (Lyle Johnson) Date: Mon, 09 Sep 2002 09:38:35 -0500 Subject: compile error on SWIG file References: <3D7C55EE.D9278B1C@ipm.fhg.de> Message-ID: <3D7CB26B.2040706@users.sourceforge.net> Markus von Ehr wrote: > compiling my c-file generated from SWIG > (swig -c -python -o mvelib.c mvelib.i) > with a setup-file, I receive the error: > > c:\programme\vc98\include\eh.h(32) : fatal error C1189: #Error: "eh.h > is only for C++!" > > Anybody knows what I have to change? Is it a C++ library that you're wrapping (sounds that way)? If so, you'd want to run SWIG with the -c++ option to tell it that. From vze3myxh at verizon.net Tue Sep 17 07:38:25 2002 From: vze3myxh at verizon.net (Satheesh Babu) Date: Tue, 17 Sep 2002 11:38:25 GMT Subject: More on Protecting Source Code References: Message-ID: I love open source and generally prefer to use open source products, mainly because I can't (or don't want to) keep telling my managers that I'm waiting for the vendor to help me (usually, this involves several hoops through some "customer service rep" before I get to talk to a real engineer), while waiting to fix a problem. With open source, I have the possibility to fix it myself. Strangely enough, I've seen that this is a big reason why people don't use open source - because then they can no longer use the excuse "waiting for the vendor". Unless majority of the world thinks that having open source is beneficial, there is a need for closed source software. If I want to make money on the software that I write, there are instances where I want to protect my intellectual property. What if: - I sell my open source product to a company - Some suit comes in and has a friendly relationship with another big consulting firm and hands them contracts. - They take my code and if they find it worthy enough, they probably'll repackage and sell it as their own. Little guys like me can't dedicate that much legal resources to fight them. Good thing is that thins don't happen often. If the software works, companies are more than happy to pay you *reasonable money*. And they don't really want to spend time to reengineer the code. Individual users may be a different story - they might have a better marketing idea than you do and will probably hijack your code. For me, .py is enough. I agree with David on validity of his points though.I've seen guys choosing Java because they can then distribute .class files instead of source. World is not ideal yet :-) -vsb http://vsbabu.org/ From niemeyer at conectiva.com Thu Sep 12 18:17:01 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Thu, 12 Sep 2002 19:17:01 -0300 Subject: ANN: NINZ 1.2.1 In-Reply-To: <200209130756.46405.rjones@ekit-inc.com> References: <20020912135926.A7584@ibook.distro.conectiva> <200209130756.46405.rjones@ekit-inc.com> Message-ID: <20020912191701.A20774@ibook.distro.conectiva> > And ZSI would be? You're the second person to ask me about it, so here it goes: --- ZSI, the Zolera SOAP Infrastructure, is a Python package that provides an implementation of SOAP messaging, as described in The SOAP 1.1 Specification. In particular, ZSI parses and generates SOAP messages, and converts between native Python datatypes and SOAP syntax. It can also be used to build applications using SOAP Messages with Attachments. ZSI is ``transport neutral'', and provides only a simple I/O and dispatch framework; a more complete solution is the responsibility of the application using ZSI. As usage patterns emerge, and common application frameworks are more understood, this may change. -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From wlfraed at ix.netcom.com Fri Sep 20 18:43:52 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 20 Sep 2002 15:43:52 -0700 Subject: Newbia alert .. working my way through Easy Python Montana Edu page, need help.. References: Message-ID: <8b8gma.dj3.ln@ix.netcom.com> Highwaykind fed this fish to the penguins on Friday 20 September 2002 06:27 am: > I'm asked ( on the website : www.honors.montana.edu\_jjc\easytut > \node10.html ) to write a small programm to calculate rectangle, > square and circle thingies( forgot the English word .. ) and I came up > with this code : > > But the thing keeps telling me width is not defined, also I can;t use > the ELIF command .. THink I could do with some help :) > Where to begin... I see way too many errors to intersperse corrections. 1) Python indentation controls block structure! 2) You never assign values to those names it is complaining about -- rather you are inputting to "a", "b", etc. but never passing /those/ to the functions. Compare: import math #get the long definition of PI def area_rect(width, height): return width * height def area_square(side): # squares are special rectangles return area_rect(side, side) def area_circle(radius) return math.pi * (radius * radius) # r*r is likely faster than r**2 option = "prompt" #filler for first pass while option != "q": if option == "r": w = input("Width") h = input("Height") print "Area of Rectangle is ", area_rect(w, h) elif option == "s": s = input("Side") print "Area of Square is ", area_square(s) elif option == "c": r = input("Radius") print "Area of Circle is ", area_circle(r) else: print "Options:" print " 'r' Calculate Area of Rectangle" print " 's' Calculate Area of Square" print " 'c' Calculate Area of Circle" print " 'q' Quit program" print " Display this help" option = raw_input("Option") -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From huaiyu at gauss.almadan.ibm.com Wed Sep 11 17:43:51 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 11 Sep 2002 21:43:51 +0000 (UTC) Subject: Restricting methods in derived classes Message-ID: This should be something that the new style class solves but I can't figure out exactly how: I need a class that is similar to dict, but, besides providing several additional methods, it only inherits a subset of dict methods. What is the best way to say that only a subset of methods are inherited? Using the UserDict approach requires wrappers for all the inherited methods, such as def keys(self): return self.dict.keys() def items(self): return self.dict.items() This has a function call overhead. I'd prefer something like items = self.dict.items but of course self is not defined here. Using the "class MyClass(dict)" approach, how do I say that methods such as update, __setitem__ are not inherited? I know the set/get attr trick, but that adds a function call overhead on every method. What I'm looking for is a way to say which methods from dict are inherited in MyClass at the time the class is defined, without incuring a cost when the methods are called. Is this possible? Huaiyu From pan-newsreader at thomas-guettler.de Tue Sep 24 15:46:48 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Tue, 24 Sep 2002 21:46:48 +0200 Subject: ZCatalog without Zope References: Message-ID: On Thu, 19 Sep 2002 12:43:26 +0200, Thomas Guettler wrote: > Hi! > > Has anyone used ZCatalog from Zope > with a standalone ZODB (without Zope)? > > Background: > I am thinking about moving away from Zope to quixote or just simple cgi. > > If you are intereseted > in the reason way I don't want to use zope: > http://lists.zope.org/pipermail/zope/2002-August/119965.html > > thomas For those who have the same interest. I just discoverd IndexedCatalog: http://www.async.com.br/projects/IndexedCatalog/ Did not try it yet. thomas From sismex01 at hebmex.com Fri Sep 27 18:25:43 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 27 Sep 2002 17:25:43 -0500 Subject: Python Process that can survive Message-ID: > > Yeah I found this hack on the web and I can't believe that this is > only way to do this in python. You're basically stripping the process > of all it's stream and sending it on its way. This is really messy. > It isn't messy, it's the correct way to do it. You're not stripping the process of it's streams, your disconnecting it from it's controlling TTY, which, if it closes before the app, sends a DIE! signal to the app; that, or your app freezes or dies when trying to use it's console. > > Plus in my lab there are a bunch of perl guys and a few python people. > To date, what one can do in their script the python guys can do to > (only nicer and much more readible). Perl has the ability to have a > process continue after the underlying terminal is killed if the > process is in the background. What is python doing that doesn't allow > this? > > Chris > I suspect someone's yanking someone else's chain; I used to write perl programs also, and whenever I needed an app to totally disconnect from it's parent, I *had* to close it's link to the console, or it's parent's console, which basically means that I had to redirect std{in,out,err} to /dev/null, in whatever mode you want. It's not that nasty, you know. -gustavo Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From mtremblay at golemlabs.com Mon Sep 30 14:51:55 2002 From: mtremblay at golemlabs.com (news1.sympatico.ca) Date: Mon, 30 Sep 2002 14:51:55 -0400 Subject: SWIG - C++ - Inheritance Message-ID: Hello, I'm having some problems with SWIG and Python. My base class is a CThread class which is defined in C++ and extended to python using SWIG. The class is an interface to easily create threads, the process function must be defined in the child class and then when the run function is called, the process function is executed in a separate thread. Every function but the process function is already implemented. class CThread { public: CThread(); //Constructor ~CThread(); //~Destructor virtual void process() = 0; //Pure virtual function to extend, thread function bool run(); bool suspend(); bool resume(); bool terminate(); private: bool startThread(); INT32 m_handle;? }; The problem comes when I come to create a new class in python that inherits from CThread. Here is the python code sample =============== test.py ================= import my_module class MyThread(my_module.CThread): def __init__(self): pass def process(self): print "hey" a = MyThread() a.run() ============================================ my_module is exposed to Python using SWIG. When I try to execute this, I get the following error : ############################################# Traceback (most recent call last): File "U:\Alexandra\test\pythontool\martin.py", line 14, in ? a.run() File "U:\Alexandra\test\pythontool\hector.py", line 649, in run def run(*args): return apply(_hector.CThread_run,args) TypeError: Type error. Expected _p_CThread ############################################# It appears that the swig module does not recognize the a variable as a CThread. I guess there is something I am doing wrong. It does not even call the process function so the problem does not appear to be with the pure virtual function. Anybody can help ? It would be really appreciated. Thanks ! Mathieu Tremblay From printers at sendme.cz Sat Sep 28 11:56:58 2002 From: printers at sendme.cz (A) Date: Sat, 28 Sep 2002 17:56:58 +0200 Subject: How to convert unicode Message-ID: <3D95ED6A.17648.13FA357E@localhost> Hi, I have a script that downloads a webpage with characters that are not plain ascii.From the web page header I can find out that there is UTF-8 coding( Unicode). I can display the page properly in a web browser if I send from my script "Content-Type: text/html; charset=UTF-8 " But I need to save the page( the text of the page) to a file and some time later import the text to a database (MS Access or similar). How can I download the file or write to a file so that the characters will be properly display in the file and in the database as well? Thanks for help Ladislav From jdavis at empires.org Wed Sep 18 23:57:44 2002 From: jdavis at empires.org (Jeff Davis) Date: Thu, 19 Sep 2002 03:57:44 GMT Subject: shared mem & semaphores module Message-ID: I found a module online by "INRIA" (I don't know who that is) that seems to wrap the C functions for shared memory management and semaphores. http://gigue.peabody.jhu.edu/~mdboom/omi/source/shm_source/shm.html My question is: are these functions included elsewhere? It seems logical that python would include them in the standard distribution, since those are a pretty important part of at least UNIX (although I know python isn't only for UNIX). If they don't, is there a reason other than cluttering the standard distribution? Regards, Jeff From s_gherman at yahoo.com Tue Sep 3 15:34:04 2002 From: s_gherman at yahoo.com (Sorin Gherman) Date: 3 Sep 2002 12:34:04 -0700 Subject: https in Python? Message-ID: Hi, Is it possible to handle https using Python's libraries? If so, what's involved with using Python to read my hotmail messages, for instance? Thanks in advance, /sorin gherman From wanner.dx at mellon.com Thu Sep 12 06:05:56 2002 From: wanner.dx at mellon.com (dxterra) Date: 12 Sep 2002 03:05:56 -0700 Subject: file upload using msvcrt References: <20020911204906.00669.00000156@mb-fh.aol.com> <20020911210159.00669.00000162@mb-fh.aol.com> Message-ID: I have tried both of the methods suggested. When I do a len(fileinfo.value) before writing, the size is consistantly 8k regardless of the actual file size. I am using Oracle 9iAS with apache. I still think that the LimitResponseSize is being set somewhere, but Oracle cannot tell me. teaandbikkie at aol.com (TeaAndBikkie) wrote in message news:<20020911210159.00669.00000162 at mb-fh.aol.com>... > >data = fileinfo.file.read( ) > >if not data: break > > I just thought of another possible problem here, read() is supposed to read in > the entire file, and maybe 8k is all data can take :) > > So you could change it to read(1024) for 1k chunks. > > Also, maybe read() recognises an EOF character in the word doc? Hopefully being > binary read this should not happen... > > Kind regards, From tjreedy at udel.edu Fri Sep 20 18:26:51 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 20 Sep 2002 22:26:51 GMT Subject: Python Compiling References: Message-ID: "Terje Johan Abrahamsen" wrote in message news:amfveg$5g64k$1 at ID-53055.news.dfncis.de... > why is not Python a compiled language? This has been a subject of much discussion and work. One answer: portability (see below) and ease of use for humans rather than computers. Another possible answer: it is, sort of. CPython compiles Python code to Python bytecode (stored in .pyc files). Jython compiles Python code to Java bytecode. In either case, you can run code (raw ascii or compiled bytecode) that does not use machine-specific features on most any machine that has a decent C compiler or Java system -- without a bunch of #ifdefs. Psyco compiles Python functions (or parts thereof) to special-purpose machine code. But it is only available for machines whose machine code it has been adapted to. Pyrex adds statements needed to supply the information needed to translate Python code to C and thence compile with a local C compiler. There is at least one other system (name escaped me for the moment) for converting numerical code to C and machine code. Another answer is that the obvious, straigthforward method of compiling Python would not gain as much as one would expect, because of its dynamic name binding. Much better to identify and rewrite in C/C++ just the functions that are actual or potential bottlenecks. Terry J. Reedy From hst at empolis.co.uk Tue Sep 17 07:35:55 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 17 Sep 2002 12:35:55 +0100 Subject: Regular expression help needed Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D28@hendrix.empolisuk.com> Torkil Grindstein wrote: > Btw, I have no knowledge of SAX. Perhaps I should dig into that? > > Torkil. > -- If you are going to do much processing of XML, then certainly. With your current documents it would seem OK to use REs, but for more complicated processing that way madness lies. Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From pinard at iro.umontreal.ca Tue Sep 3 20:48:35 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Tue, 03 Sep 2002 20:48:35 -0400 Subject: efficient list merging In-Reply-To: <20020903220944.475d7222.christophe.delord@free.fr> (Christophe Delord's message of "Tue, 3 Sep 2002 22:09:44 +0200") References: <20020903220944.475d7222.christophe.delord@free.fr> Message-ID: [Christophe Delord] >> I am not sure about the relative speed of everything, but I would be >> tempted to try: >> >> dict(zip(list1 + list2, [None] * (len(list1) + len(list2)))).keys() > > This may be written using list comprehension: > >>>> dict([(k,1) for k in list1+list2]).keys() The `for' loop, even within a list comprehension, will be compiled into an explicit loop, likely to be slower than the implicit loops within `zip'. Taking advantage of other clever suggestions, I would guess that: both = list1 + list2 result = dict(zip(both, both)).keys() would not be so bad, speed-wise. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From bokr at oz.net Sat Sep 7 17:11:10 2002 From: bokr at oz.net (Bengt Richter) Date: 7 Sep 2002 21:11:10 GMT Subject: returning values from FORTRAN with f2py References: Message-ID: On 7 Sep 2002 12:22:16 -0700, spam at fisher.forestry.uga.edu (Chris Fonnesbeck) wrote: >I am wondering how to persuade some fortran code that I have compiled >with f2py to return its calculated values to me in python. I have >some code that does gaussian elimination (mostly from Numerical >Reciopes), and is supposed to return an inverted matrix so that I can ^^^^^^^^-[1] >solve a system of linear equations. However, when run in python, the ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-[2][3] >function runs without error but returns no values: > >>>> a = [[2,1,3],[1,-1,1],[3,6,-1]] >>>> b = [7,2,10] >>>> import gauss >>>> gauss.gauss(a,3,b,1) >>>> > >Is there something that I have to change in my fortran code to make >this work? > Have you looked at http://www.pfdubois.com/numpy/html2/numpy.html and [1] http://www.pfdubois.com/numpy/html2/numpy-18.html#pgfId-303023 [2] http://www.pfdubois.com/numpy/html2/numpy-18.html#pgfId-303019 or maybe [3] http://www.pfdubois.com/numpy/html2/numpy-18.html#pgfId-303085 Perhaps there is an easier route to your goal? (I haven't used the above, but numpy seems to be recommended frequently). Regards, Bengt Richter From skip at pobox.com Tue Sep 10 08:46:43 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 10 Sep 2002 07:46:43 -0500 Subject: how to build wxPython w/ Sun's C++ compiler? In-Reply-To: <23891c90.0209092359.11acb607@posting.google.com> References: <23891c90.0209092359.11acb607@posting.google.com> Message-ID: <15741.59827.147187.55289@12-248-11-90.client.attbi.com> Paul> What about configure programs, though? They tend to accept lots of Paul> command line arguments, and it's hard to get more "Unix-centered" Paul> than that these days. Agreed. However, disutils commands have this structure: python setup.py [ options ] command [ more options ] ... which I think can get kind of confusing. Paul> Moreover, the config.status file nicely summarises what you Paul> presented to configure - much more convenient than environment Paul> variables, surely, because you get to remember how you built the Paul> package in question. The problem with wxPython is that it's got stuff written in C++ while Python is typically compiled with C. I don't want what the system was built with. ;-) Skip From bruce_deletethis_dawson at cygnus-software.com Thu Sep 26 11:34:02 2002 From: bruce_deletethis_dawson at cygnus-software.com (Bruce Dawson) Date: Thu, 26 Sep 2002 15:34:02 GMT Subject: SET_LINENO References: <3D92A46E.2030706@cygnus-software.com> Message-ID: <3D9328C1.5030802@cygnus-software.com> Thanks for all the replies - including the link to the unhandled exception handling option. Martin v. L?wis wrote: > Bruce Dawson writes: > > >>Executive summary: Has the SET_LINENO removal been tested with the HAP >>debugger, and wouldn't a breakpoint instruction give much larger >>benefits? ... >>So, wouldn't a break-point opcode be a more substantial improvement >>than removing SET_LINENO? Just bringing up that old topic again to see >>if it gets any more traction :-) >> > > No. Removal of SET_LINENO does improve performance in a "free-running" > application, which adding a breakpoint instruction would not. A breakpoint instruction would be intended to improve performance in debuggers. My point was that the improvement there would be larger (probably 100% or more) than the improvement from SET_LINENO. But the improvement would not, as you say, affect "free-running" applications at all. > That said: it might be still worthwhile to add a breakpoint > instruction. There are a number of issues to be considered, such as > getting the breakpoint instruction into the byte code, and getting the > original instruction back in. So if you'ld like to see one, you > probably have to write a PEP. Some day I will do that. I have to dig deeper in the Python source before I can do that. > >>P.P.S. A breakpoint instruction would also be a boon for asserts - I'd >>love to be able to stop on the assert when running under a debugger, >>to see what is wrong before the stack frame unwinds. >> > > I can't see how this helps. Wouldn't you have to set a breakpoint on > all asserts for that? And wouldn't that require finding all asserts in > the first place? If assert was implemented with a hard-coded breakpoint then it would work very nicely. Under a debugger this would stop you on the relevant line. Not under the debugger it would throw an exception as before. On x86 processors int 3 is the hard-coded breakpoint instruction. If you hit one it stops your program. If you're running under a debugger you can then step right over it. I was imagining something like that. Asserts are great, but they are easier to interpret if when you trigger one you are dropped onto the assert statement. Just a mad idea... From member at dbforums.com Mon Sep 16 16:31:16 2002 From: member at dbforums.com (mcolli) Date: Mon, 16 Sep 2002 20:31:16 +0000 Subject: looking for Python programmers Message-ID: <1821724.1032208276@dbforums.com> Hi, I am looking for Python programmers to participate in a Zope/Pyhton project in Buenos Aires, Argentina. Those who may be interested please send me the CV. Thanks Mariela -- Posted via http://dbforums.com From martin at v.loewis.de Mon Sep 30 01:45:45 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Sep 2002 07:45:45 +0200 Subject: Catching user defined exceptions from foreign modules References: Message-ID: Derek Basch writes: > So, this code works fine for me. However, I have 2 > much larger modules that have the same code structure > but in these larger modules the test1 refuses to catch > the raised TestError unless I change the except clause > to: > > except test2.TestError: > print 'fudge' Perhaps it isn't test2.TestError that is raised, but just TestError, as the module is used as the application program? Regards, Martin From op73418 at mail.telepac.pt Mon Sep 9 16:27:40 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Mon, 09 Sep 2002 21:27:40 +0100 Subject: Python 2.3 References: <3d7cfc19_5@news.newsgroups.com> Message-ID: <5t0qnu0dfbebm1uvk1v93msk4tespgp6bn@4ax.com> On Mon, 09 Sep 2002 22:01:32 +0200, JB wrote: >Will rational numbers be implemented in Python 2.3? And when >is the first beta due? There are no plans to implement rationals. There is however a Rat class in the demo dir, implementing rationals in pure Python. For the 2.3 plans you can consult PEP 283 at http://www.python.org/peps/pep-0283.html > >TIA, Best regards, G. Rodrigues From anthony at computronix.com Mon Sep 23 20:46:49 2002 From: anthony at computronix.com (Anthony Tuininga) Date: Mon, 23 Sep 2002 18:46:49 -0600 Subject: list problem In-Reply-To: <3D8F9F5E.DC48B13F@pop.ntlworld.com> References: <3D8F9F5E.DC48B13F@pop.ntlworld.com> Message-ID: <1032828410.2133.1.camel@localhost> If you have list comprehensions available, use [b for a in x for b in a] Anthony On Mon, 2002-09-23 at 17:10, a.clarke11 wrote: > How about: > > for item in x: > while item: > y.append(item.pop(0)) > print'y=',y > ? > hope this helps > Tony Clarke > Glasgow > > jubafre at brturbo.com wrote: > > > i have: > > x=[['0020', '0000x9'], ['0030', '0000xa'], ['00B4', '0000x8'], ['0030', '0000xb'], ['00F0'], ['0001'], ['0003'], ['0005']] > > > > and i want: > > y=['0020', '0000x9', '0030', '0000xa', '00B4', '0000x8', '0030', '0000xb','00F0', '0001', > > '0003', '0005'] > > > > how to do this? > > > > Juliano Freitas > > www.gebrasil.hpg.com.br > > -- > http://mail.python.org/mailman/listinfo/python-list From bokr at oz.net Mon Sep 9 13:56:44 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Sep 2002 17:56:44 GMT Subject: Python plugins References: Message-ID: On 8 Sep 2002 10:13:00 GMT, Tobias Klausmann wrote: >Hi there, > >For an open source project that needs to be extensible by its >users, I would like to create a plugin architecture. Mind you, >I'm not trying to use Python as a plugin language only like XChat >or Gnumeric do. Let me illustrate: > >I have a directory somewhere in PYTHONPATH (let's just assume >it's in the CWD) that contains lots and lots of *.py files with a >defined set of functions (or, at least one: register()). What I'd >like to do now is being able to load these plugins at program >start and reload them if I'd like to later. Problem is that the >program has to figure out by itself what *.py files are there - >and I have to make sure somehow that I get a grip on the loaded >files. > http://www.python.org/doc/current/lib/module-imp.html Regards, Bengt Richter From b.maryniuk at forbis.lt Tue Sep 10 06:33:05 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 10 Sep 2002 12:33:05 +0200 Subject: UNIX processes Message-ID: <200209101233.05796.b.maryniuk@forbis.lt> Hi, all. Somebody know how to list all the processes in RIGHT way on Linux/UNIX? I need to find the zombies, stopped processes etc. -- Regards, Bogdan Linux: The Ultimate NT Service Pack From whisper at oz.net Fri Sep 6 23:56:46 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 6 Sep 2002 20:56:46 -0700 Subject: Larry Wall's comment on python... In-Reply-To: Message-ID: One could hardly expect Larry to say "I have seen Pearl 6 - and it is Python!" :) David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Tim Peters > Sent: Friday, September 06, 2002 20:30 > To: python-list at python.org > Subject: RE: Larry Wall's comment on python... > > > [Peter Hansen] > > Anyone know how long is the largest chunk of code Larry Wall has > > actually written in Python? > > It was 23 lines longer than the largest chunk of code Guido has actually > written in Perl. The difference is that Larry's code worked, and Guido's > still doesn't. I suspect Larry may have taken a wrong lesson from that > . > > > The fact he has to say "I think" about this issue implies he is > > guessing. Maybe if he actually tried it he'd conclude differently. > > It was just a sound bite from an interview, and blocks aren't > quite the same > thing in Perl (for example, a Perl block can have its own variables, but a > Python block can't). I bet that if Guido had designed Perl, it > would still > have curlies, and I defy anyone to prove that wrong. Heh. > > leave-rationality-to-the-rationals-this-is-language-design-ly y'rs - tim > > > -- > http://mail.python.org/mailman/listinfo/python-list From bokr at oz.net Thu Sep 26 22:53:55 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Sep 2002 02:53:55 GMT Subject: Help! This is driving me insane! References: Message-ID: On Thu, 26 Sep 2002 23:43:33 GMT, "kara.klosterman" wrote: >Hello, >I created a very simple class that totals some data >but I am not getting the output from it that I would >expect at all. >Here is the class: >http://www.geocities.com/dbasch/insane.txt > >I would expect to get: >[0, 0] >[0, 0] >[[0, 0]] > Why? >but I am getting: >[0, 0] <<--(a) >[0, 0] <<--(b) >[[1, 1]] <<--(c) > Why not? [I labeled the above (a) etc. for reference below]. >I dont understand how the 'grouptotals' list is >getting the incremented values prior to the >'grouptotalcounter' function being called. What makes you think it is? The value you printed at (b) shows it's not. >furthermore, I can place a 'print grouptotals' right >after the errorlog append and it isnt the incremented >values! Please tell me this isnt a normal thing! Did you walk through the code and think through what is happening? class Test: def __init__(self): self.errorlog = [] pass def run(self): self.grouptotals = [] for x in range(2): self.grouptotals.append(0) print self.grouptotals <<--(a), should be [0, 0] self.errorlog.append(self.grouptotals) <<-- self.errorlog now [[0, 0]] print self.grouptotals <<--(b), no change, still [0, 0] self.grouptotalcounter() <<-- self.grouptotals changed to [1, 1] (note that self.errorlog still refers to the now changed self.grouptotals) return self.errorlog <<-- ref to changed grouptotals makes it [[1, 1]] but there is no print statement. Reference to self.errorlog is returned to caller (d) below of the run method. def grouptotalcounter(self): for totalbyindex in range(2): self.grouptotals[totalbyindex] += 1 <<-- [0, 0] becomes [1, 1] here If you put the above in insane.py and interactively made an instance thus: >>> import insane >>> t=insane.Test() >>> t.run() # <<--(d) [0, 0] [0, 0] [[1, 1]] that last line is the return value from t.run() being printed by the interactive eval/print loop. Everything as one would expect from the code. Regards, Bengt Richter From duduca007 at yahoo.com Tue Sep 24 13:46:41 2002 From: duduca007 at yahoo.com (Carlos Moreira) Date: Tue, 24 Sep 2002 10:46:41 -0700 (PDT) Subject: Pyro Error. Message-ID: <20020924174641.40449.qmail@web11403.mail.yahoo.com> Testing the simplest example of docs/8-example.html, on client side, generate an error message: Traceback (most recent call last): File "./client.py", line 10, in ? print jokes.joke("Irmen") File "/home/pgs/carlos/python/Python-2.2/lib/python2.2/site-packages/Pyro/core.py", line 315, in __invokePYRO__ self.adapter.bindToURI(self.URI) File "/home/pgs/carlos/python/Python-2.2/lib/python2.2/site-packages/Pyro/protocol.py", line 224, in bindToURI raise ProtocolError('connection failed') Pyro.errors.ProtocolError: connection failed Where I must seek for inconsistences? Pyro.conf? []'s Cadu Moreira KaduSoft President -------------------------- [......] __________________________________________________ Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! http://sbc.yahoo.com From gerhard.haering at gmx.de Wed Sep 11 16:41:41 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 11 Sep 2002 20:41:41 GMT Subject: Distutils/setup help References: Message-ID: Mahrt, Dallas wrote in comp.lang.python: > I am in the process of making modifications to the Python build system to > aid in the cross-compilation of Python. [...] Is this the right list to ask these questions? I'd suggest python-dev, the list of the Python developers. You could cc the distutils SIG's list. -- Gerhard From thomas at xs4all.net Wed Sep 11 20:25:43 2002 From: thomas at xs4all.net (Thomas Wouters) Date: Thu, 12 Sep 2002 02:25:43 +0200 Subject: Use glob not re for regexp? In-Reply-To: References: Message-ID: <20020912002543.GA797@xs4all.nl> On Thu, Sep 12, 2002 at 12:02:43AM +0000, Robert Oschler wrote: > I saw a post where someone said to use glob not re for regular expressions? > Is this true and if so why? I use Secret Labs regexp package. It depends on what you need. 'glob' doesn't do regular expressions, so if you want regular expressions, don't bother with glob. Like its docstrings say, glob is for matching filenames based on globular expressions, like most shells (including DOS shells) do. The actual matching is done by fnmatch, so if you want to use globular expressions (somewhat) like regular expressions, you want fnmatch, not glob. -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From Peer.Griebel at entire.de Wed Sep 18 07:35:38 2002 From: Peer.Griebel at entire.de (Griebel, Peer) Date: Wed, 18 Sep 2002 13:35:38 +0200 Subject: Copy with __slots__ Message-ID: <673E8D215B3BD311A9C90090279BBB8402829E7A@mail.ebssoftware.de> Hi, I just discovered another problem. It seems that objects which are instances of new style classes (derived from object) are not copied correctly. Here is an example: class C1(object): __slots__ = "s1"; class C2(C1): __slots__ = "s2"; class C3(C2): pass o1 = C1() o2 = C2() o3 = C3() print o1.__slots__ # prints s1 print o2.__slots__ # prints s2 print o3.__slots__ # prints s2 o1.s1 = 11 o2.s1 = 21 o2.s2 = 22 o3.a = 5 import copy p2 = copy.copy(o2) print p2.s2 # attribute s2 does not exist (has not been copied) The last print statement fails with the an AttributeError. Since o2.__slots__ does not know about the slots of the parent class (C1), it would not be sufficient to simply copy all elements in o2.__slots__. All parent classes had to be inspected also. So how can o2 be copied efficiently? connection reset by Peer -- Dr. Peer Griebel Tel: +49(0) 731 / 9 74 95-0 Dipl. Inform. Fax: +49(0) 731 / 9 74 95-20 Entire Software AG mailto:Peer.Griebel at entire.de Pfarrer-Wei?-Weg 10 - 12 D-89077 Ulm http://www.entire.de From lists at gregfortune.com Thu Sep 12 15:38:14 2002 From: lists at gregfortune.com (Greg Fortune) Date: Thu, 12 Sep 2002 12:38:14 -0700 Subject: problem with lists References: <20020911215423.GA30455@habana.easygolucky.de> Message-ID: <3d80eb7f$0$311$39cecf19@nnrp1.twtelecom.net> Uwe Schmitt wrote: > Sean 'Shaleh' Perry wrote: >>> Manuel > >> You want to use : > >> if fields[3:4] not in domains: >> domains.append(fields[3:4]) > >> .index() only works if the item is actually in the list. > > At least you should wrap the line with .index in a try/except pair... > But the solution with "in" is preferable. > > Greetings, Uwe > > Or simply use .count instead of a try/except block. if(domains.count(fields[3:4]) == 0) will work exactly like 'not in'. In this case, I would prefer the 'not in' option, but wrapping a .index in a try/except seems like a huge overkill. IMHO, avoid exceptions if possible. Greg Fortune Fortune Solutions From steve at ferg.org Mon Sep 9 09:52:12 2002 From: steve at ferg.org (Stephen Ferg) Date: 9 Sep 2002 06:52:12 -0700 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> Message-ID: > you'd better include a clear warning... > that you'll explain how to do it correctly > later... Can you say a little more? What is it that makes using "bind()" incorrect? And what is it about using "command" that avoids the problems? This is a genuine request for information, not a challenge to your statement. I am still learning about Tkinter features. From BPettersen at NAREX.com Mon Sep 9 17:52:08 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Mon, 9 Sep 2002 15:52:08 -0600 Subject: Windows/DOS: double clicking a .py file Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019201253172@admin56.narex.com> > From: Just [mailto:just at xs4all.nl] > > Sorry if this is a Windows FAQ, I'm a newbie to Windows, but not to > Python. > > If I double-click a Python script (or use the start command > in the dos > prompt) a new dos prompt window is opened and my program is run. The > window goes away when the program is done. However, the window _also_ > goes away when the program raises an exception, making it virtually > impossible to actually _see_ the exception... Is there a way > to keep the > dos prompt window in this case? Try something like the following... We've had much success with automatically emailing the traceback back to the developer using the cgitb module -- you can never trust users to give you good error reports besides the cgitb module provides much more context than the standard exceptions... Let me know if you'd like the code... try: your code here except: import msvcrt, traceback traceback.print_exc() print 'Hit a key to exit' while not msvcrt.kbhit(): pass -- bjorn From cliechti at gmx.net Mon Sep 23 17:00:02 2002 From: cliechti at gmx.net (Chris Liechti) Date: 23 Sep 2002 23:00:02 +0200 Subject: Python and cgi and problem! References: Message-ID: "CheapSkate" wrote in news:ammn6e$lj7$1 at lust.ihug.co.nz: > Hi Im currently making a cgi script in python which list all the > files&directory in a directory and list them into an html file with > all the files linked to the actual file. > ..... did what I just said make any sense? > > Currently I can list all the files and directories and print it out in > the html file. > my problem now is how to add the anchor tag ??? > > here is the line which prints the files&directories in the html file: > print crap > > , where crap is a filename such as colour.txt print '%s' % (filename, filename) chris -- Chris From manuel at hendel.net Wed Sep 11 07:51:18 2002 From: manuel at hendel.net (Manuel Hendel) Date: Wed, 11 Sep 2002 13:51:18 +0200 Subject: deleting the first and the last character of a string In-Reply-To: <3D7F2960.20507@Linux.ie> References: <3D7F2960.20507@Linux.ie> Message-ID: <20020911115118.GE2054@partagas.as.de.cw.net> On Wed, Sep 11, 2002 at 12:30:40PM +0100, Padraig Brady wrote: > How about: line = line[1:-1] This worked quite good, but I found another problem. There seams to be trailing whitespaces. I tried to strip(s) to get rid of them, but this doesn't work, I get the following error message: Traceback (most recent call last): File "./pop3create.py", line 9, in ? print strip(line) NameError: name 'strip' is not defined What's wrong here? manuel -- Technological progress has merely provided us with more efficient means for going backwards. -Aldous Huxley From keith_oconnell at blueyonder.co.uk Fri Sep 20 06:20:48 2002 From: keith_oconnell at blueyonder.co.uk (Keith O'Connell) Date: Fri, 20 Sep 2002 10:20:48 GMT Subject: finding last match in a file References: <87r8fplvq4.fsf@smtp.blueyonder.co.uk> Message-ID: <877khh6jy7.fsf@smtp.blueyonder.co.uk> >>>>> "Dag" == Dag writes: Dag> The problem is that greping through large files with a fairly Dag> complex regexp is taking far too long, esp. when I know that Dag> the last occurance is almost always within the last 100 Dag> lines. How about tail -n 100 ? Keith -- ___________________________________ _ Keith O'Connell. -o) Maidstone, Kent. (UK) /\\ keith_oconnell at blueyonder.co.uk _\_v From dgallion1 at yahoo.com Wed Sep 18 22:23:24 2002 From: dgallion1 at yahoo.com (darrell) Date: Thu, 19 Sep 2002 02:23:24 GMT Subject: Catching results of an exec References: <3d88f701$0$304$39cecf19@nnrp1.twtelecom.net> Message-ID: exec("a=dir()") print a --Darrell Greg Fortune wrote: > Is there any way to "catch" the value produced by an exec? I'm > considering things like print statements that don't really assign a value, > but do send a result to stdout. > > For example, if I execute > > exec('print dir()') > ... From spoermeg at voldelig.com Mon Sep 16 00:31:38 2002 From: spoermeg at voldelig.com (Terje Johan Abrahamsen) Date: Sun, 15 Sep 2002 23:31:38 -0500 Subject: Source code Message-ID: If I would like to write some code that would not be possible for others to read, after I distribute the program, would Python be suitable? I know that there are a few programs like Py2Exe, that creates .exe files. But, I also saw this: -------------------- A zip-compatible archive is built, containing all files from this directory as well as your script, and appended to a custom python interpreter supplied with py2exe. -------------------- Doesn't sound like it is protected very well. Is there some alternative to Py2Exe that can do the job, or should I look for a compiled language instead? From buzzard at urubu.freeserve.co.uk Tue Sep 10 09:37:00 2002 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 10 Sep 2002 14:37:00 +0100 Subject: Graph Layout Algorithms Message-ID: Hello, Just wondering if anyone has implemented anything in Python. I need to lay out my graphs (directed acyclic / undirected / trees) in a reasonably clear way. So if anyone has already implemented anything, or if anyone has advice on appropriate algorithms, I'd be glad to hear about it. Cheers. Duncan From whisper at oz.net Fri Sep 13 16:05:41 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 13 Sep 2002 13:05:41 -0700 Subject: Embed extended Python In-Reply-To: Message-ID: The boost libary is a great C++ embedding/extending library for Python. www.boost.org David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Mathieu Tremblay > Sent: Friday, September 13, 2002 7:57 > To: python-list at python.org > Subject: Embed extended Python > > > Hello, > I am quite new to Python and I'd like to embed extended python. > The problem is that the documentation I can find on the internet is > always related to C standard types and not to C++ objects. > > To extend python I use the really good SWIG tool and everything is > fine. The problem comes when I try to call a python script that takes > as an argument one of the class that I have defined in C++ through > swig. > > Exemple: > C++ class extended to python with SWIG, through the module wheel: > CWheel > { > CWheel(){} > ~CWheel(){} > printWheel() > { > printf("I am a wheel"); > } > }; > Now, let's suppose that the module is successfully exported and can > be used in python. An example of simple python script would be : > import wheel > > def thefunction(awheel): > awheel.printWheel() > > Calling this function directly from python (supposing we provide the > correct argument) works perfectly. The problem comes when I want to > call this script from C++. Maybe It is a stupid question but here it > is: How do you pass an existing CWheel as an argument to the function > from C++??? How do you wrap a CWheel to a PyObject? > I guess the method would be to use the function > PyObject_CallObject(pFunc, pArgs); the pArgs being a PyTuple where I > can set a PyObject to a position X. The problem is that all the > examples that I find convert int, char*, long, double etc. to PyObject > with built in python functions but no different/user defined class. > Anybody can help? > > Thanks a lot, > Mathieu > -- > http://mail.python.org/mailman/listinfo/python-list From rpm at wag.caltech.edu Mon Sep 9 11:39:48 2002 From: rpm at wag.caltech.edu (Rick Muller) Date: Mon, 09 Sep 2002 08:39:48 -0700 Subject: Can't exponentiate zero in NumPy References: Message-ID: I found out more about this problem, and I'm still hoping that someone can suggest a good fix. The problem comes when I take a power of a NumPy array that has very small values in it: >>> from Numeric import * >>> a = zeros(3,Float) >>> a**2 array([0., 0., 0.]) >>> a[1] = 1.e-310 >>> a**2 Traceback (most recent call last): File "", line 1, in ? OverflowError: math range error This crashes on Linux, but not on Mac OS X. Is this a bug or a feature? If it's a feature (which it might be), can someone offer a one-line workaround? What I would like to do is set everything below a small value (say 1.e-16) to zero. Obviously, >>> for i in range(len(a)): if a[i] < 1.e-16: a[i] = 0 or something like it should work, but it will also be slow, and I was hoping that one of the Numeric UFuncs might do the same thing more effectively. Thanks in advance for any help anyone can offer. Rick From andres.meza at nuevosmedios.ws Thu Sep 12 11:37:04 2002 From: andres.meza at nuevosmedios.ws (Andres Meza) Date: Thu, 12 Sep 2002 10:37:04 -0500 Subject: How to upload files using mod_python? Message-ID: <1031845024.2957.154.camel@coraje> Greetings. I have created a python CGI script that can upload files sucessfully. Now, I want to create a mod_python script with the same feature using the "publisher" handler and I get this error: [Thu Sep 12 08:53:41 2002] [error] PythonHandler mod_python.publisher: Traceback (most recent call last): [Thu Sep 12 08:53:41 2002] [error] PythonHandler mod_python.publisher: File "/home/mrnet/rpm/tmp/mod_python-root/usr/lib/python2.2/site-packages/mod_python/apache.py", line 193, in Dispatch [Thu Sep 12 08:53:41 2002] [error] PythonHandler mod_python.publisher: File "/home/mrnet/rpm/tmp/mod_python-root/usr/lib/python2.2/site-packages/mod_python/publisher.py", line 104, in handler [Thu Sep 12 08:53:41 2002] [error] PythonHandler mod_python.publisher: File "/home/mrnet/rpm/tmp/mod_python-root/usr/lib/python2.2/site-packages/mod_python/publisher.py", line 308, in __init__ [Thu Sep 12 08:53:41 2002] [error] PythonHandler mod_python.publisher: AttributeError: 'file' object has no attribute '__methods__' Anyone have an idea about why I get this error? Thanks for your time, -- Andr?s Meza Technical Manager __Nuevos Medios - NM S.A.____________________ e-mail: andres.meza at nuevosmedios.ws day time phone: (+572)6827794 ext.102 url: www.nuevosmedios.ws -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerhard.haering at gmx.de Tue Sep 10 12:39:19 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 10 Sep 2002 16:39:19 GMT Subject: Trouble upgrading to 2.2.1 References: Message-ID: Robert Oschler wrote in comp.lang.python: > I'm trying to upgrade from 2.1.1 to 2.2.1. I'm using kpackage (KDE's rpm > wrapper). My recommendation is to learn to use rpm directly. > When I try to install from the rpm file named > "python2-2.2.1-1.i386.rpm" I get the following dependency errors: > > libcrypto.so.2 > libsel.so.2 That should probably be libssl... > How can I correct this, or, is there an easier way to get upgraded? You should install the OpenSSL libraries in order to fulfill these dependencies. If you do have the OpenSSL libraries installed, but the libcrypto or libssl version numbers are different on your machine, you can try to provide the necessary symlinks so rpm will shut up. If you know what you're doing, you can always use the --force argument for rpm, but unless you fix your dependencies, socket and all Python modules that build on top of it (smtplib, urllib, ...) likely won't work. I guess you have that Python RPM from the KRUD site, so perhaps you can find upgrades for OpenSSL at the same place. -- Gerhard From bh at intevation.de Tue Sep 24 08:36:50 2002 From: bh at intevation.de (Bernhard Herzog) Date: 24 Sep 2002 14:36:50 +0200 Subject: Three dumb questions (ordered by dumbness descending) References: <82Zj9.136094$ub2.2966822@news1.tin.it> Message-ID: Alex Martelli writes: > Once you do have a random or pseudo-random generator that fully > satisfies you, Ian Bicking's snippet reimplementing shuffle as a > Decorate-Sort-Undecorate idiom is truly excellent -- a little jewel, > IMHO, despite the little typo in it. It does, alas, end up a > little slower than Tim Peters' original -- but losing a speed > competition to Tim is no shame, and Ian's version only loses very > very little indeed. To wit (having corrected Ian's typo): [...] > def shuffle_ian(x): > newList = [(random(), i) for i in x] > newList.sort() > x[:] = [i[1] for i in newList] What's missing, though, is a proof that shuffle_ian produces each possible permutation with the same probability (assuming random() has suitable properties) One problem I can see is that there's a non-zero chance that there will be at least two equal random numbers in newList in which case the corresponding values of x are used to sort newList. This skews the probabilities and furthermore means that shuffle_ian can only shuffle lists whose items can be ordered which among others exludes complex numbers. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://mapit.de/ From sismex01 at hebmex.com Wed Sep 4 19:11:51 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 4 Sep 2002 18:11:51 -0500 Subject: Bind threads to addresses -- Windows & urllib? Message-ID: > > It's a machine with multiple IP addresses bound to one > adapter. I want each spider thread to use a different > address... > > -- > Nick Arnett > Phone/fax: (408) 904-7198 > narnett at mccmedia.com > That's not gonna help you at all, because all threads will be capped by the interface's top throughput, or by your machine's processing power. What you want, or rather, are trying, is, if I recall correctly, is to bind a cpu (in case of a multi-cpu machine) to a certain adapter. That's doable, but you need a specific M$ utility to do that. But in this case, since all threads are gonna be drinking from the same fountain, is doesn't matter if one thread likes orange, another strawberry, and another chocolate. -gus -- Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From aleax at aleax.it Wed Sep 25 05:04:08 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 09:04:08 GMT Subject: summary: (was: callback + __call__ + TypeError: unbound method; on non method) References: Message-ID: Volker Apelt wrote: > ## Thank you, Alex Martelli for your help on this problem. You're welcome, but: ... > class replacement for staticmethod and add a second > group of () to the call. The "second group of ()" is needed only because: > def call_me(): > return time.time CALLING call_me returns (doesn't CALL) the function object time.time. Therefore: > class Callback_good: > _default_Func = staticmethod(call_me) #class wide default callback now Callback_good._default_Func is a callable returning a callable when called, therefore: > def __init__(self): > self._m_func = Callback_good._default_Func > > def __call__(self): > # uncomment one of these > #return self._m_func()() # for python < 2.2 > #return self._m_func() # for ptyton >= 2.2 Nope -- with your current definitions you need ()() in any version of Python. I have another preference, anyway: class Callback_better: _m_func = staticmethod(call_me()) # record the final-callable def __call__(self): return self._m_func() No need for __init__: self._m_func defaults to Callback_better._m_func unless specifically set as an instance attribute of self. This works either in 2.2, or 2.1 with the staticmethod class I proposed (comes from the Python Cookbook, by the way -- both the online version, and the enhanced one we edited into an O'Reilly printed book:-0). Alex From loewis at informatik.hu-berlin.de Mon Sep 9 10:13:59 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 09 Sep 2002 16:13:59 +0200 Subject: xml.minidom is stripping out my CRLF's in attrib values!! References: <3D7C80C4.9070204@NOSPAMbitbuilder.com> <3D7C8C76.8060700@NOSPAMbitbuilder.com> Message-ID: Ahmad Baitalmal writes: > That's not what my problem is, that I know about ( crlf's between nodes),, > > Here is the deal: > > > > > After the word "spotted" there is a crlf, -inside- the attribute > value. Sholdn't it be treated as part of the value? > > The value now comes stripped of that crlf. What do you mean by "stripped of"? What is the exact value that you get? Regards, Martin From sholden at holdenweb.com Sun Sep 29 06:18:34 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 29 Sep 2002 06:18:34 -0400 Subject: help References: Message-ID: "Juliana Braga" wrote in message news:amqclg$6uu$1 at server.ltid.inpe.br... > I need help. > For example: > x = ?name1? > How can I get the value of variable x (in this case the value of variable x > is ?name1?). After , I?d like to do this: > value of variable x = ?teste?. > Juliana: Your question is a little difficult to understand, so you may get several answers. I suspect that what you were looking for is: >>> x = 'name1' >>> exec x + "= 'teste'" >>> name1 'teste' >>> While this works, however, please remember that almost all such uses of "exec" are simply making trouble for you as a programmer. The code must be compiled at run-time, and whenever you need to access the variables you create in this way you have to resort to further use of the exec statement. It will probably be more appropriate to use a dictionary to hold the values you create. A dictionary can use many different datatypes as keys, and in particular strings are fine. So you might want to try something like: >>> adict = {} >>> adict[x] = "teste" >>> adict["name1"] 'teste' >>> There's a lot of similarity between dictionaries and Python namespaces (for the altogether predictable reason that Python currently *uses* dictionaries to implement namespaces). When you want to use program-determined "variable names" then a dictionary is often the solution. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From ak at silmarill.org Thu Sep 19 00:10:58 2002 From: ak at silmarill.org (Andrei Kulakov) Date: Thu, 19 Sep 2002 04:10:58 GMT Subject: Writing linux term color codes to a file References: Message-ID: On Wed, 18 Sep 2002 14:41:51 +0200, stasZ wrote: >On Wed, 18 Sep 2002 03:09:37 +0200, Andrei Kulakov wrote: > >> Hello, >> >> I ran into a bit of a problem here.. I'm making a small app that >> visually creates bash prompts (just for fun of it), and at one point it >> has to write the prompt to .profile, optionally with linux terminal >> color codes, like \[044;\]m or something like that (you know what I'm >> talking about). They don't come out right *in* the file. I tested the >> simple case where I'd have a few such codes in a string in python prompt >> and I'd look at it and it looks fine, but as soon as I write it out to a >> file and look at the file, it's "cooked". >> >> I hope you know what I mean, if anyone wants I can post direct pastes. >> >> Looks like write() does some sort of processing on the text; is there >> any way to turn that off? > >>>>prompt = r'\[044;\]' >>>> prompt >'\\[044;\\]' > >>>> f = open('/home/foo/prompt,'w') >>>> f.write(prompt) >>>> f.close() > >$ more prompt >\[044;\] > >I think your problem is solved if you use a raw string (r'spam'). >With a raw string the backslash is just a backslash. Thanks, I think that's it. I'll try it tonight. You've been doubly helpful - that' sthe funniest sig I've seen this month. :P > >Stas Z From rjones at ekit-inc.com Wed Sep 4 20:13:48 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 5 Sep 2002 10:13:48 +1000 Subject: Daemonize? In-Reply-To: References: Message-ID: <200209051013.48248.rjones@ekit-inc.com> On Wed, 4 Sep 2002 11:36 pm, sismex01 at hebmex.com wrote: > Sorry to ask here, but I don't have any "unixy" python > documentation at hand. > > Normally, I put an app into "daemon" mode, by first > forking, then reopening stdin/out/err to /dev/null, > and then forking again. Works good enough for my > purposes. Note you can also just assign an object with a write() method that does nothing to sys.std(out|err) and a similar object to sys.stdin. Why the second fork, btw? > But, am I right? Is this the correct way to do this? > Also, I can't find any "reopen" in python to apply > to sys.stdin/out/err. All that stuff is handled for you. Simply assigning to the std* attributes is enough. Note that in python 2.1+ the "old" sys.std(in|out|err) handles are still available as sys.__std(in|out|err)__ if you really need them. Richard From clspence at one.net Wed Sep 11 17:17:10 2002 From: clspence at one.net (Chris Spencer) Date: 11 Sep 2002 16:17:10 -0500 Subject: How do I capture just a single keystroke? References: Message-ID: <7acvnu0p1maai2nnvle5ucjla1qk9v8k5u@4ax.com> Nevermind...I found the answer. For those who are interested, this is it. It should work on both Unix and Windows... def getch(): try: import msvcrt return msvcrt.getch() except: import tty,sys,termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch Chris. From peter at engcorp.com Sat Sep 7 00:14:00 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 07 Sep 2002 00:14:00 -0400 Subject: horizontal scrollitis? (was Re: Larry Wall's comment on python...) References: Message-ID: <3d797cef$1@news.sentex.net> mmaddox at hcsmail.com wrote: > You're right. The PLACEMENT of blocks in my style is arbitrary. My > intention was to indicate the STYLE of block delimiting was arbitrary Probably also not true. I believe many of the choices made for Python in its early stages were made after both experience *and* experimentation with alternatives. Not sure about the block delimiters (or invisibility thereof) themselves, but certainly things like the use of the colon before a block were made because of studies suggesting they were a Good Thing. > Now, I LOVE Python. I also love C++. Smalltalk and Lisp are interesting. > Perl is useful to someone somewhere. I said some things that are not as > precise as I would have liked, and I don't want to explore the semantics > of this mailing list and each individual post. Python is cool. Let's talk > about Python. My post talked exclusively about Python, so I agree with that idea. :) Maybe you would still respond to the other Python-related question I asked: >>I definitely don't understand how Python, more or less than any other >>language, leads to more horizontal scrolling. Pretty much all >>Python code I've ever seen (though I haven't seen yours yet :-) is >>roughly 80 characters max, and mine own has been about that since I >>started writing C code 16 years ago. >> >>Do you mean there is something special about Python not delimiting >>blocks in the traditional ways which somehow leads you to write >>much wider lines of code? -Peter From cmay4 at yahoo.com Tue Sep 24 18:17:52 2002 From: cmay4 at yahoo.com (Chuck May) Date: Tue, 24 Sep 2002 22:17:52 GMT Subject: Limit number of concurrent threads References: Message-ID: Ok...I think I've got it. Thanks for everyone's help. How does this look: from threading import Thread import Queue, time, random maxthreads = 5 # maximum number of concurrent threads totalops = 80 # hold total number of operations class Worker(Thread): def __init__(self, q): Thread.__init__(self) self.q = q def run(self): all_done = 0 while not all_done: try: table = self.q.get(0) time.sleep(random.randint(10, 1000) / 1000.0) print "id %d" % table except Queue.Empty: all_done = 1 if __name__ == "__main__": q = Queue.Queue() for i in range(totalops): q.put(i) threads = [] for i in range(maxthreads): t = Worker(q) threads.append(t) t.start() # wait for all threads to complete for t in threads: t.join(); print "Al done!" Syver Enstad wrote in news:uwupbdwnj.fsf at online.no: > Chuck May writes: > >> I've searching for examples that fit my problem, and I haven't found >> any. Most examples I've found look something like this: >> >> threads = [] >> for i in range(number_of_tasks): >> thread.append(thread_for_task) >> >> # let the threads run - just wait for shutdown >> for t in threads: >> t.join() >> >> which whould work fine if I wanted to start all 80 threads at once. >> >> I've read about the Queue, but I'm not sure if it's what I want, and >> I >> >> can't seem to find any good examples on it. > > I think Queue would be nice to use, Have a thread (the main thread > perhaps) feed all the table names (or a table object if you please) > into a Queue. > > Set up some worker threads with access to the Queue > (global variable, member). The worker threads should loop something > like this: > > while 1: > queueItem = self._queue.get() > doSomethingWithQueueItemHere > > Then you can start your workers. > > (You'll have to find out some way to make the workers exit when the > work is done, perhaps putting a number of None's equal to the number > of workers last in the queue and testing for None in the working > thread loop. > > -- Chuck May IMS, Inc. From marklists at mceahern.com Wed Sep 18 17:17:38 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 18 Sep 2002 16:17:38 -0500 Subject: multiple index inconsistency In-Reply-To: Message-ID: [bert] > The following line of code > >>> a = 3*[range(3)] > produces > [[0, 1, 2], [0, 1, 2], [0, 1, 2]] > > If I then write, say, > >>> a[0][1] = 3.7 > I get > [[0, 3.7, 2], [0, 3.7, 2], [0, 3.7, 2]] > and not > [[0, 3.7, 2], [0, 1, 2], [0, 1, 2]] > > Now if I write > >>> a = [[0, 1, 2], [0, 1, 2], [0, 1, 2]] > instead, and then > >>> a[0][1] = 3.7 > I get the result I expected (and wanted): > [[0, 3.7, 2], [0, 1, 2], [0, 1, 2]] > Why the inconsistency? Is this a bug or am I missing something? Short answer: lists are mutable. ints aren't. So when you do this: a = 3 * [range(3)] you're basically doing this: l = range(3) a = 3 * [l] The result is effectively: [[l], [l], [l]] when you modify one of the lists, "all of them" are affected. A better approach: x = 3 y = 3 a = [range(x) for x in range(y)] (I assume x and y are different in theory.) Now, try this: for x in a: print id(x) and compare that to the list generated by 'a = 3 * [range(3)]' Cheers, // mark - From eworrall at netcomuk.co.uk Sun Sep 29 13:15:19 2002 From: eworrall at netcomuk.co.uk (Eric Worrall) Date: Sun, 29 Sep 2002 18:15:19 +0100 Subject: Linker can't find library (PyProlog setup) References: <0iGl9.14200$Lg2.4065036@news2.news.adelphia.net> Message-ID: <3D973527.A9D39B4E@netcomuk.co.uk> Robert Oschler wrote: > > "Robert Oschler" wrote in message > news:mdGl9.14197$Lg2.4064162 at news2.news.adelphia.net... > > > Ugh, forgot to point out that I am running those commands from within a > script file. > > thx Q&D solution - create symbolic links in the default library path and point them to the libraries you want to include, for example: ln -s /usr/lib/termcap/libtermcap.so.whatever /usr/lib/libtermcap.so Eric Worrall -- You have just received an Etech Solution For all your Linux requirements contact eworrall at netcomuk.co.uk From aleax at aleax.it Mon Sep 23 03:25:24 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 23 Sep 2002 07:25:24 GMT Subject: mySQL and Python 2.2 References: Message-ID: Greg & Janet LINDSTROM wrote: > Hello- > I am trying to convert from gadfly to mySQL for my database needs on > my Windows 98 box. I have installed mySQL and it works (I have > created my tables and can manipulate them manually), and have > downloaded mySQL-python-0.9.1, but when I python setup.py build, I > get an error about cl.exe not existing (and, sure enough, it > doesn't :-). > > I'm running Windows 98 with Activestate Python2.2. Any help you > could supply (including code snippets of how to get connected to > MySQL once I get it running) would be appreciated. You seem to be trying to build from sources without having the needed C compiler (that's what cl.exe is -- the executable that calls the compiler and linker under Microsoft Visual C++). If you don't have a C compiler, you can't build C-coded Python extensions from sources: you need to find and install pre-built binary versions of those extensions for the Python version you are using. You can find many such versions listed at (LONG URL, mail sw might break it -- if so, then rejoin it...): http://sourceforge.net/project/showfiles.php?group_id=22307&release_id=102893 Click on the link shown as (for example): MySQL-python-0.9.1.win32-py2.2.exe if you use Python 2.2 (there are other pre-built binaries for older versions, should you need those). Running that EXE after downloading it should then install all you need. I think you can also find pre-built binaries of MySQLdb 0.9.2, for example at Gerhard H?ring's page, but I'm not sure about the details -- Gerhard mentions said binaries at http://www.cs.fhm.edu/~ifw00065/news.shtml but gives no link and I can't find them. Alex From gerhard.haering at gmx.de Fri Sep 6 19:50:26 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 6 Sep 2002 23:50:26 GMT Subject: py2exe and a single exe file? References: <3D792351.3070008@motorola.com> Message-ID: Stephen Boulet wrote in comp.lang.python: > I'm trying to get py2exe to work for me, and I must be doing something > wrong. > > [...] It builds and runs, but only with the other stuff in the build > directory with the generaged exe. The other stuff is: > > tcl directory containing tcl8.3 and tk8.3 directories > _numpy.pyd > _sre.pyd > _tkinter.pyd > multiarray.pyd > umath.pyd > > What I would like to accomplish is just having a single exe file > lumping everything together. Is this possible? No. If you want to distribute the output of py2exe, use an installer like NSIS or just zip it up. Gordon McMillan's installer has means to do what you want, but it also needs to unpack .pyd and .dll files at runtime, which it will delete afterwards. So it basically cheats, which is logical, since you can't statically link shared libraries, at least not on Windows. -- Gerhard From root at [127.0.0.1] Mon Sep 16 22:37:43 2002 From: root at [127.0.0.1] (nobody) Date: Tue, 17 Sep 2002 12:37:43 +1000 Subject: stdin on Win32 References: <3d865d34$0$22177$afc38c87@news.optusnet.com.au> <3d868e43$1@news.sentex.net> Message-ID: <3d869577$0$22173$afc38c87@news.optusnet.com.au> > Which flavour of Win32? 2K and XP > Win98 needs you to explicitly invoke Python and pass the test.py name as a command line Yes that worked. I guess I'll have to write a wrapper script around it.. From sholden at holdenweb.com Tue Sep 17 12:23:47 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 17 Sep 2002 12:23:47 -0400 Subject: More on Protecting Source Code References: Message-ID: "David LeBlanc" wrote in message news:mailman.1032247760.982.python-list at python.org... [ ... ] > Well, I think of it this way: machine coded binaries are more like a 128 bit > key and Python is more like a 40 bit key. I agree that nothing is safe from > reverse engineering; it's a matter of how much pain and money it takes to > unscrut the inscrutable. Python could do better - how I'm not totally sure. > Well, when you are, please submit a patch to SourceForge. Until then, perhaps you could focus your efforts on solving the problem? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From mhammond at skippinet.com.au Sat Sep 7 20:04:08 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 08 Sep 2002 00:04:08 GMT Subject: Using Python to call a DCOM server - "'Class not registered" References: <3D787D95.9000907@ob_scure.dk> <5%ce9.1272$_l1.2960@news-server.bigpond.net.au> <3D7A1359.4010607@ob_scure.dk> Message-ID: Thomas Jensen wrote: > Is it safe to say that "ActiveX DLL" = InprocServer32 and "ActiveX EXE" > = LocalServer and that I need the later to use DCOM? (I have some > existing components that I'd rather keep as DLL - don't know why really? > :-) Yep. InProcServer32 means that the COM object is implemented in a DLL, and loaded into the calling process. LocalServer means it is an executable, and loaded into a separate process and IPC used across boundaries. For DCOM, there is no way the object can be loaded into the same process, so executable based servers must be used. Mark. From david.abrahams at rcn.com Fri Sep 27 21:44:33 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Fri, 27 Sep 2002 21:44:33 -0400 Subject: Is Boost Python version 2 ready? References: Message-ID: From: "Christian Tismer" > David Abrahams wrote: > > From: "Christian Tismer" > > > >>I have been asked whether Boost will be compatible with > >>Stackless (or vice versa:). > >>Who else could answer that better than you? > > > > > > Well, I have never tested it with Stackless, but in the end it only does > > "ordinary extension module stuff". What is it, precisely, you need to watch > > out for? Something about callbacks from C++ into Python with data on the > > stack? > > Exactly :-) > Probably nothing you would do unless enforced to? AFAIK I'm never doing that myself. It's possible for someone to write a construct in an extension module that does that, but they'd have to go out of their way to shoot themselves in the foot. HTH, Dave ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From shalehperry at attbi.com Wed Sep 11 17:53:23 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 11 Sep 2002 14:53:23 -0700 Subject: [FEEDBACK] Is this script efficient...is there a better way? In-Reply-To: References: Message-ID: <200209111453.23751.shalehperry@attbi.com> On Wednesday 11 September 2002 14:01, Bob X wrote: > > # build list of keywords > kw = [ "some", "words" ] > > # loop through the list and print the lines to a file > for line in inFile.readlines(): > for badword in kw: > if line.find(badword) > -1: > result = '%s %s' % (badword, line) > print result # Print the result > outFile.write(result) # Write the result > > # close the files > inFile.close() > outFile.close() > > # let me know when it's done > print "Finished processing file..." 1) readlines() loads the entire file into a list so if you have a 30+ mb file you just ate 30+mb of memory. Try using xreadlines() instead, it reads the file line by line and is much more memory friendly. 2) do you expect to find more than one keyword in a particular line? If not you could save some iterations by stopping the inner line.find() loop as soon as one item is found. As a final comment you need to be aware that the more keywords you look for the slower this will be. However there is not a way to get around that, it is just something to keep in mind. From aglyportREMOvethispart at nospam.yahoo.com Wed Sep 4 20:11:37 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Wed, 04 Sep 2002 17:11:37 -0700 Subject: Memory fault - core dumped while compiling python 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> <3D765A05.6030004@nospam.yahoo.com> <3D768753.8030302@nospam.yahoo.com> Message-ID: <3D76A139.1030304@nospam.yahoo.com> Martin v. Loewis wrote: > Anton Graph writes: > > >>python -E setup.py build in gdb: >> >>(gdb) where >>#0 0x80016d06 in do_reloc () from /usr/lib/libc.so.1 > > > That sounds like a question to bring to an SCO forum. Apparently, this > crashes when doing relocations while loading the extension > module. This raises a number of questions: > > - Why does it do relocations at all? Could it be that you have object > files that a not position-independent? I.e. is distutils using the > compiler correctly both for compilation, and for linking? > > It might be correct that it tries to perform relocation, e.g. for > the global offset table, and the procedure linkage table - but it > *is* troubling that relocations is where it crashes. > > - What is the precise version of the operating system you are using? > SCO_SV bongo 3.2 5.0.5 i386 > - I'm troubled by the fact that in both configurations (with an > without gcc), the compiler is always referred-to as "cc". Are you > sure you are not using gcc? > I'm positive it's SCO cc: Wed Sep 4 16:17:04 PDT 2002 bongo:/u/src/agl/txb/txt $ gcc -v Reading specs from /usr/local/lib/gcc-lib/i386-pc-sco3.2v5.0.5/2.95.2/specs gcc version 2.95.2 19991024 (release) Wed Sep 4 16:17:07 PDT 2002 bongo:/u/src/agl/txb/txt $ /usr/local/bin/cc bash: /usr/local/bin/cc: No such file or directory Wed Sep 4 16:17:14 PDT 2002 bongo:/u/src/agl/txb/txt $ /usr/bin/cc Usage: cc [ options ] files ... Wed Sep 4 16:17:18 PDT 2002 bongo:/u/src/agl/txb/txt $ /bin/cc Usage: cc [ options ] files ... > Please have a look at > > http://gcc.gnu.org/ml/gcc-testresults/1999-04/msg00239.html > > Notice that the failure mode is quite similar... Likewise, > > http://www.bitmechanic.com/mail-archives/dbi-users/Jun1999/0485.html > > reports such a problem when using gcc on SCO. I see. I doubt the problem is with the compiler though because I have a very similar problem with SCO cc. Maybe it's buggy dynamic linker, libs or 5.0.5 kernel? This maybe irrelevant, but the reason why I thought of migrating to python 2.2.1 was because my program linked against python 1.4 libs all of a sudden began to crash in memory allocation routines. I linked against Electric Fence and it shown a problem caused by this code: .... PyObject *tuple = PyTuple_New(2); .... PyTuple_SET_ITEM(tuple, 1, layout[1]); ^^^^^^^^^^^^^^^^^^^^^^^^^^ bails out with SIGSEGV whenever linked against Electric Fence and python 1.4 libs. Could someone out there tarball Python 2.2.X built on SCO and put it on a ftp site? From aleax at aleax.it Tue Sep 24 10:18:43 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 14:18:43 GMT Subject: Three dumb questions (ordered by dumbness descending) References: <82Zj9.136094$ub2.2966822@news1.tin.it> <2HZj9.260778$AR1.10903907@bin2.nnrp.aus1.giganews.com> Message-ID: <7v_j9.137081$ub2.2977680@news1.tin.it> Terry Reedy wrote: > > "Alex Martelli" wrote in message > news:82Zj9.136094$ub2.2966822 at news1.tin.it... >> Once you do have a random or pseudo-random generator that fully >> satisfies you, Ian Bicking's snippet reimplementing shuffle as a >> Decorate-Sort-Undecorate idiom is truly excellent -- a little jewel, > > How is an O(n*log(n)) algorithm a 'jewel' compared to the simple and > standard O(n) algorithm? Not performance-wise, by any means -- it just LOOKS deucedly pretty!-) >> It does, alas, end up a little slower than Tim Peters' original -- > [...] >>and Ian's version only loses very very little indeed. > > Increase n enough and it becomes arbitrarily slower and loses > arbitrarily much. You're right -- I should have mentioned that. If you must shuffle lists whose length N you cannot bound, AND you have no other bottlenecks in your program that are worse than O(N log N), then introducing an O(N log N) bottleneck is clearly out of the question. Alex From thorsten at thorstenkampe.de Tue Sep 10 17:54:31 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 10 Sep 2002 23:54:31 +0200 Subject: Python primer - comments appreciated! References: Message-ID: * Terry Reedy > "Thorsten Kampe" wrote in message > news:aljdhe$1q63hj$1 at ID-77524.news.dfncis.de... >> def quotient_set(seq, func, partition='nonbool'): >> """ partition into equivalence classes > > To my mind, you should return a dictionary mapping each realized value > of func (assuming hashable) to the list of items for which func has > that value. In other words, result.values() would be the list of > equivalence classes. Let caller toss away info of value defining > class. In any case, using a dict to sort items into such classes > should be much faster that what you wrote. > > def equiv_class(seq, func, part = 'nonbool'): > if part == 'bool': > result = {False:[], True:[]} > for item in seq: > result[bool(func(item))].append(item) Using the 'bool' function and dictionaries makes my whole "if part == 'bool'" branch superfluous - see below. > result.setdefault(func(item),[]).append(item) To make every item hashable, I made this: result.setdefault(repr(func(item)),[]).append(item) > # {}.setdefault(key,default) was added for just this sort of usage Sorry, I just don't get it: your mixing (chaining?) a dict method and a list method as if it was a f(g(x)) and /it works/!?! Where is that documented? How is is that evaluated (left to right)? > >>> f = lambda x: x % 3 > >>> equiv_class([0,1,2,3,4,5,6,7,8,9],f,part='bool') Now this is: quotient_set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], lambda x: bool(x % 3)) (Mathematically spoken, the quotient set is the set of all equivalence classes induced by func, which is what we return) Thorsten From aahz at pythoncraft.com Wed Sep 11 13:06:13 2002 From: aahz at pythoncraft.com (Aahz) Date: 11 Sep 2002 13:06:13 -0400 Subject: Multi-threading python References: Message-ID: In article , David Brown wrote: > >If C code (or other extensions) that take significant time, or block for >other reasons, release the GIL then there I suppose there is not going to be >much of a problem. The point is to maximize the throughput, and avoid >threads blocking each other unnecessarily. Yup. >It sounds like that is only true for code that does a lot of work in pure >python (rather than with time-consuming, GIL-released C code). Yup. >Thanks for the information - it was definitely helpful. It looks like the >system used by Python will work fine in all but a few situations (SMP system >in which a lot of work is being done in Python itself, rather than in >extension modules - or in badly written extensions which don't release the >GIL before doing heavy work). Such situations can be dealt with by running >two python processes - if a program really needs to do hard SMP work in >python, then that is a small price to pay since I image the GIL simplifies a >lot of things. I had been worried that the Python threading scheme would >have caused more inefficiences (such as all threads stopping while a single >thread was blocked for I/O). Yup. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From see_reply_address at something.invalid Wed Sep 11 21:49:13 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 12 Sep 2002 13:49:13 +1200 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> Message-ID: <3D7FF299.2020509@something.invalid> Stephen Ferg wrote: > What I wanted to do, though, in "Thinking in Tkinter" was more of an > explanation of the basic concepts that you need in programming with > Tkinter. From that standpoint, I think it is better to explain about > binding -- that is, binding widgets, events, and callback handlers -- > by explaining "bind()". Then, once the basic concepts are explained, > I can note how "command" can be used as a labor-saving technique. It might be better to start with some object other than a button for the purpose of introducing the concepts of event binding. Otherwise you're teaching people an incorrect way of using buttons that they're going to have to unlearn later. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From h.g.normann at gmx.de Fri Sep 27 17:05:14 2002 From: h.g.normann at gmx.de (Hans - G. Normann) Date: Fri, 27 Sep 2002 23:05:14 +0200 Subject: how to create QLineEdit.focusOutEvents? Message-ID: Hello I'm new in QT and Python. My first project: creating a GUI for Linux tar command. My prob: A QLineEdit contains a directory name. I can create this name by clicking (Fileselection maodule) or by type in. On lost focus, I want check the Directoryname, but how can I create slots, signals and the event for Line Edit? For creating gui, I'm using QT's designer. It's works fine, except focusOutEvent. Is there a (easy) sample? Hans From jubafre at brturbo.com Tue Sep 17 15:57:16 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Tue, 17 Sep 2002 16:57:16 -0300 (GMT-03:00) Subject: hexacodes in python? Message-ID: <-1995099244.1032292636635.JavaMail.nobody@webmail1> what is the hexacode for '?' in python? where can i take the hexacodes? Juliano Freitas www.gebrasil.hpg.com.br From LogiplexSoftware at earthlink.net Thu Sep 5 14:28:14 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 05 Sep 2002 11:28:14 -0700 Subject: Gratitude due to Red Hat? More work for the PBF? In-Reply-To: References: Message-ID: <1031250495.19985.1180.camel@software1.logiplex.internal> On Wed, 2002-08-28 at 08:33, Trond Eivind Glomsr?d wrote: > Cliff Wells writes: > > > On Tue, 2002-08-20 at 01:59, Steve Holden wrote: > > > I'm a little hesitant to say this, but today (while, of all things, putting > > > a sales proposal together) I realised that my attitude to the "Red Hat comes > > > with 1.5.2" question has now altered. When considering a hosting environment > > > I am happy to *exclude* any company who can only offer 1.5.2, as they are > > > clearly not serious about supporting the language environment. This is a > > > positive thing, as supporting Python isn't yet a common enough skill to be > > > available from the Interlands and the like. > > > > I submitted a bug report to RH regarding this issue and was basically > > brushed off with "the RH tools that depend on Python should all work > > with 2.x if you install all the required packages" [required packages > > thoughtfully omitted]. Heaven forbid *they* should fix anything. > > Fixing it would mean it was a problem. > > A program originally using python 1.5 and newt would, in almost all cases, work > just as well with python 2.1 if the newt module was available. And what of 2.3? 2.4? RedHat's response assumes backwards-compatibility of future versions of Python with all of their scripts and modules. Unless Guido has loaned them his time-machine this probably isn't a safe assumption. Besides "in almost all cases" isn't exactly reassuring. The reality is that most Python developers stay up-to-date with releases of Python and the RedHat-sanctioned version lags behind by months (you refer to 2.1 when I've been using 2.2 for quite some time now). The aggravating thing is that this issue would be a snap for RedHat to fix. Instead of preempting /usr/bin/python for their own use, they could maintain a /usr/bin/python-rh and leave python for user-installed versions (instead of requiring the user version to be called "python2"). Problem solved, everyone happy. > -- > Trond Eivind Glomsr?d > Red Hat, Inc. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From shalehperry at attbi.com Wed Sep 4 11:58:12 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 4 Sep 2002 08:58:12 -0700 Subject: Regexp Over Multiple Lines In-Reply-To: <565e316f.0209040740.36573b56@posting.google.com> References: <565e316f.0209040740.36573b56@posting.google.com> Message-ID: <200209040858.12863.shalehperry@attbi.com> On Wednesday 04 September 2002 08:40, Keith wrote: > In Python can I have a regular expression that spans multiple lines... > e.g. In Perl I may define a regular expression like: > yes you pass the re.compile() function an option of re.WHITESPACE as I recall (but check the docs to be sure of the exact option). From awinston at scn.org Tue Sep 10 11:42:57 2002 From: awinston at scn.org (Alan Winston) Date: Tue, 10 Sep 2002 08:42:57 -0700 Subject: PySol: "global name 'win32_gethomedir' is not defined" Message-ID: I've been trying to run the PySol 4.81 pyc files under Python 2.2.1 and WinXP and Win98, with no success. The Python window closes much faster than I can read the error message (is there any way to force the window to stay open?), but I managed to catch it with the print screen key: "global name 'win32_gethomedir' is not defined" PySol 4.60 runs fine, installed with the Windows install package, so this is a low priority for me, but I am still curious. Alan Winston Seattle From emile at fenx.com Thu Sep 5 00:59:04 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 4 Sep 2002 21:59:04 -0700 Subject: newbie-question: Nested functions and variable scope References: <7a7157fd.0209041503.7b9a0f44@posting.google.com> Message-ID: Leonardo: > If I put "in_reply" outside everything and use "global in_reply" > inside each nested function, it works, but that's evil! What would be > a better way of doing it? Do I need to use a class? Take a look at nested_scopes: ActivePython 2.1, build 210 ActiveState) based on Python 2.1 (#15, Apr 19 2001, 10:28:27) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def level1(): ... ir = 1 ... def lvl2b(): ... print ir ... :1: SyntaxWarning: local name 'ir' in 'level1' shadows use of 'ir' as glo bal in nested scope 'lvl2b' >>> from __future__ import nested_scopes >>> def level1(): ... ir = 1 ... def lvl2b(): ... print ir ... HTH, -- Emile van Sebille emile at fenx.com --------- From maxm at mxm.dk Tue Sep 24 04:53:04 2002 From: maxm at mxm.dk (Max M) Date: Tue, 24 Sep 2002 10:53:04 +0200 Subject: file = open(path,'wb')????? References: Message-ID: <3D9027F0.4080603@mxm.dk> jubafre at brturbo.com wrote: > i open the a file for writing in a binary mode, but doesnt work > > final3=['0020 0000x9', '0030 0000xa', '00B4 0000x8', '0030 0000xb', '00F0', '0001', '0003', '0005'] > destino=raw_input("Digite o nome do arquivo .mem: ") > f = open(destino,'wb') > f.write('\x03AHM ') > for i in final3: > f.write(i+' ') > f.close() > > > i open the file in the notepad and my file appears like a text file and not as a binary file, i dont know why?? > > >>>file.mem >> > AHM 0020 0000x7 0030 0000x8 0010 0000x9 00F0 0003 0002 0000 > > >>>i want the file like this, how?? >> > AHM € 0 ?  ƒ ? You are indeed writing strings to the file. Setting a file to binary mode only affects a few newline characters on Windows. Nothing else. You should use the struct module for writing binary values. 4.3 struct -- Interpret strings as packed binary data regards Max M From LogiplexSoftware at earthlink.net Fri Sep 20 09:36:53 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 20 Sep 2002 06:36:53 -0700 Subject: More on Protecting Source Code In-Reply-To: <3D86E466.6010208@cascade-sys.com> References: <20020917062412.GA85457@hishome.net> <3D86E466.6010208@cascade-sys.com> Message-ID: <1032529013.20661.194.camel@localhost.localdomain> On Tue, 2002-09-17 at 01:14, James J. Besemer wrote: > > Or if I reduce those thoughts to paper or to software or to wood and > metal that somehow everybody else is entitled to share the benefits of > my possibly substantial endeavor? > > What a load of bullshit. Sort of. The idea of "owning" ideas/information is indeed artificial. I don't see how you can argue otherwise. However there are good reasons for having such a concept (as you outline below). However, also note that there are exceptions to intellectual property laws (in the U.S. anyway) where the rights of the author/owner are occasionally diminished in the interest of the common good. It's a balancing act between the two interests (creator and public). The problem that many (including myself) have with the current state of copyright/patent law is that it is often enforced in such a way that the interest of the public is disregarded. Consider the fact that it is still illegal to copy software contained in the ROMs from an Apple //e. Clearly Apple no longer has any monetary interest in maintaining the copyright on that software (the hardware for which it was written is no longer sold) and there is possibly some benefit to releasing it to the public domain (for emulators and whatnot, or possibly as examples for education), but the law continues to protect Apple's "interest" in this piece of code for no apparent reason. I'd suggest that 5 years is adequate time to protect a piece of software, not 35 or 95 or 120 or 70 years after the death of the author (depending upon the particular work being considered). > An artist who creates an image or the specifications for a musical > performance has every right to own his creation and benefit from its > use. This is no different for a programmer and code of his own creation. It is different in that software has a much shorter useful lifespan than a work of art. A book written in 1976 can still be sold and hence has some value. I'll sell you my copy of Wordstar for CP/M, if you're interested. I'm guessing you're not. > Even if you go back to the early industrial age, key products of > industry was intellectual property. E.g., engineers had to produce > drawings and written specifications before they could build a bridge or > a mousetrap. That "information" was every bit their property as the > more tangible artifacts they later sold commercially. An unscrupulous > competitor could use the IP to recreate the commercial artifacts at a > fraction of the original owner's cost. Or he could reverse engineer the > IP and again enjoy an unfair advantage. That's blatantly unfair and > it's a good thing we have laws to protect against such theft. All true. > Now if somebody elects to give away their IP -- out of charity or in > hope of scoring points in some circles -- that's fine. But if he > instead elects to profit from it, in a free world, that should be > perfectly reasonable and respectable also. > > >but it > >can be made more property-like by laws that restrict people's freedom to > >use information. > > > > Copyright laws have precedent dating back to pre colonial England. > Interesting new books and music were intrinsically hard to create but, > (after Gutenberg) once created, they were easy for the unscrupulous to > copy and receive full benefit of their publication. Robbing the > creators the fruits of of their labor is inherently unfair. Not only > does the IP thief unfairly benefit from work he did not perform he also > robs the real owner of income he otherwise would have received. > > Thus IP laws naturally evolved to protect rightful property owners. > It's meet and good. > > People fought and died (and more importantly prevailed) in defense of > the rights to be free and to own property. And others have fought and died to free property from the hands of a privileged few. What does this prove? Nothing except that people fight over property. > Now I don't necessarily support some of the more recent changes and > extensions to copyright laws. Some maybe go a step too far. However, I > don't think they can or should be rejected altogether. At their core > they're not arbitrary; rather in protecting the works' creators they're > the epitome of fairness. The problem is that these laws are usually created as the result of lobbying by groups that have a specific interest in protecting their intellectual property and the interests of the public are just as often neglected. For instance, there is a "fair use" clause for copyright that allows individuals to make archival copies of copyrighted works. I wonder what happens to that right when I buy a copy-protected CD of a game? Who is lobbying to protect that right? The RCIAA? Not likely. > >The state has given you the 'right' to use the power of its court and > >police to forcibly restrict people that use information you have created > >in violation of copy-restriction laws. > > > > Yeah, sure, in your dreams we could instead have laws that say all > information was free. I submit that such a situation would actually > stifle innovation. Sure a few dreamers would still invent but the > volume and time to market would be greatly diminished. > > Lack of ownership is precisely why most socialist countries soon became > and forever remained vast economic wastelands. It may have been one reason, among many. Gross over-simplification weakens your argument. Denying individuals any > incentive for working harder than others, the economy soon deteriorates > to where it can hardly provide the necessities of life let alone invent > clever and innovative luxuries. Worse, collectivist economics are > unnatural in that they fly in the face of most human instincts. Probably true. Thus it > requires a large and oppressive government to enforce collectivism and, > in practice, those governments typically become corrupt. The two or three examples we have available to examine would seem to support this. However, the common American view of equating an economic system (socialism, communism) with a government system (totalitarianism, dictatorship) is flawed. It doesn't seem impossible that there could exist a democratic socialist state any more than it would be impossible to have a capitalist dictatorship. In any case, > economies invariably, immediately revert to capitalism soon as the > communist/socialist oppression ceases. And Russia's economy has flourished ever since ;) Even if we disregard how U.S. trade with Russia has changed since the cold war (and its effect on their economy) there isn't much of an argument to be made here. > It is precisely the promise of commercial reward that makes America the > incredible fount of invention and creativity that it is. And of course the natural resources to make those grand ideas a reality. The simple > formula of rewarding people for their own hard work is what made America > the worlds only superpower. Not only do we have the most powerful > military in the world our people also enjoy one of the world's highest > standards of living. And not at all because we have almost unlimited natural resources or because we use our powerful military to make sure that we obtain other countries' natural resources at a "reasonable" price. Most socialist countries have had to choose one or > the other or don't have the choice of either. > I just don't get you folks who push this Communistic view of economics. > It's childish. Marx sounded good on paper 100 years ago and yeah we > all believed it when we were idealistic teenagers. At the cost of > hundreds of millions of citizens (murdered by their own government) and > a significant fraction of the 20th century's world's human resources, we > gave Communism every chance to succeed. Ah, by giving them a chance to succeed, you must mean by imposing economic sanctions and encouraging them to bankrupt themselves on military spending. To pretend that the USSR collapsed without help from outside forces is stretching it a bit. After almost a century of > experimentation with collectivist economics, the results are all in and > the bottom line is that it simply doesn't work. The net cost to The > People in the long run is always greater than the net benefits. If you > don't understand this then you really haven't been paying attention to > recent world history. And most of these countries were in the same position prior to adopting socialism. And they'll be in the same position after they switch to capitalism. Name one wealthy country that switched to socialism and went broke. Name a poor socialist country that switched to capitalism and became wealthy (not counting billion dollar handouts the U.S. rewards these governments with - perhaps that's where some of the motivation to switch to capitalism comes from?). > The problem with Capitalism is that not everyone shares equally in the > wealth. The problem with Communism is that everybody DOES share equally > in the misery. I prefer Capitalism. I don't disagree with your conclusion, just how you got there. Your arguments sound too much like cold war propaganda. > > >But that is not enough for you. You also want the 'right' to complain about > >something that was given to you freely and expect that righteous rants > >about your view of intellectual property laws will somehow compel people > >to modify it to your specification without compensation. > > > > You're being unfair. > > Mr. LeBlanc was not complaining about anythinthe fact that during the Cold War the USSR was g that I could see. He was > merely describing a tangible shortcoming of Python (one which launched > this entire thread) that restricts its use for some purposes. He > further, humbly suggests how it might be made a little more useful to > commercial users. And at last we agree. I didn't see a complaint in David's post or indeed anything that required such a response. > --jb > > -- > James J. Besemer 503-280-0838 voice > 2727 NE Skidmore St. 503-280-0375 fax > Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com > http://cascade-sys.com You know, I work like 2.1 miles from your house (as maps.yahoo.com flies). We could add two to the millions who have fought and died over this topic, if you like ;) Anyway, taking this to alt.neverending.arguments... Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From rjones at ekit-inc.com Sun Sep 29 08:21:36 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sun, 29 Sep 2002 22:21:36 +1000 Subject: What does Python fix? In-Reply-To: <87znu1rugt.fsf@pokey.henrik-motakef.de> References: <87znu1rugt.fsf@pokey.henrik-motakef.de> Message-ID: <200209292221.36348.rjones@ekit-inc.com> On Sun, 29 Sep 2002 7:55 pm, Henrik Motakef wrote: > Courageous writes: > > >Let's not forget that Python's syntax (most of all the significance of > > >whitespace) is considered strange at least by about all novices. In > > >both cases - significant whitespace and lots of irritating superflous > > >parentheses - people don't just get used to it, but tend to like it > > >after a while. > > > > I'm fairly sure that you meant to say "Lisp" where you said Python, > > right? > > No, I'm talking about how newbies tend to react when you tell them > that block structure in Python is determined by indentation. What do newbies care? I'm sure if they have a problem with indentation for blocks, they're going to have more trouble with remembering to put additional punctuation either side of the blocks, in the right places... Unless, of course, your "newbie" is actually someone who has had the C-style brace crap engraved on their mind before encountering Python... Of course, if you're talking from experience with having taught newbie programmers, and found that "about all" of them consider Python's blocking syntax "strange", then I'll happily take all this back :) And if those same people don't find lisp's syntax (and hell, lisp in general) "strange", then I'll doubly apologise :) Richard From david.abrahams at rcn.com Sun Sep 15 13:22:31 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sun, 15 Sep 2002 13:22:31 -0400 Subject: Stackless Python, eventual merge? References: Message-ID: "Christian Tismer" wrote in message news:mailman.1032107006.6411.python-list at python.org... > The changes to Python are also so small now, that > it doesn't matter if it will be merged or not. > Porting Stackless to a new Python is a matter of a few > hours. You may rely on getting a Stackless version > of any new Python version in almost no time. I think it still matters. You don't want people who need stackless' capabilities to have to use a non-standard Python forever, do you? -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From skip at pobox.com Wed Sep 18 19:56:49 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 18 Sep 2002 18:56:49 -0500 Subject: linking extension modules w/ "ld" on Solaris - to be expected? Message-ID: <15753.4801.895937.802904@12-248-11-90.client.attbi.com> On a Solaris machine I configured Python (2.1.3 at the moment, but 2.2.1 is in the wings) using: ./configure --with-gcc=mycc --with-cxx=mycc where "mycc" is a shell script which decides whether or not to invoke Sun's C or C++ compiler. Some (but not all) 3rd party extension modules need to be compiled with C++, but I don't want to force all to be C++-compiled. (Gcc is not an option here.) I noticed in the configure output that LDSHARED got set to "ld -G". Is this typical for Solaris when building with a non-gcc compiler? -- Skip Montanaro - skip at pobox.com The need for gutters to be cleaned is directly proportional to how hard it happens to be raining at the moment. From sholden at holdenweb.com Sat Sep 7 17:28:54 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 7 Sep 2002 17:28:54 -0400 Subject: web crawler help? References: Message-ID: <_due9.18451$l_4.1926@atlpnn01.usenetserver.com> "koko" wrote in message news:JARd9.6927$yt3.3340577 at newssrv26.news.prodigy.com... > is there any sample for basic web crawler, that ask for a starting url and > log the url and extract the hyperlinks? > thx Take a look at tools/websucker in your Python distribution (you might need to download it if you have used a limited binary installer). regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From rpm at wag.caltech.edu Mon Sep 9 13:40:32 2002 From: rpm at wag.caltech.edu (Rick Muller) Date: Mon, 09 Sep 2002 10:40:32 -0700 Subject: Can't exponentiate zero in NumPy References: Message-ID: Tim Peters wrote: > > Does this require wrapping in a Numeric array, or does it also happen in > *any* of these straight Python expressions?: Turns out it appears to be a more general problem than I thought. > > 1e-310 ** 2 Works on RH linux/1.5.2, overflows on RH linux 2.2 > pow(1e-310, 2) Works on linux 1.5.2, overflows on linux 2.2 > import math > math.pow(1e-310, 2) Works on linux 1.5.2, works on linux 2.2 (??!) > > 1e-310 ** 2.1 Works on linux 1.5.2, fails on linux 2.2 > pow(1e-310, 2.1) Works on linux 1.5.2, fails on linux 2.2 > math.pow(1e-310, 2.1) > Works on linux 1.5.2, works on linux 2.2 > In addition, exactly which version of Python are you using (2.0, 2.1, 2.1.1, > 2.1.2, 2.1.3, 2.2, 2.2.1, ...)? These are the standard python/python2 distributed with RedHat Linux 7.3. "Works" means returns 0.0 "Fails" means raises an OverflowError Can someone suggest a decent workaround? Rick From from_deja at alandaniels.com Wed Sep 25 11:20:48 2002 From: from_deja at alandaniels.com (Alan Daniels) Date: 25 Sep 2002 08:20:48 -0700 Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> <3D911A1B.1000109@something.invalid> Message-ID: Greg Ewing wrote in message news:<3D911A1B.1000109 at something.invalid>... [snippage...] > You use tabs to get up to the current statement indentation level, > and then spaces after that for the purpose of lining-up. Unfortunately, that fails when one person writes their code with tabs set to 8, and another person reads the code with tabs set to 4. Code that was hand-aligned with a mix of tabs and spaces doesn't align anymore. Sometimes I wonder if Guido would have saved a lot of debate by declaring, long ago, that Python code would never allow tabs in it, period. Which may be a bit extreme, I'll admit. :-) From aglyportREMOvethispart at nospam.yahoo.com Wed Sep 4 15:07:49 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Wed, 04 Sep 2002 12:07:49 -0700 Subject: Memory fault - core dumped while compiling 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> Message-ID: <3D765A05.6030004@nospam.yahoo.com> Martin v. Loewis wrote: > Andrew Koenig writes: > > >>Looks like the same symptom I had. >> >>If you are using binutils 2.13, try going back to 2.12.1 and >>see if that fixes the problem. > > > Alternatively, use the system C compiler - Python does not support gcc > on SCO, apparently (or else it would not try to pass -belf). > > It is probably easy to add gcc support - just adjust the OpenUnix > fragments in configure.in to SCO. > > Regards, > Martin Ok. I run gmake distclean and configure --without-gcc (output from configure confirmed that it would not use gcc). Compiling: cc -G -KPIC -Ki486 -belf -Wl,-Bexport build/temp.sco_sv-3.2-i386-2.2/arraymodule.o -L/usr/local/lib -o build/lib.sco_sv-3.2-i386-2.2/array.so /bin/sh: 1577 Memory fault - core dumped gmake: *** [sharedmods] Error 139 Did not even take nearly as long for it to coredump. With optionless configure build was going at least for a half an hour and this one bailed out pretty much right away... From richie at entrian.com Wed Sep 18 06:06:42 2002 From: richie at entrian.com (Richie Hindle) Date: 18 Sep 2002 03:06:42 -0700 Subject: Earing money with Python software (was: More on Protecting Source Code) References: <4jt7ma.fse.ln@lenashee.goebel-consult.de> Message-ID: <8a6ba1da.0209180206.2d47f2bd@posting.google.com> > How can I get some reward back when writing software like > decompyle and bridgekeeper? > [...] > - Develop two different versions, a "free" one which is missing some > features and a commercial/registered/supported one offering more > sophisticated functionallity? For library code (and tools like bridgekeeper which have a library component), my approach is to release a single version under two licenses, one free (as in both speech and beer) for use in Open Source projects and one with a fee for use in closed source projects. Sleepycat seems like a good Open Source license to use - it's OSI certified, GPL-compatible (but free from political problems) and demands that projects using Sleepycat-licensed code must themselves be open source (but not necessarily Sleepycat-licenced). While there are commercial users who release their source code, most don't, so this pretty much catches all the people who I feel should pay. There'll always be exceptions but it's a simple way to get most of the way there. Making code free for Open Source projects effectively makes it free for personal/evaluation use as well - if you're using it for a toy project then you're probably happy to ship your source, and if you're only using it for evaluation then you won't be redistributing your project. If your 'personal' use is in a project that you intend to sell in a closed-source way, that makes you a commercial user. Things are a bit different for tools like decompyle with no redistributable components. I don't have any better suggestions there, other than a free (as in beer but not as in speech) license that allows use only _with_ open source projects, and another paid-for license allowing unrestricted use. Whether licenses like that - governing the class of software that a tool may be used with - are feasible, I don't know. I'm not a lawyer. I've haven't properly started distributing code yet (it's all from spare-time projects that my life and my day job leave me little time for - what little there is is on my incomplete website at www.entrian.com) so it's too early to say whether this approach is working for me or not... -- Richie Hindle richie at entrian.com From andrewa at calibredigital.com Mon Sep 23 13:11:28 2002 From: andrewa at calibredigital.com (Andrew Alzner) Date: Mon, 23 Sep 2002 13:11:28 -0400 Subject: parsing tabs in a string Message-ID: <006201c26324$4148ae90$025e10ac@calibredd.com> Hello, I'm getting to know Python and have a quick question for something I don't understand. I'm trying to parse information extracted from a spreadsheet which is tab separated. Here is a simplified version of what I have: list=['"103-01a-17"\t2\t33\t256\t227\n'] y=list[0] print y.find("\t") print y.find("\t",1) I thought the second .find should return the second occurence of "\t". To get the index of the second tab I have to type: print y.find("\t",13) This doesn't make sense to me. Can someone help me please. Thanks, Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: From nc-lessaudo at netcologne.de Wed Sep 25 05:11:14 2002 From: nc-lessaudo at netcologne.de (Donald Lessau) Date: Wed, 25 Sep 2002 11:11:14 +0200 Subject: [newbie] mod_python apache w32 References: Message-ID: hi christopher, i've got exactly the same problem... Did you find a solution in the meantime? thanks Donald "christopher knievel" schrieb im Newsbeitrag news:ami5rr$des$04$1 at news.t-online.com... > Hi all, > i got some problems running mod_python with apache under windows. > I am using python 2.2 and apache 1.3.26. > As written in the manual i configured httpd.conf like this: > > LoadModule python_module modules/mod_python.dll > > AddModule mod_python.c > > > AddHandler python-program .py > PythonHandler mptest > PythonDebug on > > > I copied the mod_python.dll to C:/Python22/lib/mod_python. > > The Apache server is starting with "Apache/1.3.26 (Win32) mod_python/2.7.6 > Python/2.2.1 running..." > So i guess it should be working.... > > The test script looks like this: > > #! C:/Python22/python.exe > > from mod_python import apache > > def handler(req): > req.send_http_header() > req.write("Hello World!") > return apache.OK > > my error.log (last entry): > [Sat Sep 21 18:00:13 2002] [error] [client 192.168.1.99] python_handler: > make_obcallback returned no obCallBack! > > i've read several newsgroups and googled a lot but i didn't found a working > solution > Thanks a lot in advance... > christopher knievel > > From BrenBarn at aol.com Thu Sep 12 21:35:02 2002 From: BrenBarn at aol.com (OKB (not okblacke)) Date: Fri, 13 Sep 2002 01:35:02 GMT Subject: Help with regular expression using findall and .*? References: Message-ID: czrpb wrote: > p=re.compile(r'macro.*?orcam',re.DOTALL) > > for x in re.findall(p,s1): > print x > > for x in re.findall(p,s2): > print x > If you use re.findall directly you need to pass a pattern string in, not a compiled object, and I don't think there's a way to specify flags with that approach. Instead, use the findall method on your compiled expression object: for x in p.findall(s1): print x -- --OKB (not okblacke) "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From e_fax_t at hotmail._ZAPME_.com Tue Sep 24 16:31:20 2002 From: e_fax_t at hotmail._ZAPME_.com (Justin) Date: Tue, 24 Sep 2002 22:31:20 +0200 Subject: readlines() and "binary" files Message-ID: <3d90cacf$0$30457$afc38c87@sisyphus.news.be.easynet.net> Hi, I have excel data with occasional multi-line fields, which when dumped to CSV translates to embedded CR's within a line, whereas the records/lines themselves are delimited by the CR+NL pair (this is MS-land). What I'd like to do is read those files and split every line apart on the semi-colon field separator. But it seems that whether the file is opened as text or not, (x)readlines() still considers the lone CR as a line delimiter and so not all my lines end up with the same number of fields as they should. Is there a way to handle this, or is readlines just not meant to work with anything but proper text files? f = open('testdata.csv','rb') for line in f.xreadlines(): fields = line.split(';') print len(fields) # should always be the same value From helm at dnv.com Wed Sep 25 09:36:27 2002 From: helm at dnv.com (Jens Bloch Helmers) Date: Wed, 25 Sep 2002 13:36:27 GMT Subject: missing functions in os.path Message-ID: I hope that a future version of Python will include the following two functions: os.path.localpath( file ) # Returns the non-UNC name # of file. >>>file = r'\\computer\shared\myfile.txt' >>>os.path.localpath( file ) 'd:\somedir\shared\myfile.txt' os.path.relpath( file, dir ) # returns the relative path of # file relative to directory dir >>>file = r'C:\test\mydir\hum.txt' >>>dir = r'C:\otherdir' >>>os.path.relpath( file, dir ) '..\test\mydir\hum.txt' From Oschler at earthlink.net Fri Sep 6 13:20:50 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Fri, 06 Sep 2002 17:20:50 GMT Subject: Interapp communication under Python[Linux]? Message-ID: My Python app will talk to 3 or 4 modules written in Java and C/C++. Fortunately I have the source for the Java and C/C++ modules and I have experience in both languages. Currently the external modules have no provision for being accessed outside of the process they are running as. So I'm wondering what the best protocol would be used to "glue it all together". There a dizzying array of possibilities: 1) Have everybody talk to each other via SOAP (web services). 2) Have everybody talk to each other via XML-RPC (Don't know much about this method). 3) Use Boost's SWIG interface for C++ to link the C/C++ modules to Python. How to link to Java in the same manner? 4) Use "sockets" and my own custom protocol for everybody. 5) Code in Jython instead and use various methods above to talk to C/C++ modules from Jython app. 6) CORBA? (yikes!) So as I said, a lot of ways to get things done. I'd like to hear from those of you that have actually done a lot of cross-app communication with Python on what your experiences have been, and the pros and cons you encountered. thx From kp at kyborg.dk Tue Sep 24 08:11:29 2002 From: kp at kyborg.dk (Kim Petersen) Date: Tue, 24 Sep 2002 14:11:29 +0200 Subject: __name__ in embedded python giving error Message-ID: <3D905671.1070106@kyborg.dk> Hi, First: This is probably my fault in forgetting to consider some call when embedding python .... When doing: if __name__ == "__main__": in modules i get the following error: Traceback (innermost last): File "/var/www/cgi-bin/CGIX.py", line 641, in ? if __name__=="__main__": TypeError: function requires at least 2 arguments; 1 given Could some enlightened head give me a pointer as to what i've done wrong (or am missing)? Please query for more information - i haven't included much (because the program is a bit large)... Error on Linux 2.4 - using python 1.5 (haven't tried yet with 2.2 - but i think the error is there as well)... From loewis at informatik.hu-berlin.de Mon Sep 2 06:57:13 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 02 Sep 2002 12:57:13 +0200 Subject: wie greife ich mit Python auf die c-bibliotheken zu ? References: <3D7323BB.4070200@uni-koblenz.de> Message-ID: Oleg Seifert writes: > k?nnte vielleicht jemand es mir an einem Beispiel zeigen. Ich habe als > Attachments zwei kleine Anwendungen dazu geschickt. Du musst einen Typ definieren; nimm als Beispiel Modules/xxmodule.c aus der Python-Distribution. Dort sollte es dann ungef?hr lauten typedef struct { PyObject_HEAD person *_person; } PyPerson; Die Methoden der C++-Klasse musst Du alle "wrappen", etwa extern "C" PyObject* PyPerson_setname(PyPerson* self, PyObject*args){ char *n; if(!PyArg_ParseTuple(args, "s:setname", &n)) return NULL; self->_person->set_name(n); Py_INCREF(Py_None); return Py_None; } Dann kann man das ganze vielleicht benutzen als p = person.new() # Annahme: das ganze Modul heisst person, nicht xx p.set_name("Peter") Alternativ kannst Du auch set/get als Attribute wrappen, so dass man dann schreiben kann p.name = "Peter" # ruft implizit ->set_name() Ciao, Martin From oren-py-l at hishome.net Sat Sep 7 16:10:22 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 7 Sep 2002 16:10:22 -0400 Subject: Daemonize? In-Reply-To: <20020907174957.GA25058@glacier.arctrix.com> References: <20020907161037.GA70503@hishome.net> <20020907174957.GA25058@glacier.arctrix.com> Message-ID: <20020907201022.GA93398@hishome.net> On Sat, Sep 07, 2002 at 10:49:57AM -0700, Neil Schemenauer wrote: > Oren Tirosh wrote: > > devnull = os.open('/dev/null', 0) > > os.dup2(devnull, 0) > > os.dup2(devnull, 1) > > os.dup2(devnull, 2) > > > > This is safer because it prevents these file descriptors from being reused. > > Better: > > os.close(sys.__stdin__.fileno()) > os.close(sys.__stdout__.fileno()) > os.close(sys.__stderr__.fileno()) > os.open('/dev/null', 0) > os.dup(0) > os.dup(0) Any particular reason why you think this is better? Oren From sholden at holdenweb.com Tue Sep 17 18:10:43 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 17 Sep 2002 18:10:43 -0400 Subject: MarketProductLifecycle References: Message-ID: "GerritM" wrote in message news:am81ff$pdh$1 at reader1.tiscali.nl... > > Oops pressed the send key before verifying the destination... > > This does not belong here, but how to cancel from OE5? > Select your message (you have to be able to see it on your server...) and select "cancel message" from the "Message" menu. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From jb at cascade-sys.com Fri Sep 20 01:03:56 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Thu, 19 Sep 2002 22:03:56 -0700 Subject: Larry Wall's comment on python... References: <006501c25fd5$ecc80740$0101010a@local> Message-ID: <3D8AAC3C.9020300@cascade-sys.com> Chris Gonnerman wrote: >I just like that I don't have to type the #!$&@!! things >anymore. > >No smiley this time... I really hate typing curly after curly. >It makes me wonder that anyone *likes* the freakin' things so >much that they named a LANGUAGE after them. > They are a hell of an improvement over "begin" and "end". But I agree, leaving them out altogether is even better. --jb From dag at animagicnet.no Thu Sep 19 13:06:50 2002 From: dag at animagicnet.no (Dag) Date: 19 Sep 2002 17:06:50 GMT Subject: finding last match in a file Message-ID: I have a number of very large files where I have to find the last line which matches a certain experssion. Currently I'm simply opening the file and looping through it noteing each time a line matches and at the end of the loop I see which was the last match. However this is very slow and inefficient. Is there some way to read through the file backwards and simply find first match starting from the end of the file. The files are really too big to read the entire thing into memory. Dag From timr at probo.com Fri Sep 20 00:23:44 2002 From: timr at probo.com (Tim Roberts) Date: Thu, 19 Sep 2002 21:23:44 -0700 Subject: Strange Telnet error References: <4378fa6f.0209181245.7b06124d@posting.google.com> Message-ID: mnations at airmail.net (Marc) wrote: > >I have been running some code that all the sudden stopped working. I >can not figure out what's happened. I am doing a simple telnet >connection that sends and receives info. Now I am getting this error: > >Traceback (most recent call last): > File "C:\Python22\lib\threading.py", line 408, in __bootstrap > self.run() > File "C:\Python22\lib\threading.py", line 396, in run > apply(self.__target, self.__args, self.__kwargs) > File "main.py", line 85, in run > command[0](*command[1:3]) > File "key.py", line 92, in command > conn.write(com) > File "C:\python22\lib\telnetlib.py", line 272, in write > self.sock.sendall(buffer) >AttributeError: 'int' object has no attribute 'sendall' > >Has anyone ever seen this before? If so, what could do this be related >to? I'm guessing you continued to try to do work after closing the connection. Note this code at line 247: def close(self): """Close the connection.""" if self.sock: self.sock.close() self.sock = 0 # <<<< this makes self.sock an integer self.eof = 1 Your code is multithreaded. Could another thread have closed the socket on you? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From phr-n2002b at NOSPAMnightsong.com Tue Sep 17 02:22:16 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 16 Sep 2002 23:22:16 -0700 Subject: Source code References: <3d868ccc$1@news.sentex.net> Message-ID: <7xfzw9qgo7.fsf@ruckus.brouhaha.com> "James J. Besemer" writes: > Furthermore, even if you formally assign the copyright to somebody > else, I understand ownership eventually reverts to the original author > after a lengthy period (45 years or something). Evidently it > preserves the copyright for the heirs of the author. I heard the opposite. In fact part of the debate before the 1976 copyright extension act was about who should get the additional years of copyright of a work that had been assigned to a publisher, the author or the assignee. Of course the same corporate lobbyists who got the extension passed in the first place made sure that publishers, not authors, got 100% of the benefit of the extension. See http://eldred.cc for more info. From tjreedy at udel.edu Sat Sep 14 11:50:21 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Sep 2002 15:50:21 GMT Subject: How to represent sets References: Message-ID: <1VIg9.16142$5r1.654088@bin5.nnrp.aus1.giganews.com> "Anton Vredegoor" wrote in message news:alvd8p$1sq$1 at news.hccnet.nl... > In the past there have been some discussions on various platforms about > whether sets should be implemented using long integers (possibly leading to > longs becoming iterable arrays of booleans), or by using dictionaries. Framing this an an either/or question is simply wrong. The 'best' implementation of the abstract concept 'set' depends on the application, the number of possible members, the density of actual sets, and the operations needed. Sets with up to 32 possible members are well implemented by C longs (Python ints). Somewhat dense sets of ints in a much larger range can be longer bit maps. A set of integers in the range +- 10**20 has to be done with dicts. Ditto with sets of strings up to length, say, 32. Similar false questions for other abstract data types: what is the best way to implement numbers, sequences, or matrixes. For matrixes, linear arrays (with address calculation), arrays of arrays, and dicts mapping pair->value all have their appropriate uses. > The matter seems to be mostly settled and there is a sets.py script in the CVS > directory at sourceforge which uses dictionaries. Guido has agreed to support an experimental general solution as part of the standard library, perhaps to eventually become a builtin module or type. This in no way precludes other implementations. That is part of way user classes with magic methods is for. Choosing to support a general purpose set-of-anything-hashable rather than a more limited set-of-integers-in-a-reasonable-range is in line with Guido's other design decisions. > I would like to reopen this discussion. I don't remember any pronouncement from Guido or anyone else closing it, except perhaps with regard to what he will personally support. > Starting this discussion again when the CVS script is already very mature > seems a bit inappropriate, but I believe there is a way to make sets faster. I > only recently realized this so I could not act earlier. Special-purpose implementations often have some advantage of the most general implementation. If not, they get forgotten about. > > To give some material for the discussion I am providing a beta version of a > possible implementation af a set class using long integers to represent sets. > It is basically the same script I presented a year ago but I have made several > improvements to this script so that it is now a bit faster, and I hope the > docstring is a bit better now. Please keep in mind this is just a test script, > for a safer and more complete implementation the script in CVS is preferable. > > http://home.hccnet.nl/a.vredegoor/universe/universe.py > > or the html version: > > http://home.hccnet.nl/a.vredegoor/universe/universe.html To be most useful as an alternative implementation, your implementation should be (could be? is?) a plug-in replacement for sets.py so one could gain its advantages by replacing 'import sets' with 'import universe as sets' (or 'import longsets as sets'). Having one 'standard' implementation now defines a standard interface that gives you a (pretty-well) fixed target to aim at for compatibility. Before this was hashed out among the prime developers, and some arbitrary decisions made, there were multiple possible targets. I took a preliminary look at universe.py. Your test() function would be more useful as a regression test if you automated it with the doctest module. To do so, cut the contents of the function (perhaps after dedenting) and paste it into the interactive interpreter. (On Windows, turn off 'fast pasting' first!!, and maybe paste just a few lines at a time.) Then cut and paste the result and put it in a doc string and otherwise add the doctest boiler plate given in doctest.__doc__. Terry J. Reedy From martin at v.loewis.de Mon Sep 2 02:04:48 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Sep 2002 08:04:48 +0200 Subject: MySQL and Python in Solaris 8 References: Message-ID: ganapathy murali krishnan writes: > cc -Xc -mt -O -I/opt/mysql/mysql-3.23/include/mysql > -I/opt/python/default/include/python2.1 -c _mysql.c -o > build/temp.solaris-2.8-sun4u-2.1/_mysql.o -fPIC > cc: Warning: illegal option -fPIC > "/opt/mysql/mysql-3.23/include/mysql/mysql.h", line 111: long long not > allowed in Xc mode Something is quite broken here. Can you tell where the Xc/mt options come from? To my knowledge, Python/distutils never uses those on its own - could it be that you set environment variables to that effect? (perhaps mysqldb introduces them, but that would be surprising) -fPIC usage indicates that you have been using gcc to build Python. Is this the case? Do you have gcc on your system? GNU binutils? > ImportError: ld.so.1: /usr/local/bin/python: fatal: relocation error: file > /opt/python/default/lib/python2.1/site-packages/_mysql.so: symbol > PyLong_FromUnsignedLongLong: referenced symbol not found > ------- > > which suggests that the original build was not complete. More precisely, it indicates that you have been linking with GNU binutils, but Python failed to detect that it had to use -Wl,-export-dynamic when linking python. What is your binutils version? Regards, Martin From cben at tx.technion.ac.il Mon Sep 16 16:15:12 2002 From: cben at tx.technion.ac.il (Beni Cherniavsky) Date: 16 Sep 2002 13:15:12 -0700 Subject: "str"(expr)"str" interpolation syntax References: <8a6ba1da.0209130002.37ede06a@posting.google.com> Message-ID: richie at entrian.com (Richie Hindle) wrote: > Guido's time machine strikes again: > > >>> foo, bar, quux = 1, 2, '3' > >>> print ("A template string - here: %s it goes\n" % foo + > ... "Also multiple values: %s, %s\n" % ( bar, quux ) + > ... "Quoting percent (%s) sings probably not needed...\n" % '%') > A template string - here: 1 it goes > Also multiple values: 2, 3 > Quoting percent (%) sings probably not needed... Well, all right. I'll find something more useful to do than repainting the wheel ;-) From tg5027 at citlink.net Wed Sep 18 19:40:56 2002 From: tg5027 at citlink.net (terry) Date: Wed, 18 Sep 2002 19:40:56 -0400 Subject: monetary applications (et al) Message-ID: >>> Michael wrote: for how to emulate numeric types. >>> Right, I have looked at that. As near as I can tell there is a vast difference between 'emulation' and 'intrinsic' - and the burden of that difference falls on the programmer/customer in your assessment. The difference involves the amount of effort required to anticipate and react to the use of emulation as opposed to the simplicity of using intrinsic data types. Maybe in the C world, dealing with what ever comes your way in what ever way you deem appropriate for your current project/situation is a way of life, but for those of us who have to deal directly with a world in which money is a common data type, all of that extraneous OO stuff to represent what is really a common information form really is a crude approach to getting a job done. just my $0.02 ;>) terry From cnetzer at mail.arc.nasa.gov Sat Sep 28 22:23:04 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Sat, 28 Sep 2002 19:23:04 -0700 Subject: Help please with menubars In-Reply-To: <000f01c266f3$2903dbc0$2502a8c0@emily.ewndsr01.nj.comcast.net> References: <000f01c266f3$2903dbc0$2502a8c0@emily.ewndsr01.nj.comcast.net> Message-ID: <200209290223.TAA30009@mail.arc.nasa.gov> On Saturday 28 September 2002 06:30, andy surany wrote: > Thanks Chad. No problem; I'm posting my reply to the newsgroup, because I think it is relevant. > Yes, Tk. > > The problem with using add.menubar is that I end up with a cascade. Huh? Not in the example that I posted... > But I hadn't thought of a bind. I know that I can bind to a button - > but this is an item on a menubar. I'm not sure how to do that. Me neither. :) It really is more effort than it is worth; and I think you don't need it. > BTW, what I am encoding is a menubar with 5 top level items. The > first 4 are cacading/pulldown (no problems!), but the fifth is simply > an "Exit" on the menubar. Click it, and the window should be history. That was almost exactly what the code I posted did... Hmmmph; Here is a revision that exits when you click on the "Exit" entry in the menubar, WITHOUT dropping down a menu. I also added a separate menu entry that does cascade down, just to show you it can be done. If this isn't what you need, then I have no clue what you mean; it would be best to post your code (or the relevant portions), to see how you are attempting to use menus. I'm making it an attachment, so it should be easy for you to save and run it. Please DO run it, if you haven't, before replying, and let me know if it doesn't work as I say it should. Also, by using the "menu" option of a Toplevel, this code will integrate much better with the system you are on, than if you try to make your own custom "menubar", using a Frame and menubuttons, for example. On the Mac, for example, this code follows the systems menubar conventions (per desktop, not per window). -- Chad Netzer cnetzer at mail.arc.nasa.gov -------------- next part -------------- A non-text attachment was scrubbed... Name: menubar_test2.py Type: text/x-java Size: 654 bytes Desc: not available URL: From bokr at oz.net Tue Sep 3 10:23:47 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Sep 2002 14:23:47 GMT Subject: syntax error in Pyton shell References: <3D746BC1.2BFA05F8@alcyone.com> Message-ID: On Tue, 03 Sep 2002 00:58:57 -0700, Erik Max Francis wrote: >lion wrote: > >> I'm learning exception handling, I type these code in Python shell: >> >> >>> try: f=open("nofile") >> ... except IOError: pass >> ... print "The exception is just passed!" >> File "", line 3 >> print "The exception is just passed!" >> ^ >> SyntaxError: invalid syntax >> >> But these code run without any error as a program(or script). Could >> anyone tell me why? > >This is an artifact of entering in code manually in the shell, which >normally would have more cues to go on. In a script it would no that >these two statements were unrelated; in the interactive interpreter it >can't be sure so is waiting for a blank link to separate them. You can >tell this when the prompt is ... instead of >>>. > Why can't it be sure? IWT the dedent should tell it the previous chunk is complete. And in any case, why not keep accepting lines until the blank line, once into accepting more than one? It is annoying to have to resort (interactively) to: >>> if 1: ... for i in range(5): ... print i, ... print '[output desired on same line].' ... 0 1 2 3 4 [output desired on same line]. because this screws up: >>> for i in range(5): ... print i, ... print '[output desired on same line].' File "", line 3 print '[output desired on same line].' ^ SyntaxError: invalid syntax Regards, Bengt Richter From david.abrahams at rcn.com Thu Sep 5 22:05:46 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Thu, 5 Sep 2002 22:05:46 -0400 Subject: try blocks in Python vs. C++ References: Message-ID: "David LeBlanc" wrote in message news:mailman.1031270709.27012.python-list at python.org... > I think the biggest reason why try blocks aren't suggested for use in C++ is > that they increase code size substantially (as do some other nice features). That's not a very good generalization. C++ implementations vary substantially on the over (and under-) heads implied by exception-handling constructs. One reason you might want to avoid try blocks is that generally you want to do cleanup unconditionally and rethrow the exception unmodified, and C++ has no "finally" construct. Usually it works a lot better to use destructors of local objects for this sort of thing, since you can re-use them and you can't forget to "throw;" at the end. BTW, saying "Stroustrup's C++ Book" isn't very specific (he has several), and early editions of TC++PL contained some bad advice about C++ EH. See the downloadable Appendix E at http://www.research.att.com/~bs/3rd_safe0.html for some good advice. > Try...except is good practice in Python IMO. Yeah, it's a completely different story in Python: Python has 'finally' __del__ methods don't execute as the stack is unwound (whereas C++ destructors do) throwing an exception to deal with ordinary conditions (e.g. StopIteration) is common, since unlike most C++ implementations throwing an exception is no more expensive in Python than returning from a function. ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com > > > -----Original Message----- > > From: python-list-admin at python.org > > [mailto:python-list-admin at python.org]On Behalf Of Roy Smith > > Sent: Thursday, September 05, 2002 16:54 > > To: python-list at python.org > > Subject: try blocks in Python vs. C++ > > > > > > I'm reading Stroustroup's C++ book, and came upon a piece of advice to > > avoid using try blocks. I use try blocks a lot in Python and gather > > it's common practice among pythonistas. > > > > Is there something fundamentally different about try blocks in Python > > and C++ which makes them more attractive to use in one vs. the other? > > On the surface, they appear to be virtually identical in just about > > every respect. Is it simply a cultural difference? Or just the > > author's own personal style? > > -- > > http://mail.python.org/mailman/listinfo/python-list From snyderf at loki.stockton.edu Tue Sep 24 21:14:38 2002 From: snyderf at loki.stockton.edu (Fred Snyder) Date: Tue, 24 Sep 2002 21:14:38 -0400 Subject: IDLE Default Save Directory Message-ID: <3D910DFE.F74644B4@loki.stockton.edu> Hi - I'm just getting up and running with Python(2.11)/IDLE(.8) on SuSE 7.3. Hope this is not a too "duh" question. I've looked but can not find how to change the default "Save" and "Save As" directories in IDLE. Have looked at the various configuration files but don't know the syntax or the [Section] to make these changes. Would someone please give me some examples of a customized config file (maybe .idle) so I can make some changes. Thanks, Fred From skpeternospam at ucdavis.edu Mon Sep 30 17:25:40 2002 From: skpeternospam at ucdavis.edu (Sam Peterson) Date: 30 Sep 2002 17:25:40 -0400 Subject: Python Process that can survive References: <571739c3.0209271111.6514c32f@posting.google.com> Message-ID: On Fri, 27 Sep 2002 at 19:11 GMT, Christopher Peery spake thus: > sismex01 at hebmex.com wrote in message news:... > Plus in my lab there are a bunch of perl guys and a few python > people. To date, what one can do in their script the python guys > can do to (only nicer and much more readible). Perl has the ability > to have a process continue after the underlying terminal is killed > if the process is in the background. What is python doing that > doesn't allow this? My guess is that they're using something like $ nohup perl . This catches the HANGUP(HUP) signal sent from the terminal and effectively daemonizes a process. All the perl I've scripted before would die as soon as I'd logout, and I'd use the nohup program to keep it running. -- Sam "Da Man" Aren't I an egotist? s/nospam/son/ -- to email me. From tdelaney at avaya.com Sun Sep 22 19:51:15 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 23 Sep 2002 09:51:15 +1000 Subject: Minimal debug/rep functionality Message-ID: > From: richie at entrian.com [mailto:richie at entrian.com] > > The first version used the AST, but there are several holes in that - > 'else' lines, for instance, are identified by the parser as executable > lines, but the trace function doesn't always get called for them. Something I would have had to find out myself ... thanks :) > found out that SET_LINENO is going away in Python 2.3... The reason I didn't do the same thing ... > My current system (which I think works 8-) uses co_lnotab, which is a > delightful data structure that describes the relationship between > bytecodes and line numbers. Here's the relevant piece of code, which > builds in 'lineNumbers' a list of the execuable line number in the > code object 'code': Thank you. This should help immensely. > Hope that helps. The coverage tool that this belongs to is finished > but unreleased (mostly because of lack of thorough testing, but I'm > using it myself with no problems) - if you'd like a copy, drop me an > email. Please do - it will be interesting to see how our approaches differ. Don't bother about tidying it up unless it's a real mess. I'd better get onto asking my employer if I can pass this code onto other people I guess :) Tim Delaney From bloke at ii.net Sat Sep 14 14:38:11 2002 From: bloke at ii.net (Rob Hall) Date: Sun, 15 Sep 2002 02:38:11 +0800 Subject: convert python package to rose uml References: <3d838069$0$22311@echo-01.iinet.net.au> Message-ID: <3d838203$0$22326@echo-01.iinet.net.au> oh yeah, should have mentioned, it simply dumps the convertion into a file called import.ptl in the CWD. Rob From alanmk at hotmail.com Tue Sep 24 12:40:04 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: 24 Sep 2002 09:40:04 -0700 Subject: Strange values in Accept-Language header? References: <8FWj9.39597$V7.10466682@twister.socal.rr.com> Message-ID: Alan Kennedy: >> Accept-Language: en-us,x-ns1rDGeT4e2FpA,x-ns2f67971hgDw1 >> Accept-Language: x-ns13V8cN8S1Xz9,x-ns2T329gfxKa7d >> >> I have no idea what these could mean (I've changed the actual values >> BTW, on the remote off-chance that somebody's highly personal >> information was coded in there) Jeff Davis: > I really don't know what those extra characters mean. Do you think it might > have to do with some related preference like fonts or the screen or > something? I should have mentioned: although I changed the value, I didn't change the first four characters, so the "x-ns1" and "x-ns2" at the beginning of each string are original. To me, that indicates some form of identifier structure, like a URN, for example...... However, if it is a crack attempt, perhaps the "x-ns1" and "x-ns2" are keys in some dictionary/hashmap that are vulnerable in some server? Jeff Davis: > Perhaps if you posted the secret info someone else might notice something. Yes, I think I'm being too squeamish by not posting the values. Here's two of the headers, unmodified Accept-Language: x-ns16W5tM7A2Nh6,x-ns2U210btwUq5f Accept-Language: en-us,x-ns1jZKcD2t3NhQ,x-ns2r3509OnmPe2 If it was some form of request modifier for custom clients/proxies/servers, then why not simply use a custom HTTP header, like X-Custom-Header: x-ns16W5tM7A2Nh6,x-ns2U210btwUq5f Odd. Alan. From roy at panix.com Thu Sep 5 19:53:48 2002 From: roy at panix.com (Roy Smith) Date: Thu, 05 Sep 2002 19:53:48 -0400 Subject: try blocks in Python vs. C++ Message-ID: I'm reading Stroustroup's C++ book, and came upon a piece of advice to avoid using try blocks. I use try blocks a lot in Python and gather it's common practice among pythonistas. Is there something fundamentally different about try blocks in Python and C++ which makes them more attractive to use in one vs. the other? On the surface, they appear to be virtually identical in just about every respect. Is it simply a cultural difference? Or just the author's own personal style? From aleax at aleax.it Thu Sep 19 11:29:43 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 15:29:43 GMT Subject: Getting started References: Message-ID: holger krekel wrote: > Lance wrote: >> Hi All, >> >> Last night I attended a Weak typing, C++ Templates, and Python talk by >> Bruce Eckel. It was great, my introduction to Python. >> >> I'm sold on Python and weak typing. > > I am not. But i much prefer dynamic over static typing :-) > What is 'weak typing' supposed to mean, anyway? I have heard that a > couple of times from java-people because they tend to think that python > is not strongly typed. $a = "2.3"; $b = 45; print $a+$b; emitting 47.3 is pretty close to what I consider "weak typing". I find it very hard to produce substantial, large programs using weakly-typed languages. Python is strongly, albeit dynamically, typed, as you say. Unfortunately, some seminal material of a few decades ago confused terminology (I vaguely remember something about it in some early article about Scheme, for example). Alex From Oschler at earthlink.net Sun Sep 1 19:13:53 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 1 Sep 2002 19:13:53 -0400 Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: "Gerhard H?ring" wrote in message news:mailman.1030916762.5578.python-list at python.org... > > I never saw such a note. Maybe you were reading a message from the > (dormant) types-sig, where ways to introduce optional (!) stronger > typing into Python are discussed. I never saw Guido make any comments > about removing dynamic features from Python, though. With /one/ > exception, which you didn't mention, yet: assigning to the __class__ > attribute: > Yes it was in a thread where that was mentioned. That's not a feature I would miss, kind of scary (dynamically switching an instance's class). The add method stuff though is superb. It's used to wonderful effect in XML parsers I've seen for parsing. If your're curious about the __dynamic__ keyword, here's the thread. Look in the neighborhood of message #68 and find the keyword __dynamic__ (wow what a great password this link would make): http://groups.google.com/groups?hl=en&lr=lang_en&ie=UTF-8&oe=UTF-8&safe=acti ve&threadm=mailman.997727540.19628.python-list%40python.org&rnum=1&prev=/gro ups%3Fhl%3Den%26lr%3Dlang_en%26ie%3DUTF-8%26oe%3DUTF-8%26safe%3Dactive%26q%3 DRe%253A%2BCopy%2Bconstructors%2Bpython thx From umop at psyon.org Wed Sep 18 17:34:09 2002 From: umop at psyon.org (Eric Arnold) Date: Wed, 18 Sep 2002 14:34:09 -0700 Subject: Regex question References: Message-ID: Okay, I have it down to: (?.*):(?[^,]*(,|$))+ which almost works ... : "Name" : "AAA" : "BBB" : "CCC" : "" it's picking up the on the last character (right after "C") and it's an empty string. Shouldn't "CCC" (as captured with the $ end of string as a delimiter) be the last thing found? Eric "Eric Arnold" wrote in message news:amapuf$45t8t$1 at ID-144898.news.dfncis.de... > Hi folks, > > I'm trying to figure out why this is not working, and wonder if there are > any regexperts out there who can give me a pointer. > > The string I'm capturing is as follows: > > Name:AAA,BBB,CCC > > where I'd like to extract the following data: > > : Name > : AAA > : BBB > : CCC > > this is the regular expression I wrote to do so: > > (?.*):(?([^,]*(?=,))|((?<=,)[^,]*))+ > > I tried it with the (?<=,) as another (?=,) too, but no luck. I imagine > that the problem is that when the (?=) is used once, it can't be used with > the second group, but I don't know a way around that. > > Thanks! > > Eric > > From DGustafson at attbi.com Fri Sep 20 06:48:57 2002 From: DGustafson at attbi.com (Dave Gustafson) Date: Fri, 20 Sep 2002 10:48:57 GMT Subject: general thoughts References: Message-ID: I've been programming for, hard to believe when I think of it, 30 years... I just recently picked up a book that really brought back som fo the Joy of programming and programming languages. I wish I'd picked it up much earlier! It's not about Python, but rather about a dialect of Lisp called Scheme, and is titled "The Little Schemer". It's been really fun to work through and really "grok" what's going on in programming, also fun to translate the concepts there in to Python which to me is a more real-world language. I'd suggest it as a way to have some fun with this art... Dave From jb at cascade-sys.com Thu Sep 26 02:39:15 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 25 Sep 2002 23:39:15 -0700 Subject: Larry Wall's comment on python... References: Message-ID: <3D92AB93.8060102@cascade-sys.com> Courageous wrote: >>Once upon a time, a large class of computers, and their attendant >>peripherals, OSs and utility programs universally implemented tabs >>hard-wired at 8 stops. >> >> > >Indeed; such is this issue that I leave hard tabstops as 8 in my >editor, and set soft tab stops set to 4. > I'm aware of that technique and I know of others who favor it. And it does give you 4 column stops without having to dink with all your printers and other utilities. Personally, though, I don't care for it. VI is not my programming environment all the time (maybe 50% these days) and some other tools I use don't have this feature. Then I'm stuck running into spaces where I don't expect them. Another editing nit that I use is to cursor left one or some other specific number of "indents" and then cursor up or down to where the enclosing code lines up. If you have spaces or a mix then half the time you have 3 extra character positions to move to get where you need to be. Incidentally, mixing spaces and tabs is officially less desirable in the official code style guides than tabs or spaces. All my life I've relied on indent being 1 tab and I'm too old to change that, though I can live with 4 char tab stops. When I make slight tweaks to other people's program, I always strive to honor the pre-existing standards. If I'm doing a lot of work, then I might well convert to all tabs while I'm working on it and convert back, if necessary, to whatever standard the customer requires. Code I write just for myself of course generally is all tabbed at 8 columns. But I'm NOT telling you what you should do. You do what you want. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From manuel at hendel.net Fri Sep 27 05:13:25 2002 From: manuel at hendel.net (Manuel Hendel) Date: Fri, 27 Sep 2002 11:13:25 +0200 Subject: comparing all values of a list to regex In-Reply-To: <0lUk9.149240$ub2.3291527@news1.tin.it> References: <0lUk9.149240$ub2.3291527@news1.tin.it> Message-ID: <20020927091325.GA375@partagas.as.de.cw.net> Sorry for forgetting some details. On Fri, Sep 27, 2002 at 08:07:24AM +0000, Alex Martelli wrote: > > def classify(login_email): > l_e = login_email.split(',') I think that I nearly understand what you are doing here. But I don't understand the assert part. I already checked at the documentations but this doesn't helped me at all. > assert 1 <= len(l_e) <= 2, "More than one comma in (%s)" % login_email > if len(l_e)==2: return 2 # both > elif l_e.find('@'): return 1 # email, I guess > else return 0 # other case (local account, I guess) Manuel -- From '86 until the summer of last year, wherever I went, people would say, "You would have made a great James Bond! Weren't you going to be James Bond? You should have been, you could have been, you may have been." Yes, yes, yes, yes, yes. It was like unfinished business in my life. I couldn't say no to it this time around. -Pierce Brosnan From Henrik.Weber at sys.aok.de Fri Sep 27 05:37:25 2002 From: Henrik.Weber at sys.aok.de (Henrik Weber) Date: 27 Sep 2002 02:37:25 -0700 Subject: DBI cursor behaviour with multiple statements? Message-ID: <7e964d1d.0209270137.568a3f3@posting.google.com> Hello, I'm trying to write a DBI2 compliant module for Microsoft Access databases. Now I'm not quite sure how to interpret the DBI2 specification when it comes to the execution of multiple data returning statements with the same cursor. For example if c is my cursor and I do: c.executemany("SELECT * FROM table WHERE column = '%s'", [["parm1"], ["parm2"], ["parm3"]]) should the result be the union of all three statements or just the result of the first or the last statement? Or should the user switch from one resultset to the next with nextset? And what if I execute another SELECT-statement before all results of the previous execute or executemany have been fetched? Should the cursor first return the rest of the previous statements results or should the results of the last statement replace whatever there was before? Maybe someone reading this group can clarify those points for me. Thanks, Henrik Weber From jb at cascade-sys.com Fri Sep 20 13:48:24 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 20 Sep 2002 10:48:24 -0700 Subject: [Help]: mailbox classes References: Message-ID: <3D8B5F68.2070906@cascade-sys.com> Jeff Davis wrote: >Ok, I'll assume your using mbox format, but this is easily adapted for >maildir, etc. > >import mailbox >mbox_file = '/path/to/mbox' > >mbox_fp = open(mbox_file) >mbox = mailbox.UnixMailbox(mbox_fp) >msg = mbox.next() > >there, now you have a message object (a rfc822.Message object, to be >exact). Now just import the rfc822 module and do whatever you need. You'll >probably want to use a loop to process all of the messages. > I've found these packages to be somewhat fragile. In particular, real world email includes a lot of spam and a fair amount of spam does not conform 100% to all the mime encoding rules. A frequent error is that a surprising number of mime-encoded messages for some reason do not include the ending boundary marker. This often results in errors while parsing that message and the loss of all messages following that point. IIRC the error becomes unexpected EOF after all the remaining messages have been mistakenly skipped looking for that missing boundary. I was looking to Python and the email classes to whip up a quick and dirty spam filter, so "filter out the spam first" is not a solution to my problem. FWIW, Netscape does not have any problem with this same data. I've had moderate success by reading all the messages into a string, splitting the string on "^From ", passing individual messages to the email parsing classes, and treating the the unexpected EOF exception like a real EOF. But with hundreds of messages daily, that's a rather clumsy and expensive operation. It also defeats the effort the email classes go to to avoid having to have everything in memory. I'm curious if I'm missing something obvious here and if there's some easy way to get mailbox to work with large amounts of real world email with imperfect encodings. If possible, perhaps mailbox should have some absolute sense of the end or beginning of a message ("^From "?) that overrides mime boundaries. That MUST be how Netscape does it. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From martin at v.loewis.de Mon Sep 30 17:20:21 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Sep 2002 23:20:21 +0200 Subject: xml.dom.minidom parser error References: Message-ID: revyakin at yahoo.com (revyakin) writes: > Any ideas what this could mean? Writing a parser by myself does not > sound exciting. No, it just means that you have to install one. You can chose either pyexpat, or xmlproc; if pyexpat, you can either use the wrapper that comes with Python, or PyXML. If you use the wrapper, install Expat 1.95.x, and point Modules/Setup to the location where you have installed Expat. If you want to use xmlproc, or don't want a separate Expat installation, install PyXML. Good luck, Martin From pete at shinners.org Wed Sep 25 12:22:57 2002 From: pete at shinners.org (Pete Shinners) Date: Wed, 25 Sep 2002 16:22:57 GMT Subject: Pygame event problem References: <41c203e.0209250702.160102d@posting.google.com> Message-ID: Anand wrote: > I wrote a simple image viewer in python using pygame image api. The > GUI is in wxPython. There are 2 classes, one for the window frame and one > for the pygame image processing. > The effect is stopped by clicking with the mouse on the pygame > display window. My problem is that if I try to invoke any other menu methods > in the main GUI frame *without doing this*, the application ie both the > wxFrame and the pygame display window, hangs. > > > I have a gut-feeling that this is because I am calling a method on > the MyPyGameImgViewer class without exiting the while loop. > > Is there a way around this, ie to call any method in the > MyPyGameImgViewer class from the GUI class, while one of its methods > is executing a while loop i'd be a little afraid of mixing wxpython and pygame like this, but it sounds like you are pretty close to running. to exit the pygame loop you could probably just pass it a mouse button event e = pygame.event.Event(MOUSEBUTTONDOWN) pygame.event.post(e) of course, that also means you'll probably want to clear the pygame event queue before starting your while loop. also, to clear the event queue it will probably be better to get _all_ the events from the queue. otherwise it will fill up with mouse motion and other types of events. change the event part of the loop to this if pygame.event.peek(MOUSEBUTTONDOWN): pygame.event.get() break instead, you could also filter the pygame event queue, so only mouse button events were put onto the queue. the code for that would be like this pygame.event.set_allowed(None) #allow no events pygame.event.set_allowed(MOUSEBUTTONDOWN) #only allow buttondown also, there are ways to get SDL to work within an embedded window. therefore embed into a wxpython control. basically it involves setting an environment variable to an existing window id/handle. wxpython allows you to get the id/handle you need. the code to embed the SDL window looks kind of like this: handle = wxpython_widget.get_window_id_i_forget_how() os.environ['SDL_WINDOWID'] = str(handle) if sys.platform == 'win32': os.environ['SDL_VIDEODRIVER'] = 'windib' #no directx embedded pygame.init() size_is_ignored = 10, 10 window = pygame.display.set_mode(size_is_ignored) also, since you are likely only using the display portion of pygame, no need to initialize the whole thing (like audio/cd/joystick/etc). you could change the "pygame.init()" call do just "pygame.display.init()" that should be pretty slick when you get it working. although it's been a long time since i did anything like this. this should be all the correct info. oh, also remember, when you embed the SDL window like this, it will not receive any input events. you'll need to use wxpython's event handling for that. From mcherm at destiny.com Tue Sep 10 12:44:07 2002 From: mcherm at destiny.com (Michael Chermside) Date: Tue, 10 Sep 2002 12:44:07 -0400 Subject: embedded Python sample References: <2a0f4cc4.0209100520.1d3a723b@posting.google.com> Message-ID: bruno Monnet wrote: > Hi, > > I'm trying to call a python script from my c++ code. All I need is to > invoke the script and check the return status. > > does anyone has a simple example ? All I found until now is very > complex and ugly code :-(( > > Regards, > Bruno Why not just execute as a sub-process... invoke it as a shell command just as you'd do with "ls". -- Michael Chermside From k at kk.k Sat Sep 21 17:53:06 2002 From: k at kk.k (Zed) Date: Sat, 21 Sep 2002 21:53:06 GMT Subject: Math optimization Message-ID: <6T5j9.145247$pX1.5195840@news2.tin.it> Hi! What's faster in python? Divide or multiply? (a= b*c is faster than a=b/c)? Math expressions with constants are calcolated during .pyc creation or real time? (a=b*5 is faster than a=b*5*2/2 )? Thanks From python at rcn.com Fri Sep 6 08:15:54 2002 From: python at rcn.com (Raymond Hettinger) Date: Fri, 6 Sep 2002 08:15:54 -0400 Subject: tree data structure References: Message-ID: There are a number of ways to represent trees: -- instances of a treenode class -- a list of lists: [l0, [s2, [s0, [q1]], [s1,[q2]], [s3]]] -- or, my favorite, a dictionary of lists: >>> original = [('L0','S2'), ('S2','S0'), ('S2','S1'), ('S1','Q2'), ('S0','Q1'), ('S2','S3')] >>> tree = {} >>> for key, value in original: tree.setdefault(key,[]).append(value) >>> tree {'S2': ['S0', 'S1', 'S3'], 'S1': ['Q2'], 'S0': ['Q1'], 'L0': ['S2']} Raymond Hettinger "Padraig Brady" wrote in message news:FM0e9.2860$cP3.6165 at news.iol.ie... > Hi, > > I've a graph like stucture represented > by a list of tuples: > > [(L0,S2), (S2,S0), (S2,S1), (S1,Q2), (S0,Q1), (S2,S3)] > > And would like to convert it to > a tree structure like: > > S0 - Q1 > / > L0 - S2 - S3 > \ > S1 - Q2 > > Any tips appreciated. > > Thanks, > P?draig. > From tjreedy at udel.edu Mon Sep 9 21:43:29 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 10 Sep 2002 01:43:29 GMT Subject: Diving into the Python pool.... References: Message-ID: <57cf9.424498$Aw4.17832215@bin2.nnrp.aus1.giganews.com> "Jordan Faris" wrote in message news:mailman.1031613328.24522.python-list at python.org... >My primary focus is to create streamlined, rapid-deployment web applications >(PHP and JSP portal sites, etc), but from what I've seen, Python can be used >or adapted to achieve comparable results; Your main problem may be choosing from the 5+ Python-based web app frameworks already available. Welcome. Terry J. Reedy From mstenner at phy.duke.edu Fri Sep 6 09:51:41 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Fri, 6 Sep 2002 09:51:41 -0400 Subject: pygtk In-Reply-To: ; from martin.klaffenboeck@gmx.at on Fri, Sep 06, 2002 at 03:30:48PM +0200 References: Message-ID: <20020906095141.A14067@phy.duke.edu> On Fri, Sep 06, 2002 at 03:30:48PM +0200, Martin Klaffenboeck wrote: > Hello, > I'm new here in Python, because a few people told me that the > implementation of gtk is better in python than in Perl. So now I try do > do object orientated programming here... > > Is this a good group to discuss pygtk things or is this just for python? There is a separate pygtk list that would be most appropriate for pygtk questions. Obviously, the people there are familiar with python. It is not necessarily true that people here use/know pygtk. http://www.daa.com.au/mailman/listinfo/pygtk > (I think I have questions in both.) Perhaps you should subscribe to both lists then. > So now this message is also to say 'Hello' to everybody in this room. Hello. > Maybe you'll here much from me. ;-) Wonderful. We hope you enjoy python. -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From gustav at morpheus.demon.co.uk Sat Sep 7 06:02:02 2002 From: gustav at morpheus.demon.co.uk (Paul Moore) Date: 07 Sep 2002 11:02:02 +0100 Subject: Smoothing a discrete set of data Message-ID: <3csmdso5.fsf@morpheus.demon.co.uk> This isn't so much a Python question, as an algorithms question. I couldn't find a newsgroup for discussing algorithms (is there a good one?) so as I'm implementing the code in Python I thought I'd try here - I hope that's OK. I have a set of data, basically a histogram. The data is pretty variable, and I'd like to "smooth" it to find trends. Actually, this comes up a *lot* for me - some examples: sampled IO rates on a machine - I want to look for trends (is IO higher overnight or during the day, etc) or fuel consumption for my car (do I use less fuel since I had the service). Normally, what I do with things like this is draw a graph, and try to spot the trends "by eyeball". But it feels to me like I should be able to write something which smooths the data out. I just don't see how :-) Take an example - here's a rough ASCII-art diagram 9 XX XX 8 XX XX XX 7 XX XX XX XX XX 6 XX XX XX XX XX XX 5 XX XX XX XX XX XX 4 XX XX XX XX XX XX 3 XX XX XX XX XX XX XX XX XX 2 XX XX XX XX XX XX XX XX XX XX XX XX XX 1 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX This seems to me to have very clear peaks at the left and right, and a shallow point in the middle. I'd say that you could "smooth" this to something that averaged 8 for the first 3 bars, then 2 for the next 9, then 7 for the last 3. But try to make that precise... When I've tried to formalise this, I've always stumbled over the fact that it's a trade-off exercise (there most be some sort of "tolerance" parameter in the algorithm) - on the one hand, the original data is "best" (in the sense that it matches exactly) whereas on the other hand, a single horizontal line at the average is "best" (fewest number of steps). My instinct is that you're looking for something that balances number of steps vs difference from the original data. But for the life of me I can't see how to make this intuition precise. Can anyone help me? I can't believe that this problem has never come up before, but I can't find any literature on it. Thanks in advance, Paul Moore. From sschwarzer at sschwarzer.net Sun Sep 8 12:37:05 2002 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sun, 08 Sep 2002 18:37:05 +0200 Subject: Strange threads/stack size interaction on FreeBSD References: <3D765A95.6090308@tu-clausthal.de> Message-ID: <3D7B7CB1.4070201@sschwarzer.net> Hi Neal Unless noted otherwise, the descriptions below refer to the problematic stack size of 512 MB. Neal Norwitz wrote: >>- Should I enter a bug report on this topic? > > Probably, although, there are few people who can test with your > configuration. So you may be stuck debugging this yourself. > > If you have stack traces, are they very long? where does the crash > occur? It's rather a block than a crash. I was able to reproduce the problem with this small test script: ----- import threading def hello(): print "Hello" t = threading.Thread(target=hello) t.start() t.join() ----- The program blocks in t.join(). A backtrace from pdb.py just before blocking is ----- (Pdb) bt (1)?() /srv/home/svss/thread_test.py(8)?() -> t.join() /usr/local/lib/python2.2/threading.py(450)join() -> self.__block.wait() > /usr/local/lib/python2.2/threading.py(190)wait() -> waiter.acquire() (Pdb) s ----- So, to be more precise, the program stops on calling waiter.acquire() in _Condition.wait(). Apart from that, I could stop the python process only with the kill command from another terminal, but not with Ctrl-C in the xterm where Python was running. I also got kernel trace output on FreeBSD and noted that I see the program blocking here, too. That is, the dump doesn't grow larger when I let hang the program around longer. The last entries before the program hangs are: ----- 21517 python CALL mmap(0xbfaef000,0x10000,0x3,0x400,0xffffffff,0,0,0) 21517 python RET mmap -1 errno 12 Cannot allocate memory 21517 python CALL __sysctl(0xbfbff160,0x2,0x8810c440,0xbfbff15c,0,0) 21517 python RET __sysctl 0 21517 python CALL poll(0x8175000,0,0) 21517 python RET poll 0 21517 python CALL poll(0x8104000,0,0) 21517 python RET poll 0 21517 python CALL poll(0x8104000,0,0) 21517 python RET poll 0 21517 python CALL gettimeofday(0x881a97ec,0) 21517 python RET gettimeofday 0 21517 python CALL poll(0x8104000,0x1,0xffffffff) ----- which is shortly after reading atexit.pyc. > What compiler are you using? gcc 2.95.3 > Can you report all the tests that don't pass? Output from make test: ... test test_asynchat crashed -- socket.error: 61 ... test test_fork1 failed -- test failed ... test test_pwd produced unexpected output: ********************************************************************** *** mismatch between line 7 of expected output and line 7 of actual output: - caught expected exception + fakeuid 4127 did not except pwd.getpwuid() ********************************************************************** ... test test_socket failed -- (48, 'Address already in use') ... 161 tests OK. 4 tests failed: test_asynchat test_fork1 test_pwd test_socket ... However, in order to let the tests succeed, I disabled all tests beginning with "test_thread". Suprisingly, after make test was through, it didn't return to the prompt but I could stop it with Ctrl-C. > Have you tried with the latest and greatest source? > 2.2.1+: cvs update -r release22-maint I got "cvs [update aborted]: no such tag release22-maint". > 2.3: cvs update -A I get all the same symptoms as described above; I didn't look for the kernel trace dump, but the test script still hangs. After just reactivating the old kernel with a stack size of 256 MB I get the expected output "Hello" and the script returns to the prompt. The last entries in the kernel trace dump are (from the same position onwards as above): ----- 217 python CALL mmap(0xbfaef000,0x10000,0x3,0x400,0xffffffff,0,0,0) 217 python RET mmap -1079054336/0xbfaef000 217 python CALL setitimer(0x2,0xbfbff554,0) 217 python RET setitimer 0 217 python CALL mmap(0xbfade000,0x10000,0x3,0x400,0xffffffff,0,0,0) 217 python RET mmap -1079123968/0xbfade000 217 python CALL __sysctl(0xbfbff524,0x2,0x4810c440,0xbfbff520,0,0) 217 python RET __sysctl 0 217 python CALL poll(0x8193800,0,0) 217 python RET poll 0 217 python CALL fstat(0x1,0xbfafe80c) 217 python RET fstat 0 217 python CALL ioctl(0x1,TIOCGETA,0xbfafe840) 217 python RET ioctl 0 217 python CALL write(0x1,0x8199000,0x6) 217 python GIO fd 1 wrote 6 bytes "Hello " 217 python RET write 6 217 python CALL clock_gettime(0,0xbfaedfa4) 217 python RET clock_gettime 0 217 python CALL poll(0x8104000,0,0) 217 python RET poll 0 217 python CALL poll(0x8104000,0,0) 217 python RET poll 0 217 python CALL gettimeofday(0x481a97ec,0) 217 python RET gettimeofday 0 217 python CALL sigaction(0x2,0xbfbff8fc,0) 217 python RET sigaction 0 217 python CALL sigprocmask(0x1,0x480dee60,0xbfbff9e0) 217 python RET sigprocmask 0 217 python CALL sigprocmask(0x3,0x480dee70,0) 217 python RET sigprocmask 0 217 python CALL setitimer(0x2,0xbfbffa00,0) 217 python RET setitimer 0 217 python CALL close(0x3) 217 python RET close 0 217 python CALL close(0x4) 217 python RET close 0 217 python CALL fcntl(0,0x3,0) 217 python RET fcntl 6 217 python CALL fcntl(0,0x4,0x2) 217 python RET fcntl 0 217 python CALL fcntl(0x1,0x3,0) 217 python RET fcntl 2 217 python CALL fcntl(0x1,0x4,0x2) 217 python RET fcntl 0 217 python CALL fcntl(0x2,0x3,0) 217 python RET fcntl 2 217 python CALL fcntl(0x2,0x4,0x2) 217 python RET fcntl 0 217 python CALL exit(0) ----- Probably, the best is to discuss this on one of the FreeBSD mailing lists. Anyway, thank you very much for your help. :-) Stefan From sross at connectmail.carleton.ca Wed Sep 4 20:52:45 2002 From: sross at connectmail.carleton.ca (Sean Ross) Date: 5 Sep 2002 00:52:45 GMT Subject: Python Source Code Documentation Message-ID: Hi. I'm interested in trying to get an understanding of Python's source code. I'd like to understand how it works. I was wondering if there exists a set of documents or guidelines I could read, alongside the source, that would outline what each file in the cvs is, what it does, how it fits into the overall design: sort of like a thread through the maze. Where to begin, what's important, how things tie together. That sort of thing. Thanks for your time, Sean Ross From markus.vonehr at ipm.fhg.de Thu Sep 5 11:56:25 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 05 Sep 2002 17:56:25 +0200 Subject: upgrading python Message-ID: <3D777EA9.F9A96C83@ipm.fhg.de> Hi, first of all I'd like programming in python. Sometimes you need to grade up to a newer version. I have to download everything again and install every single package, for example: -win32all -PyOpengl -Pyserial -Numeric -unzip Pmw -PIL -py2exe -PyXML etc. So I just mentioned "only" 8 packages, additionally I have to install the newer python version and to uninstall the old packages... Couldn't it be made easier? Maybe I do something wrong and am misunderstanding how to deal with it. Now I wanted to grade up to tk84. It was quite hard to find _tkinter.c, then I downloaded the tcl-sources, tk-sources, installed MSVC6, found out that some X11 stuff is missing... I know that all mentioned packages are different projects but could it be made that there's a python distribution with all packages up2date and the installer is asking for the desired ones? Do you have similar experiences? Markus From mhammond at skippinet.com.au Sat Sep 7 20:11:26 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sun, 08 Sep 2002 00:11:26 GMT Subject: untrusted dynamic module: win32api References: Message-ID: Enoch wrote: > Hi, > > I'm a Softimage|XSI user, a 3D graphic software that support ActiveX > Scripting on win32 platforms. > > This software integrate a 'NetView', an integrated internet explorer. > > To be able to communicate between the NetView and XSI I have to create the > XSI.Application object. > > Works fine with VBScript and JScript, however I'm running into a problem > trying to make it work with Python. > > Basicaly I have to include in my html page the following code: > > > > But when I load this page into the NetView ( or even in an external > brother ) I have this error message: > > 'ImportError: untrusted dynamic module: win32api' > > Is there any way to 'force' the import ? > > Sorry if this has been discussed earlier, I'm relatively new to Python. It appears that SoftImage is configuring ActiveScripting for "untrusted" scripts - ie, SoftImage is requesting the scripting engine switch into untrusted mode. Thus, you really need to ask SoftImage is the application can be configured to not request restricted execution mode of the language. Mark. From gerhard.haering at opus-gmbh.net Wed Sep 11 06:23:22 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 11 Sep 2002 10:23:22 GMT Subject: function pointer References: Message-ID: Christina wrote: > Does Python have function pointers? [...] Functions, as well as modules, classes and about everything else are objects in Python. Python doesn't have pointers, but it does have references, so you can make a reference to a function like this: def foo(): pass # Create a reference to the 'foo' function: bar = foo Python is highly dynamic, so this is nothing special. You can make references to functions, classes and even modules. You can dynamically create functions and classes at runtime, and a lot more. Servus, Gerhard From steve at ferg.org Thu Sep 12 08:36:40 2002 From: steve at ferg.org (Stephen Ferg) Date: 12 Sep 2002 05:36:40 -0700 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> <20020911150511.GA28720@unpythonic.net> Message-ID: Thanks. This has got to be the authoritative answer on what "command" does! From BPettersen at NAREX.com Tue Sep 17 02:37:17 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Tue, 17 Sep 2002 00:37:17 -0600 Subject: threads or queue for this task Message-ID: <60FB8BB7F0EFC7409B75EEEC13E201920125335E@admin56.narex.com> > From: James J. Besemer [mailto:jb at cascade-sys.com] > > >James J. Besemer wrote: > > > >>Generally, Queues never get "full" and you generally don't care if > >>they're empty. > > > >You can define Queues that can hold a maximum number of items; [...] > > > >Setting size is just an optional embellishment, though sometimes it > >does pay dividends. > > > > Setting size has it's place but otherwise introduces unnecessary > complications. Among other things, it forces the queue > writer to deal with the situation of what to do if the queue is full. Signal error > back to its client? Sleep and try again later? Silently > discard the request? Abort? > > "Generally," NOT having a limit is by far the more elegant solution. [snip] You must be kidding (or you can't have written any significant amount of multithreaded code). In the general producer/consumer paradigm you want the producer to look very similar to: try: while 1: work = createWork() if not work: break queue.push(work) # block if queue full if I'm the last producer: # kill consumers for i in range(numberOfConsumerThreads): queue.push(None) except Timeout: abendGracefully() and the consumer to look very similar to: try: while 1: work = queue.pop() # block until not empty if not work: break process(work) except Timeout: abendGracefully() If you have any amount of data to process (why else would you be multithreading?) I've never seen producers and consumers being close enough in performance to not have the system end up swapping to death -- unless, that is, if the queue is bounded. The Python Queue module supports most of this out-of-the-box, and adding timeouts is fairly trivial... processing-too-many-16Gb-files-with-tight-SLAs-leaves-scares'ly y'rs -- bjorn From mal at egenix.com Thu Sep 5 13:24:05 2002 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 05 Sep 2002 19:24:05 +0200 Subject: [DB-SIG] RE: What database should I use References: Message-ID: <3D779335.1040603@lemburg.com> > Hello, > I am going to program a small application (in Python and wxPython) which > consists about 2000 - 3000 records . Can you please recommend which database > is the best for that. I use Windows. Maybe MS Access or FoxPro or MySQL or > better? I want to keep the program as small as possible. Thanks Ladislav If you only use it internally, then I'd suggest downloading and installing the MS MDAC package and using it via ODBC. You get the Access Jet-Engine for free that way. Another approach would be SAP DB which is Open Source and works nicely on Windows too. -- Marc-Andre Lemburg CEO eGenix.com Software GmbH _______________________________________________________________________ eGenix.com -- Makers of the Python mx Extensions: mxDateTime,mxODBC,... Python Consulting: http://www.egenix.com/ Python Software: http://www.egenix.com/files/python/ From david at dataovation.com Thu Sep 26 19:51:10 2002 From: david at dataovation.com (David McInnis) Date: Thu, 26 Sep 2002 16:51:10 -0700 Subject: POP3 and Multipart Mime Message-ID: <005c01c265b7$97954d40$6400a8c0@bigdaddy> Does anyone know where I can find a tutorial on how to accomplish the following? I need to log into a POP3 account (which I have been able to do using poplib). I need to be able to read and decode the message. The problem is that most of our users send word docs as attachments (1 or more). I need to take these files and save them to disk. David McInnis -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at aleax.it Thu Sep 26 13:22:11 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 17:22:11 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <3D911FE1.1050801@something.invalid> Message-ID: <7nHk9.172208$pX1.6117207@news2.tin.it> Pedro RODRIGUEZ wrote: ... >>> But why use grotesque hacks in the first place? "a ? b : c" is a ... > Ada has two short-circuits operators : "and then" and "or else" that > do the trick : > if A and then B then > ... > end if; > > Looks cleaner to me. Ada's "and then" is like Python's "and"; Ada;s "or else" is like Python's "or". Neither is like C's "a?b:c" (ternary operator), though with some tricks boolean shortcircuiting operators can be used to simulate ternary operators (a bit cumbersome in the general case). The reason zz = a and b or c is not the same thing as zz = a ? b : c is that, when a is true and b is false, the former returns c, while the latter returns b. The tricks deal with ways to work around this problem, by ensuring that and's RHO can never be false, e.g. zz = (a and [b] or [c])[0] The other traditional emulation of ternary operator is by indexing, e.g.: zz = (b, c)[not a] and here the defect is that this isn't short-circuiting -- both the b and c sub-expressions are evaluated anyway, no matter what's the value of a (this is a problem when, e.g., b is actually a function call such as "fb()"). Here, the workarounds can use and/or if it's OK to evaluate _a_ multiple times: zz = (a and b, not a and c)[not a] or lambdas: zz = (lambda:b, lambda:c)[not a]() The deeper problem with all of these "solutions" is that they're unholy kludges, of course. Alex From kingprad at mail.com Fri Sep 27 16:09:52 2002 From: kingprad at mail.com (Carl) Date: 27 Sep 2002 13:09:52 -0700 Subject: Python Process that can survive References: Message-ID: <668b76ce.0209271209.36412b6b@posting.google.com> That's pretty cool! I can't wait to try it. From aleax at aleax.it Wed Sep 18 11:41:08 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 15:41:08 GMT Subject: Splitting a list of strings References: Message-ID: Emile van Sebille wrote: ... > for line in lines: > vals["@#".find(line[:1])+1].append(line) ... > Or, if you want to use an lc: > > [ vals["@#".find(line[:1])+1].append(line) for line in lines] The lc variant wantonly produces and throws away a list of copies of None, one per line in lines. It's thus likely to be quite a bit slower than the simpler loop. IMHO, vals should be a dictionary indexed by the character used to discriminate -- using vals as a list and doing a find operation repeatedly seems a waste. However, I admit I haven't timed the two alternatives, so I could be wrong! Alex From ahmad at NOSPAMbitbuilder.com Mon Sep 9 07:55:55 2002 From: ahmad at NOSPAMbitbuilder.com (Ahmad Baitalmal) Date: Mon, 09 Sep 2002 11:55:55 GMT Subject: xml.minidom is stripping out my CRLF's in attrib values!! References: <3D7C80C4.9070204@NOSPAMbitbuilder.com> Message-ID: <3D7C8C76.8060700@NOSPAMbitbuilder.com> That's not what my problem is, that I know about ( crlf's between nodes),, Here is the deal: After the word "spotted" there is a crlf, -inside- the attribute value. Sholdn't it be treated as part of the value? The value now comes stripped of that crlf. Martin v. L?wis wrote: > Ahmad Baitalmal writes: > > >>What's the deal, is there a setting I can set? > > > XML specifies that line endings must be normalized by a processor, see > > http://www.w3.org/TR/REC-xml#sec-line-ends > > There is no option to report anything but #xA to the application. > > Regards, > Martin > -- - - -- ---- ----------------------------------------- --- -- - - *Ahmad Baitalmal*** *BitBuilder*** web: http://www.bitbuilder.com - - -- ---- -------------------------------------------------------------- --- -- - - From mtremblay at golemlabs.com Fri Sep 13 10:56:32 2002 From: mtremblay at golemlabs.com (Mathieu Tremblay) Date: 13 Sep 2002 07:56:32 -0700 Subject: Embed extended Python Message-ID: Hello, I am quite new to Python and I'd like to embed extended python. The problem is that the documentation I can find on the internet is always related to C standard types and not to C++ objects. To extend python I use the really good SWIG tool and everything is fine. The problem comes when I try to call a python script that takes as an argument one of the class that I have defined in C++ through swig. Exemple: C++ class extended to python with SWIG, through the module wheel: CWheel { CWheel(){} ~CWheel(){} printWheel() { printf("I am a wheel"); } }; Now, let's suppose that the module is successfully exported and can be used in python. An example of simple python script would be : import wheel def thefunction(awheel): awheel.printWheel() Calling this function directly from python (supposing we provide the correct argument) works perfectly. The problem comes when I want to call this script from C++. Maybe It is a stupid question but here it is: How do you pass an existing CWheel as an argument to the function from C++??? How do you wrap a CWheel to a PyObject? I guess the method would be to use the function PyObject_CallObject(pFunc, pArgs); the pArgs being a PyTuple where I can set a PyObject to a position X. The problem is that all the examples that I find convert int, char*, long, double etc. to PyObject with built in python functions but no different/user defined class. Anybody can help? Thanks a lot, Mathieu From shalehperry at attbi.com Fri Sep 6 12:56:35 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 6 Sep 2002 09:56:35 -0700 Subject: Getting a proccesses ID In-Reply-To: References: Message-ID: <200209060956.35530.shalehperry@attbi.com> On Friday 06 September 2002 09:48, Micah Mayo wrote: > > Ah, but os.getpid get's my pid, I need to get another programs, and in > fact, several other program's pid. :) > hence the smiley. If you wanted to be cool about it you could write a python module which parsed the various /proc interfaces of BSD, Linux, Solaris and created process trees/maps/dictionaries from this data. Kind of like writing a generic db frontend to read the os's backend. From solonas73 at hotmail.com Fri Sep 20 07:08:43 2002 From: solonas73 at hotmail.com (Solon Kazantzidis) Date: 20 Sep 2002 04:08:43 -0700 Subject: access to palm with pilot-link pisock library (python binding) Message-ID: <24165ed4.0209200308.4d6b3b7a@posting.google.com> Hello, I want to achieve the following: - I want to use the python language to access my palm pilot Vx - I found the pilot-link package which provides a python binding of the pisock library written in c - Unfortunately the documentation I need as newbie to this is listed in the TODO list so I am searching a documentation - I want to be able to connect to the Palm (I have some example for a connection from the pyrite-publisher .py file) - I want to be able make what the pilot-xfer -l command does - I want to be able to create/delete/access databases stored on my Palm - I need to have access on data which I want to gather with the Palm What I achieved so far: 1. downloaded pilot-link package (version 0.11.3) 2. build it and created the python binding (python version 2.2.1) 3. from file plugin_instpisock.py (pyrite-publisher) I got some starting information to establish connection to the palm: ------------------------------------------------------------------------- #!/usr/bin/python2.2 import pisock port = "/dev/pilot" sd = pisock.pi_socket(pisock.PI_AF_SLP, pisock.PI_SOCK_STREAM, pisock.PI_PF_PADP) if not sd: print "failed to create socket" exit if (pisock.pi_bind(sd, (pisock.PI_AF_SLP, port))) == -1: print "failed to bind socket" exit if (pisock.pi_listen(sd, 1)) == -1: print "failed to listen on socket" exit ret = pisock.pi_accept(sd) if ret == -1: print "failed to accept connection" exit socket = ret[0] pisock.dlp_OpenConduit(socket) pisock.dlp_ReadDBList(sd,0,pisock.dlpDBListRAM,0) -------------------------------------------------------------------------- As there is no documentation out there and I am not the best programmer I can only say that the whole procedure stops with a: "Speicherzugriffsfehler"-->(translated) "Memory access failure" All works fine until the "ret = pisock.pi_accept(sd)". At this point the python interpreter stops and waits for me to press the hotsync button. After I press it the above mentioned error arises. I need urgently help with this as I cannot with the start form my thesis until the mechanism for accessing works. (and then the real work of synchronising gathered data starts....) Thanks alot for your help/comments, Solon. From martin at v.loewis.de Fri Sep 6 12:03:28 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Sep 2002 18:03:28 +0200 Subject: Getting a proccesses ID References: Message-ID: Micah Mayo writes: > Can anyone tell me a cross platform way of grabbing a particular > processes ID Depends on how you want to identify the process. If the process is a child of yours, you best safe the process id at the time of process creation. If the process is sshd, you read at /var/run/sshd.pid. If you don't trust that sshd saves its pid file in /var/run, you read /etc/sshd/sshd_config - it might be best to find out the location of sshd.pid at installation time. If you *really* need to invoke ps, I recommend to - perform the searching in Python, instead of invoking grep/awk. - you plan for two families of ps binaries: SysV and BSD. On Solaris, ps x says usage: ps [ -aAdeflcjLPy ] [ -o format ] [ -t termlist ] [ -u userlist ] [ -U userlist ] [ -G grouplist ] [ -p proclist ] [ -g pgrplist ] [ -s sidlist ] 'format' is one or more of: user ruser group rgroup uid ruid gid rgid pid ppid pgid sid taskid pri opri pcpu pmem vsz rss osz nice class time etime stime f s c lwp nlwp psr tty addr wchan fname comm args projid project pset On Solaris, it so happens that you can use /usr/ucb/ps x, but that won't be available on other SysV systems. The SysV equivalent is "ps -e". - you plan for multiple sshd processes being found. In theory, you need to find the one that has "1" as its parent process, but killing the one with the lowest pid might be good enough in real life. Regards, Martin From peter at engcorp.com Thu Sep 5 23:51:53 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 05 Sep 2002 23:51:53 -0400 Subject: A Free Idea: Search Engine for Webpages References: <3D685D54.249F3350@engcorp.com> <477762c2.0208260615.3790945@posting.google.com> <3D6AB55D.63D36207@engcorp.com> Message-ID: <3d78263f@news.sentex.net> Serge Boiko wrote: > It would be very kind of you to ask the name of the software. > Many thanks. > -Serge Sorry, I lost track of this thread after you asked and before I managed to find out, until Amit's posting brought it to my attention again (and basically answered the question, too). More specifically, http://toolbar.google.com should be where you go for this thing. -Peter From david.abrahams at rcn.com Sun Sep 29 16:15:27 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sun, 29 Sep 2002 16:15:27 -0400 Subject: Why does QT Windows need Visual Studio? References: <3ljepusnje8iuca90im2r9vceja5tfc5l7@4ax.com> Message-ID: "John Hall" wrote in message news:3ljepusnje8iuca90im2r9vceja5tfc5l7 at 4ax.com... > I was about to download the Windows non-commercial version of QT, but > noticed that it requires MS Visual Studio, so didn't. > This requirement surprises me - is there a way around that? http://kde-cygwin.sourceforge.net/qt3/ -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From dbasch at yahoo.com Mon Sep 30 12:11:06 2002 From: dbasch at yahoo.com (Derek Basch) Date: Mon, 30 Sep 2002 09:11:06 -0700 (PDT) Subject: Catching user defined exceptions from foreign modules Message-ID: <20020930161106.27910.qmail@web20805.mail.yahoo.com> Everyone, Well, after pulling my hair out last night trying to figure out why my user defined exceptions were not working as I would expect, I fired up the modules this morning and they work exactly as I would expect them too. Its enough to drive a man (or woman) insane! However, I still would appreciate someone telling me if it is normal to have to import user defined exceptions. Thanks for all the help everyone and sorry to waste your time :( Thanks, Derek Basch __________________________________________________ Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! http://sbc.yahoo.com From bdesth at nospam.free.fr Tue Sep 3 23:37:12 2002 From: bdesth at nospam.free.fr (laotseu) Date: Tue, 03 Sep 2002 23:37:12 -0400 Subject: ascii value References: Message-ID: <3D757FE8.2020907@nospam.free.fr> Axel Grune wrote: > A sorry, I missed ord(), shoot me Bang ! laotseu From tim.schulz at sdm.de Wed Sep 4 05:22:38 2002 From: tim.schulz at sdm.de (Tim Schulz) Date: 4 Sep 2002 02:22:38 -0700 Subject: using python to call java code?? Message-ID: <3cc90cd2.0209040122.17242a04@posting.google.com> I am considering to use zope in order to develop an content management portal. My problem is, that I have to integrate some ready-built java code. Is there any possibility to call java code from python? Is there a API for this kind problem? Thanks in advance. Tim Schulz From Padraig at Linux.ie Mon Sep 30 09:01:50 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Mon, 30 Sep 2002 13:01:50 GMT Subject: Find out link location References: <7uf9na-vd9.ln@lbdb01.gsi.de> Message-ID: <3D984AF8.3070908@Linux.ie> Klaus Hoeppner wrote: > Hi, > > with the os.path module I can use the islink function to check, wether > a file is symbolic link. But how can I find out, where the link points > to. E.g. if I have readme.txt --> ../packages/mypackage/readme.txt how > do I get the "../packages/mypackage/readme.txt" with python? import os filter (lambda x: x.find("link") != -1, dir(os)) #see the 2nd item P?draig. From Oschler at earthlink.net Sat Sep 28 23:43:34 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 29 Sep 2002 03:43:34 GMT Subject: Fast-track to installing/implementing a SWIP module? References: Message-ID: "Gerhard H?ring" wrote in message news:slrnapcp8g.617.gerhard.haering at lilith.my-fqdn.de... > Robert Oschler wrote in comp.lang.python: > If I understand correcly, you only have to have SWI-Prolog in your PATH, then > the following: > > python setup.py build > > will build everything and > > python setup.py install > > will install your modules. > > > Explanation: This function: > > def get_atom(atom): > query = "pl -f none -g 'current_prolog_flag(%s, V), write(V), nl.' -t 'halt'" > f = os.popen(query % atom) > ... > > in setup.py should do the magic of finding the include and library paths to > link against SWI Prolog. > > -- Gerhard Gerhard, Thanks that's exactly what I needed. I'm still having a hard time with the 'ease' that things happen when doing things in Python. thx From tismer at tismer.com Fri Sep 20 09:19:19 2002 From: tismer at tismer.com (Christian Tismer) Date: Fri, 20 Sep 2002 15:19:19 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> <3D8A7735.3090403@something.invalid> Message-ID: <3D8B2057.5090002@tismer.com> Greg Ewing wrote: > Martin v. Loewis wrote: > >> That is not true. It is more reliable to inspect the source code. >> >> In general, it is very easy to do so: if there are no callbacks to >> Python, the module is stackless-safe. > > > > That's a fair point, and I guess it takes care of > the majority of extensions. > > But the cases where there is doubt are typically > going to be big, complicated things like GUI > libraries. Making a line-by-line inspection of > one of those isn't exactly something you do over > a cup of tea. > > And you don't just have to look at the code, you > have to understand what it's doing, because the > things which cause problems are dynamic rather > than static features of the code. Fine. But still I'm trying to see your true message. Why is it bad to just switch off switching when an unknown extension is entered? Making that xtension stackless-safe is in fact a project, I can't see anything bad with it. Compare it to olde Stackless: It refused to switch anything that wasn't the toplevel interpreter. New Stackless can be restricted in the same way. The only difference is that the new technology is *able* to switch any stacks. This should only be enabled if one knows what she's doing. But there is no reason to damn a new technology just because it is very powerful. Run it tamed by default, and everything is fine and by no means worse than before. On the other hand, if you want to take advantage of it with extension modules, then analyse these modules. This is a project, and I'm greatful for any contribution. but-there-is-no-free-lunch -- ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From ianholmes01 at lycos.com Tue Sep 3 12:09:45 2002 From: ianholmes01 at lycos.com (Ian Holmes) Date: 3 Sep 2002 09:09:45 -0700 Subject: Python to surpass C performance by 2030 References: <3D6B6D4B.B8EE2F7D@engcorp.com> Message-ID: holger krekel wrote in message news:... > We might as well consider sponsoring Armin Rigo with his fantastic > Psyco effort to achieve order-of-magnitude increases for python3. > > holger Yup pystoned it on my win2k machine and got a 4 fold increase. - ran a self made test script based on the "why it is so dramatical" post http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&threadm=mailman.1031047453.13193.python-list%40python.org&prev=/groups%3Fhl%3Den%26group%3Dcomp.lang.python and for the list join solution post a nice 3x speed up (the string += string2 was about the same unsurprisingly) - what ever Armin is doing its amazing and he has my vote. Ian From max at alcyone.com Mon Sep 16 02:06:42 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 15 Sep 2002 23:06:42 -0700 Subject: couldnt find __dic__ References: <7153651c.0209151958.4099ac3e@posting.google.com> Message-ID: <3D8574F2.3929F514@alcyone.com> black wrote: > my book told me all dictionaries have __dic__ method but I searched > each dictionaries and find nothing, where is it ??? I think you misread it. What it probably said is that all _instances_ have __dict__ attributes. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Success and failure are equally disastrous. \__/ Tennessee Williams REALpolitik / http://www.realpolitik.com/ Get your own customized newsfeed online in realtime ... for free! From Padraig at Linux.ie Mon Sep 16 06:01:01 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Mon, 16 Sep 2002 10:01:01 GMT Subject: representing a literal single slash References: <3D84E9F9.8090101@linux.ie> <3D84FEE6.90600@linux.ie> Message-ID: Terry Reedy wrote: > "Padraig Brady" wrote in message > news:3D84FEE6.90600 at linux.ie... > >>>mystr = mystr.replace(r'\\', r'\') >> >>Emm this actually doesn't work. Why can't you: >>s=r'\' >>Is it a bug? > > > Ref Manual 4.1: > When an `r' or `R' prefix is present, a character following a > backslash is included in the string without change, and all > backslashes are left in the string. For example, the string literal > r"\n" consists of two characters: a backslash and a lowercase `n'. > String quotes can be escaped with a backslash, but the backslash > remains in the string; for example, r"\"" is a valid string literal > consisting of two characters: a backslash and a double quote; r"\" is > not a valid string literal (even a raw string cannot end in an odd > number of backslashes). > Specifically, a raw string cannot end in a single backslash (since > the backslash would escape the following quote character) But there is no escaping when the prefix r is used? I guess there is a good reason for this inconsitency? P?draig. From jacob at boris.cd.chalmers.se.cd.chalmers.se Wed Sep 25 13:37:22 2002 From: jacob at boris.cd.chalmers.se.cd.chalmers.se (Jacob Hallen) Date: 25 Sep 2002 17:37:22 GMT Subject: Will "Python in a Nutshell" be too short? References: <915a998f.0209230848.60cc1415@posting.google.com> Message-ID: In article <915a998f.0209230848.60cc1415 at posting.google.com>, Hamish Lawson wrote: >Steve Holden wrote: > >> I wil be very surprised if Alex' book does not become the canonical >> reference for the language, since his treatment is exceptionally thorough >> and (even for him) more than usually precise. > >I had no doubts about this - I'm just a greedy so-and-so who wanted to >have Alex's treatment over as wide a range of material as would fit >into a book that could still qualify to be called a nutshell! I'm >therefore delighted to learn from Alex that his book will in fact >cover a good number of the most popular third-party libraries, and >I'll therefore get to throw away a bunch of printed-out notes after >all (which is what I meant when I hoped that "Python in a Nutshell" >would be a one-stop reference). I know Alex wanted to keep the book to >about 400 pages, but for me the 600 pages that the book has grown to >is still nutshell enough and a small price to pay for the breadth of >coverage. I'm looking forward to it. > > >Hamish I have had a small peek at 2 chapters in Alex Nutshell book. All I can say is that I think it is going to be the best Python reference on the market. Jacob Hall?n -- From phr-n2002b at NOSPAMnightsong.com Fri Sep 20 07:06:28 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Sep 2002 04:06:28 -0700 Subject: general thoughts References: Message-ID: <7xznuc2a4r.fsf@ruckus.brouhaha.com> "Dave Gustafson" writes: > I've been programming for, hard to believe when I think of it, 30 years... > I just recently picked up a book that really brought back som fo the Joy of > programming and programming languages. I wish I'd picked it up much > earlier! It's not about Python, but rather about a dialect of Lisp called > Scheme, and is titled "The Little Schemer". It's been really fun to work > through and really "grok" what's going on in programming, also fun to > translate the concepts there in to Python which to me is a more real-world > language. I'd suggest it as a way to have some fun with this art... That sounds like either a "port" or a re-interpretation of the classic "The Little Lisper". You should also of course have read "Structure And Interpretation of Computer Programs" by Hal Abelson and Gerry Sussman: http://www-mitpress.mit.edu/sicp/ The complete text is on that website now! From GavinT at ResMed.com.au Wed Sep 18 01:11:02 2002 From: GavinT at ResMed.com.au (Gavin Tomlins) Date: Wed, 18 Sep 2002 15:11:02 +1000 Subject: PythonScript Message-ID: <362133AB12B2CE4EA3C01E12CD6CCC6E0254E08E@osprey.corp.resmed.org> Thanks for the prompt reply David, yes unfortunately the suggestions you proposed have been implemented though to no avail. I guess its a matter of attrition. Shall repost if I find a solution. Regards Gavin -----Original Message----- From: David LeBlanc [mailto:whisper at oz.net] Sent: Wednesday, 18 September 2002 2:35 PM To: Gavin Tomlins; python-list at python.org Subject: RE: PythonScript > The problem I seem to be hitting is utilising python in applications that > embed an ActiveScript Engine. To date I am unable to get one python script > to execute. Other languages vbscript, jscript,perl etc, work in the same > environment so I'm left wondering if its a configuration problem or > something that I might be overlooking. If anyone could give me pointers, > url's, snippets etc. it would be interested. The product I specifically > having problems is FinalBuilder (http://www.atozedsoftware.com) > though have > seen this problem in other applications as well. > > I've tried both ActiveState and Python distribution 2.2.1 with Win32 > 1.48all. > > Regards > > Gavin > Did you register Python as an ActiveScript host? I believe this is done for you automatically if you use the installer and not done for you if you don't. It's possible that it gets done for you the first time you run the PythonWin IDE too. Have a look at this file: \Python22\Lib\site-packages\win32com\readme.htm HTH, Dave LeBlanc Seattle, WA USA Warning: Copyright ResMed. Where the contents of this email and/or attachment includes materials prepared by ResMed, the use of those materials is subject exclusively to the conditions of engagement between ResMed and the intended recipient. This communication is confidential and may contain legally privileged information. By the use of email over the Internet or other communication systems, ResMed is not waiving either confidentiality of, or legal privilege in,the content of the email and of any attachments. If the recipient of this message is not the intended addressee, please call ResMed immediately on +61 2 9886 5000 Sydney, Australia. From dwelch91 at nospam.attbi.com Fri Sep 20 01:45:58 2002 From: dwelch91 at nospam.attbi.com (dwelch) Date: Fri, 20 Sep 2002 05:45:58 GMT Subject: newbie seeks advise. References: <77c84db2.0209192137.51167ebb@posting.google.com> Message-ID: <3D89F5E4.1000002@nospam.attbi.com> akirasugiura wrote: > Hi, > > I've been learning python for about a month. I had no prior knowledge > of programming. > > My question is, I have a tuple which is, data = (69, 40, 74, 41, 56, > 57, 38, 58, 26, 55). How I can make a function that picks up a largest > number > from this "data" tuple. If "data" was a 'List' I would be able to > use "sort" but since sort doesn't work with tuple. I am stuck here. > > Thanks in advance > > Sincerely, > Simple way, probably not optimal: >>> max_element = max(list(data)) >>> max_element 74 From hancock at anansispaceworks.com Sun Sep 8 14:08:17 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 08 Sep 2002 11:08:17 -0700 Subject: horizontal scrolling (was Re: Larry Wall's comment on python...) Message-ID: <3D7B9211.86A1F406@anansispaceworks.com> Terry Hancock wrote: > that you don't need () on the if-clause (they may think they > will cause a syntax error -- which they *do* in csh/tcsh, > which they may have previous experience in, BTW). Duh. I don't know what I was remembering here, but it's not true that tcsh generates an error when the if expression is in ()s. There's plenty of other stuff to complain about, though. I think csh was invented to torture sysadmins. ;-D Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From rjones at ekit-inc.com Sun Sep 1 07:45:51 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sun, 1 Sep 2002 21:45:51 +1000 Subject: ANN: New PEP Format: reStructuredText In-Reply-To: References: Message-ID: <200209012145.51274.rjones@ekit-inc.com> On Sun, 1 Sep 2002 6:46 pm, Robin Becker wrote: > In article , Richard > Jones writes > >This is done in the docutils sandbox under the richard/pythonpoint > > directory. I had this working ages ago (back in March, I think) but > > hadn't updated it when David merged the dps and restructuredtext projects > > to form the docutils project. That's done now. > > > > > > Richard > > So does this appear as a CGI somewhere or should I go ahead and make a > working demo? No, there's no CGI. The pythonpoint script in the sandbox is a "working demo". Pass it a rest file as a command-line arg, and it'll spit out pythonpoint XML (read the example for limitations though). Richard From aleax at aleax.it Wed Sep 18 10:09:15 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 14:09:15 GMT Subject: Splitting a list of strings References: Message-ID: Sean Ross wrote: ... > filter, where you drop handfuls of change into the top of the device and > they come out the other side sorted into pennies, nickels, dimes, > quarters. In this case I had comments, attributes, and data. The comments ... > You can probably just chalk this all up to an infatuation with list > comprehensions. Yep. A list comprehension is a device that Python got from functional programming (Haskell, specifically): in functional programming, data structures don't mutate. Thus, a list comprehension doesn't mutate existing structures -- it just produces a new one. For the "change sorter" effect, use a normal loop and a dictionary of lists. Say you have a function "classifier" that accepts any item in the list and returns how the item should be classified (as a number, say, or a string -- any hashables that distinguish item classifications will do). "Sieving" a list that way is then trivial: def sieve(alist, classifier): result = {} for item in alist: result.setdefault(classifier(item),[]).append(result) return result If you don't want the result as a dictionary of lists, but e.g. a list of lists in ascending order of classifier-returned keys, change the last statement to: keys = result.keys() keys.sort() return [result[key] for key in keys] See, you get to use a list comprehension again in this case:-). Alex From ark at research.att.com Wed Sep 18 17:08:31 2002 From: ark at research.att.com (Andrew Koenig) Date: Wed, 18 Sep 2002 21:08:31 GMT Subject: A list comprehension to do this?... References: <3D88E4F5.B443918@quartercase.com> Message-ID: joe> Is there a list comprehension or other 'cleaner' or 'prettier' way joe> to do the following: >>>> xx = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) >>>> ww = [] >>>> for i in range(0, len(xx), 2): joe> ww.append((xx[i+1],xx[i])) How about [(xx[i+1], xx[i]) for i in range(0, len(xx), 2)] ? -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From aahz at pythoncraft.com Wed Sep 4 17:44:55 2002 From: aahz at pythoncraft.com (Aahz) Date: 4 Sep 2002 17:44:55 -0400 Subject: quick question about generator.next() References: Message-ID: In article , Erik Price wrote: > >If I have a generator object, the first value produced by the generator >object does not actually get produced until the first time I call >generator_object.next() , correct? > >In other words, simply instantiating the generator object doesn't >"activate" the generator function, rather it just creates it -- only >when the next() method is called does the generator's internal logic >"activate", right? Correct. I find that although technically inaccurate, it's a lot easier to think of generators as functions that return iterator objects. >(Where are generator objects getting their next() method from anyway... >is it implicitly inherited behind the scenes when I use the "yield" >keyword to turn a function into a generator?) Generator objects conform to the iterator protocol. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From erick_papadakis at REMOVEFORSPAM.yahoo.com Tue Sep 17 11:30:28 2002 From: erick_papadakis at REMOVEFORSPAM.yahoo.com (Erick) Date: Wed, 18 Sep 2002 00:30:28 +0900 Subject: can wxpython do this? References: <737aefee.0209151702.3f735252@posting.google.com> Message-ID: sorry for restating, but is there a way for me to connect to the Internet, make a call to a webserver as a browser would do, retrieve data and display it inside my application? perhaps an example of using sockets in wxpython? thanks much/erick From cliechti at gmx.net Sat Sep 7 16:42:28 2002 From: cliechti at gmx.net (Chris Liechti) Date: 7 Sep 2002 22:42:28 +0200 Subject: Killing/Terminating a running thread References: Message-ID: Heiko Wundram wrote in news:mailman.1031419029.11871.python-list at python.org: > Hi to all! > > I've looked over google groups, but I've found no real answer that > satisfied the needs I have. Just a little explanation: > > I have a Queue module, which stores method-calls and delegates them to > threads, which take over running the call. Now it happens that a method > takes much longer to complete than I would like it to, and in this case, > the thread running the code should just be terminated, discarding all > values computed so far. sound like the news thread "Interrupting Python" could be interresting for you... > The basic problem I have that it is pretty much impossible to get at the > PID of the thread running the code in question; but I have a reference > to the thread class in a central "garbage-collector" (the queue object). > And anyway, this approach would only work on Unix (I guess), when using > pthreads, which create a "real" subprocess with its own PID for a > thread. > > Has anyone had a similar problem, and know of a solution? the clean solution is to test for a flag and terminate if the flag is set. e.g. you could provide a function: def interrupted(): return global_flag_if_user_wants_to_abort and in you function in the queue: def worker(): while not interrupted(): do_stuff() you can do that of course with or without a function. a function has the benefit that you could do additional checks, such as stopping only a specific thread/worker. (e.g. threading.currentThread() could be used to test if it the thread to be killed) chris -- Chris From imbosol at vt.edu Sun Sep 1 19:45:55 2002 From: imbosol at vt.edu (Carl Banks) Date: Sun, 1 Sep 2002 19:45:55 -0400 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: Gerhard H?ring wrote: >> which means the real time is not spent in the compile() function, but >> in the match or find function. So basically, couldn't one come up with >> a *human readable* syntax for re, and compile that instead? > > That's equally powerful? Most probably not. Why not? It won't be as fast, but it should be able to do anything a regexp can do, and would be much more versatile. -- CARL BANKS http://www.aerojockey.com From fperez528 at yahoo.com Fri Sep 27 17:35:56 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 27 Sep 2002 15:35:56 -0600 Subject: Better terminal for windows? References: <3D94B037.2020202@motorola.com> Message-ID: Gerhard H?ring wrote: >> If I want to run python interactively (and perhaps using ipython), is >> there something better than the "cmd" terminal? > > Well, you could install MSYS from the mingw project, which is sort of a > Cygwin-lite :-) > >> I'm used to bash on linux at home, but I'd like to avoid installing >> cigwin for now. Thanks. > > cmd.exe isn't that bad once you activate tab completion in the > registry. Have you done that? That is, as long as you aren't interested in tab completion for python :) The problem is lack of support for readline, which is how you get tab completion under python. The other problem is that the windows terminal doesn't properly honor ANSI color escapes. I tried a lot to get ipython's coloring to work under windows and finally gave up in disgust. Why is it that MS can't be bothered to _ever_ follow the simplest standards? So some of ipython's nicest functionality (full support for tab completion for both objects and files, and color-enhanced information, tracebacks and even syntax highlighted source info) are gone under Windows. If you know of a way to fix this, patches are welcome :) Cheers, f. From Oschler at earthlink.net Tue Sep 10 12:52:10 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Tue, 10 Sep 2002 16:52:10 GMT Subject: Trouble upgrading to 2.2.1 References: Message-ID: <_qpf9.29862$w51.7937790@news2.news.adelphia.net> "Gerhard H?ring" wrote in message news:slrnans81k.jc.gerhard.haering at lilith.my-fqdn.de... > Robert Oschler wrote in comp.lang.python: > > I'm trying to upgrade from 2.1.1 to 2.2.1. I'm using kpackage (KDE's rpm > > wrapper). > > You should install the OpenSSL libraries in order to fulfill these > dependencies. If you do have the OpenSSL libraries installed, but the > libcrypto or libssl version numbers are different on your machine, you can > try to provide the necessary symlinks so rpm will shut up. > I have 0.9.6b-34 of OpenSLL installed. Is this the wrong version or do I have a different problem? thx From steve at ferg.org Tue Sep 10 21:25:58 2002 From: steve at ferg.org (Stephen Ferg) Date: 10 Sep 2002 18:25:58 -0700 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> Message-ID: "Steve Holden" wrote in message news:... > "Stephen Ferg" wrote in message > news:b16e4ef7.0209090552.3ad7691b at posting.google.com... > The problem, from a learner's point of view... > Steve Holden Thanks! An excellent answer. And I think it puts a finger on what I'm trying to do in "Thinking in Tkinter" in contrast to other explanations of Tkinter that I've encountered. Most other introductions to Tkinter programming would start by explaining how to use "command", on the grounds that it is simpler to use, and will get you up and running faster. A quicker way to get a learner productive. A perfectly reasonable approach. What I wanted to do, though, in "Thinking in Tkinter" was more of an explanation of the basic concepts that you need in programming with Tkinter. From that standpoint, I think it is better to explain about binding -- that is, binding widgets, events, and callback handlers -- by explaining "bind()". Then, once the basic concepts are explained, I can note how "command" can be used as a labor-saving technique. As you say, "it's rather like teaching someone to drive by explaining the mechanical details of the steering and engine." Maybe a good example would be, "it is sort of like teaching someone to drive by explaining the details of the differential". It is possible to explain the techniques of say, driving on slippery road surfaces -- or getting out of ditches when you're stuck -- without explaining how the differential works. But if you know how the differential works, you will better understand why you should -- or shouldn't -- do certain things in certain situations. I guess what I'm saying is that this kind of explanation gives you more than just techniques. It gives you an organizing set of deeper concepts -- a mental model -- within which the techniques make sense. That's the kind of explanation of Tkinter that I'd like to read. "Thinking in Tkinter" will never be the book that I'd like to read. I don't have the time to do that. But I'd like it to cover a few of the most basic points, in the way that such a book would cover them. I'm not saying that that kind of approach is better. Only that it might be a better approach for certain folks with certain learning styles. ... My apologies for the verbosity! Anyway, Steve, thanks for your very helpful answer. You're a good explainer. I'm going to go to Amazon right now and order a copy of "Python Web Programming"! From Doc at goodweb.de Thu Sep 5 18:03:57 2002 From: Doc at goodweb.de (Thomas Korb) Date: 06 Sep 2002 00:03:57 +0200 Subject: 4Suite / McMillan Installer / py2exe References: Message-ID: Thanks for the answers! (@Thomas Heller: I really like your py2exe; it does a great job when using the standard Python- distribution only; and it is very easy to use!) I think I found a solution for Gordon McMillan's Installer: In the 4Suite distribution, there is a module named 'Math.py' in (e.g. for Python 2.2): C:\Python22\Lib\site-packages\Ft\Xml\Xslt\Exslt\ This causes problems with Python's built-in math-module (most probably since Win32 systems are not case-sensitive) when trying to use Gordon McMillan's Installer. (The executable is built; but when you try to use e.g. the XSLT-Processor of 4Suite, you get a lot of error-messages.) Solution - Rename the above module to something like 'myMath.py' and change the import of 'Math' in __init.py__ (in the above dir) to 'myMath'. Then everythingworks just fine. (I am only using the XSLT-Processor; so maybe the above changes affect other parts of 4Suite. Did not check that up to now. But as far as I could see, the Math.py - module is not used very often in the 4Suite-distribution.) I will report this to the people at 4Suite.org. Maybe they still have the chance to change this modules name in the next distribution. -- ----------------- Dr. Thomas Korb - G O O D W E B . D E s i g n --- ----------------- DOMAIN: www.goodweb.de / E-MAIL: Doc at goodweb.de --- From dman at dman.ddts.net Thu Sep 12 10:35:32 2002 From: dman at dman.ddts.net (Derrick 'dman' Hudson) Date: Thu, 12 Sep 2002 10:35:32 -0400 Subject: Paradox table In-Reply-To: <3D7F5DD6.8814.1363983@localhost> References: <3D7F5DD6.8814.1363983@localhost> Message-ID: <20020912143532.GA17566@dman.ddts.net> On Wed, Sep 11, 2002 at 03:14:30PM +0200, A wrote: | Hi, | Is there a module for reading Paradox database (.DB) files with Python? | I need to run the script under Linux, so I can not use ODBC. | Any suggestion would be appreciated One way to access the data is to export it from paradox in CSV format. CSV is an open standard and several (python) parsers exist for it. However, using this method won't allow you to easily access the data from both paradox and from your script, instead you would need to re-export it every time you modified it in paradox and you would not be able to modify it using your script. If you can, it would probably be easiest to migrate to a different db such as postgresql. Postgres databases are much more accessible than paradox is (at least with the paradox version I've seen, 3.5). -D -- Dishonest money dwindles away, but he who gathers money little by little makes it grow. Proverbs 13:11 http://dman.ddts.net/~dman/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 248 bytes Desc: not available URL: From sholden at holdenweb.com Fri Sep 6 18:11:00 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 6 Sep 2002 18:11:00 -0400 Subject: Dead Man Timer? References: <3D728103.5060308@itamarst.org_NOSPAM> Message-ID: "Neil Everhart" wrote in message news:FrOc9.110025$_91.144030 at rwcrnsc51.ops.asp.att.net... > Itamar, > > Thank you for the suggestion. I will test the timeoutsocket.py code > tomorrow > on my target setup. I have incorporated it into a version of my script but > can not really evaluated it until I am running in the terminal server > environment. > > Neil. > > -- > > > "Itamar Shtull-Trauring" wrote in message > news:3D728103.5060308 at itamarst.org_NOSPAM... > > 1. Use timeoutsocket.py - this lets you set timeouts on socket operations > > (find it on http://py.vaults.ca). > > > > 2. Use an event driven networking architecture - don't know of any that > have > > telnet client support though. > > > > Option 1 is your easiest solution. > > Note that similar functionality is currently planned for 2.3. Changes have been checked in. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From eddie at holyrood.ed.ac.uk Thu Sep 19 06:47:07 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Thu, 19 Sep 2002 10:47:07 +0000 (UTC) Subject: Strange Telnet error References: <4378fa6f.0209181245.7b06124d@posting.google.com> Message-ID: mnations at airmail.net (Marc) writes: >Hi, >I have been running some code that all the sudden stopped working. I >can not figure out what's happened. I am doing a simple telnet >connection that sends and receives info. Now I am getting this error: >Traceback (most recent call last): > File "C:\Python22\lib\threading.py", line 408, in __bootstrap > self.run() > File "C:\Python22\lib\threading.py", line 396, in run > apply(self.__target, self.__args, self.__kwargs) > File "main.py", line 85, in run > command[0](*command[1:3]) > File "key.py", line 92, in command > conn.write(com) > File "C:\python22\lib\telnetlib.py", line 272, in write > self.sock.sendall(buffer) >AttributeError: 'int' object has no attribute 'sendall' Have you just loaded a new version of Python by any chance. Line 272 in my 2.2 copy of telnetlib has 'send' instead of 'sendall', the latter seems to be the better of the two so I guess it's a newer version. Which makes me suspect they've broken something else while working on it, in which case I'd report it as a bug. Unless of course, your code fiddles about with the underlying sockets and things of the telnet object. Eddie From roy at panix.com Thu Sep 5 15:18:51 2002 From: roy at panix.com (Roy Smith) Date: 5 Sep 2002 15:18:51 -0400 Subject: Why Python? References: <4f49d232.0209050418.7668c21@posting.google.com> <3D77FB95.3070300@nospam.free.fr> Message-ID: I wrote: >> If you're learning languages to study computer >> science, lisp is looking a lot better. laotseu wrote: > I think once you know them both, you know *how* to program, whatever > the language you have to use. I believe we actually both said the same thing, just worded differently :-) From keilj_33 at yahoo.com Tue Sep 3 16:25:20 2002 From: keilj_33 at yahoo.com (Jeffrey Keil) Date: 3 Sep 2002 13:25:20 -0700 Subject: basic cgi question Message-ID: <67f6bbe5.0209031225.56b1b7bd@posting.google.com> Greetings: I've used Perl in the past for cgi programs. I thought I'd play around a little with Python. I've tried a few experiments. I have programs that prints out to the browser. Unfortunately, it prints out everything, including the "import" statements, "print", etc. I'm not quite sure what I'm doing wrong. Thanks, Jeff Keil From ark at research.att.com Fri Sep 27 19:25:28 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 27 Sep 2002 23:25:28 GMT Subject: Better terminal for windows? References: <3D94B037.2020202@motorola.com> Message-ID: Stephen> I'm using python 2.2.1 on winnt. Stephen> If I want to run python interactively (and perhaps using ipython), is Stephen> there something better than the "cmd" terminal? How about idle? -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From martin at v.loewis.de Mon Sep 16 17:57:36 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Sep 2002 23:57:36 +0200 Subject: Mutable Stings References: <6qznuhx1je.fsf@thetis.intevation.de> Message-ID: Bernhard Herzog writes: > Not necessary. I submitted a bugreport when this came up the last time > and it has been fixed in CVS since then. You are right; I was using an old copy. Regards, Martin From rsrchstr at hotmail.com Sun Sep 29 17:26:05 2002 From: rsrchstr at hotmail.com (mike henley) Date: 29 Sep 2002 14:26:05 -0700 Subject: idea for a much needed application Message-ID: <576c1752.0209291326.56dcdf31@posting.google.com> I remember a while ago reading about tim burners-lee and how his vision of the WorldWideWeb as a medium where all can freely and easily publish information has not materialized properly, and i felt it so strongly over the past week when trying to look at options for hosting a website. Hosts are either expensive or limit you in terms of what languages, modules, applications, and OSs you can use. They also limit you in terms of space, bandwidth used per period, number of executions of CGIs... etc. Some of those who give good deals, seem difficult to trust with either your credit card number or your content. I wish i can just use my own computer, with whatever technologies I choose, keeping my content that i build up over time safe here on my own machine, but unless you have a broadband connection this is not possible. It may be possible using a dynamic DNS provider, but then again either they add cost, end up with an ugly URL, and, most importantly, there's no way for others to know when you get online. So here comes the idea that occured to me, and i post it here to ask if you know of an application that already provides this functionality, then please tell me what it is, or if you think it is worth doing on an open source basis, or even proprietary, in which case i invite anyone to do so, or if you think it's a completely stupid and impossible idea, then perhaps you can please tell me why. You probably guessed if you read as far as the second paragraph that what i'm thinking about is an application functionality that enables instant messaging to provide the dynamic DNS functionality. So instead of giving others a URL I can just give them an IM username they can add to their client, and when i go online, through my humble dial-up connection that changes IP whenever i log in, they'll be aware of my presence, and be able to connect to a server i host on my machine. It sounds like a simple thing; IM presence, automatic IP query of my username, click on my username and or use a contextual menu option or whatever and a browser launches to go to the site i'm hosting on my machine. Perhaps it can use existing open-source platforms, such as jabber or gnutella, or as an add-on to existing open-source applications/clients. Basically what i'm suggesting is a little tool to enable a server such as apache to join the whole IM/p2p thing and have "presence". The more automated it is, and the easier it is, the better. I think such a functionality will be especially useful for certain uses, in my case it will be hosting a wiki, as i leave my machine online a lot through my dial-up, can't predict the number of executions of CGI or the amount of space needed, wish to be free to use whatever wiki application is best for my needs and in whatever language regardless of what a host will support, and do not wish to pay a monthly fee, extra charges, setup fee or a domain registration. Perhaps there can be other areas where it is useful, and i'm sure there are other areas where it will not be suitable. Perhaps there can also be a simple way to enable a page hosted in such a way to be submitted to search engines, i haven't thought about that yet, but tell me if u see any. What do you think? already done, worth doing, stupid, or impossible? (p.s. please also let me know if there are other newsgroup to which posting this will be a good idea) From aleax at aleax.it Wed Sep 25 05:21:58 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 09:21:58 GMT Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> <96zj9.150553$pX1.5399868@news2.tin.it> <3D911CFA.4060405@something.invalid> Message-ID: Greg Ewing wrote: ... >>>Using *tabs* only is the only way to get truly >>>preference-independent indentation. >> >> ...unless other people use tools that do NOT let them change the >> ways tabs are displayed, and that way is intolerably incompatible >> with your use of tabs. > > I agree there are good reasons to prefer spaces-only > for code that will be transmitted or displayed by > dumb software. To put it differently: use tabs only if you ARE willing to bet a very substantial amount that the source file in question will NEVER be transmitted, displayed, nor otherwise processed in any way, shape, or form, by software you consider "dumb" (take it up with KDE KNode's maintainers whether their news reader is "dumb"... I like it, though it doesn't show tabs:-). > I was only pointing out that, whatever arguments there > may be in favour of spaces-only, "it doesn't force the > reader to view it the way you do" is not one of them! I agree with you that this is a fact. Only very smart software would be able to display varying amount of leading spaces in programmable ways, and software that smart would no doubt be able to do anything with tabs too. Alex From prema at prema.co.nz Sat Sep 28 14:08:18 2002 From: prema at prema.co.nz (Mike) Date: Sat, 28 Sep 2002 18:08:18 GMT Subject: py2exe and a single exe file? -- Oops References: <3D792351.3070008@motorola.com> Message-ID: This time !!! :-) from distutils.core import setup import sys, os, py2exe name = sys.argv[1] sys.argv[1] = 'py2exe' sys.path.append(os.path.dirname(os.path.abspath(name))) setup(name=name[:-3], scripts=[name]) Stephen Boulet wrote: > I'm trying to get py2exe to work for me, and I must be doing something > wrong. > > I have a script that uses easygui (which uses Tkinter) and Numeric. It > also imports a small module from the same directory that the script > resides in. > > I try building it like this: > > python setup.py py2exe -d N:\ -i easygui > > It builds and runs, but only with the other stuff in the build directory > with the generaged exe. The other stuff is: > > tcl directory containing tcl8.3 and tk8.3 directories > _numpy.pyd > _sre.pyd > _tkinter.pyd > multiarray.pyd > umath.pyd > > What I would like to accomplish is just having a single exe file lumping > everything together. Is this possible? > > -- Stephen > From jb at cascade-sys.com Fri Sep 27 05:31:41 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 27 Sep 2002 02:31:41 -0700 Subject: Getting started References: <3D911306.7080609@ucsd.edu> Message-ID: <3D94257D.2020501@cascade-sys.com> Adam Taylor wrote: >This sounds like the same thing as I said, or damn close. Am I >missing something? > Not really. Just different emphasis. >Yes. It seems to me that Table 1 in Cardelli: > > Typed Untyped >Safe ML LISP >Unsafe C Assembler > >Might be better like this: > > Statically typed Dynamically typed Untyped >Safe ML LISP >Unsafe C Assembler > >(Python would also be in the (Safe,Dynamically typed) position.) > >Although safety and strongly-checked are not the same thing, this >table is also correct: > > Statically typed Dynamically typed Untyped >Strongly checked ML LISP >Weakly checked C Assembler > I agree. So where in this spacewould YOU put Python and Perl? >>A literal reading furthermore defines "weakly typed" only in >>terms of static checking. >> >> > >I don't understand what you mean by this. Cardelli never uses the >term "weakly typed" himself, he only uses it that one time, to say >that it's the term most people use for the concept that he prefers to >call "weakly checked". > I was translating his internal vocabulary to use the term we started with. He defines "weakly checked" only in terms of "static checking". Since they're synonyms, this reference only supports a def of "weakly typed" in terms of static checked languages. So I'm saying the reference does not help us nearly as much as I would like. >Or at >least when people start talking about "strongly typed" vs "weakly >typed" languages, that first thing to get straight is which axis >they're talking about. > Fair enough. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From senux at senux.com Thu Sep 26 06:28:23 2002 From: senux at senux.com (Brian Lee) Date: Thu, 26 Sep 2002 19:28:23 +0900 Subject: CGI server by Python Message-ID: <20020926102823.GA17893@mercury.senux.com> Hi, I tested CGIHTTPServer.py in Python 2.2 and found that cgi files in sub directory does not run. Does anybody know about this? /cgi-bin/test.cgi works. /cgi-bin/a/test.cgi does NOT works. $ python CGIHTTPServer.py Serving HTTP on 0.0.0.0 port 9002 ... avante.xxx.co.kr - - [26/Sep/2002 19:20:24] code 403, message CGI script is not a plain file ('/cgi-bin/a') avante.xxx.co.kr - - [26/Sep/2002 19:20:24] "GET /cgi-bin/a/test.cgi HTTP/1.1" 403 - avante.xxx.co.kr - - [26/Sep/2002 19:20:33] "GET /cgi-bin/test.cgi HTTP/1.1" 200 - /cgi-bin/test.cgi and /cgi-bin/a/test.cgi is same file. -- Brian Lee From marklists at mceahern.com Fri Sep 27 18:02:06 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 27 Sep 2002 17:02:06 -0500 Subject: watching mutables? In-Reply-To: Message-ID: Someone (I think Skip?) mentioned the possibility of using metaclasses. The OP has asked for a method that doesn't require modifying the original code. This doesn't satisfy that request, but is interesting nonetheless (imho): #!/usr/bin/env python class Watched(type): def __new__(cls, cls_name, bases, classdict): # print "__new__(%s, %s, %s, %s)" % (cls, cls_name, bases, classdict) def w_setattr(self, name, value): print "%s.__setattr__(%s, %s)" % (cls_name, name, value) bases[0].__setattr__(self, name, value) def w_setitem(self, i, el): print "%s.__setitem__(%s, %s)" % (cls_name, i, el) bases[0].__setitem__(self, i, el) def w_getitem(self, i): print "%s.__getitem__(%s)" % (cls_name, i) return bases[0].__getitem__(self, i) def w_getattribute(self, name): print "%s.__getattribute__(%s)" % (cls_name, name) return bases[0].__getattribute__(self, name) classdict['__setattr__'] = w_setattr classdict['__setitem__'] = w_setitem classdict['__getitem__'] = w_getitem classdict['__getattribute__'] = w_getattribute return type.__new__(cls, cls_name, bases, classdict) class WatchedDict(dict): __metaclass__ = Watched class WatchedList(list): __metaclass__ = Watched l = [] l.append(1) l = WatchedList() l.append(1) d = WatchedDict() d['a'] = 1 print d['a'] ** Output: WatchedList.__getattribute__(append) WatchedDict.__setitem__(a, 1) WatchedDict.__getitem__(a) 1 From pierpaolo.glave at ciaolab.com Wed Sep 4 08:55:22 2002 From: pierpaolo.glave at ciaolab.com (Pier Paolo Glave) Date: 4 Sep 2002 05:55:22 -0700 Subject: Tkinter, updateStringProc for type font Message-ID: <1907a5e4.0209040455.64ae73b1@posting.google.com> Hi all, I'm facing a problem with my Python program, which uses Tkinter to interface Tcl/Tk. I sometimes get this error message from Tcl: "UpdateStringProc should not be invoked for type font". As a consequence, the application crashes with SIGABRT (6). I'm using: Python 2.2, Tcl/Tk 8.3.3-69. I've seen in the tcl sources that this happens when a function named Tcl_GetString() is called for a "type" which has the "byte" field set to NULL, and no "updateStringProc" function pointer: this seems to happen for Tk type "font", sometimes in my application. Anyway, I'm not able to understand more. Has anyone encountered this problem before? Thank you -- Pier Paolo Glave From padraig at linux.ie Sun Sep 15 16:12:33 2002 From: padraig at linux.ie (Padraig Brady) Date: Sun, 15 Sep 2002 20:12:33 GMT Subject: representing a literal single slash References: Message-ID: <3D84E9F9.8090101@linux.ie> Jonathan Claggett wrote: > Here is an easy question (I'm hoping). > > I'm trying to process a string so that all doubled up backslashes (\\) > are replaced with a single backslash (\). > > The obvious approach doesn't work since a single backslash can't end a > string: > > str = str.replace('\\', '\') # broken > > So, how does one represent a literal single slash? unicode or hex > values perhaps? mystr = mystr.replace(r'\\', r'\') P?draig. From joe.sixpack at quartercase.com Wed Sep 18 16:41:25 2002 From: joe.sixpack at quartercase.com (joe sixpack) Date: Wed, 18 Sep 2002 20:41:25 GMT Subject: A list comprehension to do this?... Message-ID: <3D88E4F5.B443918@quartercase.com> Is there a list comprehension or other 'cleaner' or 'prettier' way to do the following: >>> xx = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) >>> ww = [] >>> for i in range(0, len(xx), 2): ww.append((xx[i+1],xx[i])) >>> ww [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)] >>> Thanks in advance... From tundra at tundraware.com Sun Sep 1 16:40:03 2002 From: tundra at tundraware.com (Tim Daneliuk) Date: Sun, 01 Sep 2002 20:40:03 GMT Subject: [ANN]: 'waccess' 1.61 Released Message-ID: I have just released version 1.61 of 'waccess': http://www.tundraware.com/Software/waccess/ 'waccess' is a Quick And Dirty web access log analysis tool. It's useful if you want to see how many hits a particular file has seen on your web site. It will also attempt to get the names of the accessing hosts by doing reverse lookups on their IP addresses. 'waccess' is not a replacement for a serious web log analysis tool, but it is quite handy nonetheless. 'waccess' is written in Python and needs a reasonably current version of the langugage on your machine. 'waccess' was written for and tested on FreeBSD 4.6R, but should port to other systems pretty trivially. This version adds two features: - User can now name the log to examine on the command line instead of having to edit the string constant in the source. - The program now supports 'ignoring' IP addresses. You can designate which IP address spaces you do not care about and 'waccess' will ignore all records from such addresses. Changes to the FreeBSD port have been committed as well. -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From 102030405 at gmx.net Sat Sep 28 01:54:05 2002 From: 102030405 at gmx.net (Ralf Claus) Date: Sat, 28 Sep 2002 07:54:05 +0200 Subject: zlib needs the python15.dll on python22 ??? Message-ID: Hello NG, by importing the zlib module on python 2.2 (windows) i get a popup that means "python15.dll not found in path //winnt/system32/......and so on... On that computer, there was never installed python 1.5 !? What is wrong ? Thanks a lot Ralf From jeff at sasmor.com Mon Sep 9 10:11:20 2002 From: jeff at sasmor.com (Jeff Sasmor) Date: Mon, 09 Sep 2002 14:11:20 GMT Subject: Zope Status? References: <3D7C4833.2080308@mxm.dk> Message-ID: Hi Max, What I meant was that since the initial implementation won't support the old (Zope 2) APIs, you'd have to have the mindset to dig in and see what's going on. The learning curve for Zope 2 is made easier due to the many existing apps and examples that exist. Even so, it's a complex system and is daunting for a lot of folks. I expect that the ratio of folks who use Zope to those who create apps in Python for Zope is pretty high. Right now, almost anyone who wants to play around can install Zope 2 and get it to do things by installing some popular apps like Squishdot (etc,etc). You only have to know how to install software to be able to be productive. Until this same state of affairs exists for Zope 3 (and there's nothing to say that it will take that long, one hopes) it will take a more advanced (tyro < 'advanced developer' < Einstein) developer who has the time and inclination to poke into the innards and see how it works. Especially as the docs will likely trail the sw for a while. >From what I've seen, Zope 3 is more regular and better organized than Zope 2, but it _is_ different. Anyway, that's all I meant. Nothing bad, just inevitable. Anyway, it's just my opinion, so it doesn't matter all that much! jms -- #-------------------------------- Jeff Sasmor jeff at sasmor.com "Max M" wrote in message news:3D7C4833.2080308 at mxm.dk... > Jeff Sasmor wrote: > > > > That's just one thing. Also, Zope 3 is a clean-slate redesign; that is, > > it is being rearchitected with no initial regard for existing Zope > > applications. I suppose opinions go either way on this, but overall > > it is probably a Good Thing. I recall reading that there will eventually > > be backwards compatibility, perhaps with some interface layer, but > > I suspect that the initial releases will be for very advanced developers. > > > As far as I can see from the examples you actually don't need to be an > advanced developer. It seems that it will indeed be much more simple to > develop for Zope3 than it is for the current version. > > Also they are taking care of some of the things that could make it > difficult to develop in Zope. Like relations. > > > regards Max M > From peter at engcorp.com Mon Sep 16 09:20:04 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 16 Sep 2002 09:20:04 -0400 Subject: "if x == None" raises "'NoneType' object is not callable" References: Message-ID: <3d85da78$1@news.sentex.net> Luc Saffre wrote: > """ > If I define __getattr__() and __setattr__() for a class, then I cannot > test instances of this class for equality with None. > > the code example below raises > TypeError: 'NoneType' object is not callable > > class Row: > > def __init__(self): > self.__dict__["_values"] = {} > > def __getattr__(self,name): > try: > return self._values[name] > except KeyError,e: > AttributeError,str(e) > > def __setattr__(self,name,value): > self.__dict__["_values"][name] = value > > > row = Row() > if row == None: # here it happens. > print "row instance is None!" When when you call "row == None" it calls __getattr__ with '__eq__' to see if you want to provide a equality comparator function. Inside __getattr__ you are not going to find such a beast, so you go to the exception handler. Unfortunately, you left out the "raise" keyword, so you are in the end returning None as all methods do in Python which don't explicitly return something else. -Peter From sholden at holdenweb.com Sun Sep 29 07:00:34 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 29 Sep 2002 07:00:34 -0400 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: wrote... > > [ ... ] OK, so don't use whole pennies (or smallest currency) as your base, use 10,000ths of a penny, but still use integer arithmetic for your calculations. Floating point has too many rounding errors to be trustworthy; or, looking at it from another angle, floating-point calculations cannot be 100% accurate because of the way it's implemented. "...has too many errors to be trustworthy..." is clearly an overstatement given the huge number of computations each day which use floating-point without any apparent problem. Floating-point got us to the moon and back, surely it can handle a few money computations. The real problem is that you have to grok the nature of floating-point to use it well and appropriately. This is not a simple task (and you only have to look at the timbot to realise that it can have disastrous consequences ;-). A typical modern double (64-bit floating-point number) will give you an effective 53 bits of fraction, which equates to over 14 significant figures. Since you always need two digits after the decimal point you can work with amounts up to 999,999,999,999.99 without loss of accuracy as long as you know what you are doing. Appropriate rounding before storage will avoid accumulation of rounding errors. Of course, none of this is necessarily an argument that f-p is the *best* representation for money, but I'm always amused to see people arguing against it on general grounds when it's perfectly acceptable for many such purposes *when correctly used*. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From peter at engcorp.com Wed Sep 18 09:52:33 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Sep 2002 09:52:33 -0400 Subject: try except ImportError failing to catch error! References: Message-ID: <3d888514$1@news.sentex.net> Ben Gerblich wrote: > I am importing all module files in the CWD. This part works fine. > > I want to add the functionality to catch the error if there is a > typo in the imported module file. The following does not catch > the error! > > try: > self.userDefs[file[:-3]]['class'] = __import__(file[:-3]) > except ImportError, e: > print 'cant do it', e > > I still get the runtime error: >[...] > TypeError: line() takes exactly 5 arguments (6 given) That's not an import error, so your exception handler won't catch it. If you want to catch *any* error in the imported module, you'll have to do "except Exception, e" instead. Unfortunately, then you'll also have ImportErrors in the mix, so you won't know if the module could be found but had its own error, or if the call to __import__ failed... Also, you won't know whether perhaps the file[:-3] expression failed, or any of the other stuff that might fail in that import line. > And is there a way for my handler routine to return the line-number of > the imported module file that caused the error? Look into the traceback standard module. I don't understand why you want to intercept these exceptions anyway. If you want to catch the error, *and* the line number, and print it, why don't you want Python to show you where the problem came from? Maybe there's a better approach than what you've selected so far... -Peter From Hobbes2176 at yahoo.com Thu Sep 19 15:46:55 2002 From: Hobbes2176 at yahoo.com (Mark) Date: Thu, 19 Sep 2002 19:46:55 GMT Subject: Minimal debug/rep functionality References: <3d894106@news.sentex.net> Message-ID: Peter Hansen wrote: > > Sorry, I couldn't find a solution that was larger than six lines: > > >>> def trace(frame, event, arg): > ... if event == 'line': > ... print '%s: %s' % (frame.f_code.co_filename, frame.f_lineno) > ... return trace > ... > >>> import sys > >>> sys.settrace(trace) > > -Peter Hey, This is exactly what I needed. Now, can you explain to me how I hook in a "local" trace function to take over once I execute the function I'm interested in tracing? I'd like to use the "event" argument to take note of calls that are 1 level deep (ie in my foo function, any calls made) and turn off tracing of these until they return back to the level of foo. I presume I could implement this with a "if event == 'call':" condition, but I can't seem to get a global trace function to hook up to a local trace function ... it does one or two things right, then goes crazy. Regards, Mark From mmoales at fluent.com Thu Sep 5 10:40:02 2002 From: mmoales at fluent.com (Mark Moales) Date: Thu, 05 Sep 2002 10:40:02 -0400 Subject: Privacy and Inheritance References: Message-ID: <3D776CC2.CA928E38@fluent.com> Dennis, I think the point of the double underscores is to create "private" attributes similar to C++'s or Java's private keyword. In other words, only the class that defines the attribute can access it. Subclasses and others can't. We use a single underscore here to denote "protected" attributes, or attributes that are accessible by subclasses. However, the only way to enforce this in Python is by having well behaved programmers ;-) Here's an example: class BaseClass: def __init__(self): self.publicVar = 'Foo' self._protectedVar = 'Bar' self.__privateVar = 'Spam' class SubClass(BaseClass): def aMethod(self): print self.publicVar print self._protectedVar # Can't do this because it's private # print self.__privateVar Mark "Dennis B." wrote: > > Greetings; > > Have enough confidence in Python to realize this is probably just my > misunderstanding, but wondering why Python mangles private, double > underscore attributes with the name of the base class even if they're > inherited and the instance is that of the sub class. > > Like the following doesn't even seem to work: > > class StandardNormal: > > def letEventZScore(self, eventZScore): > self.__eventZScore = float(eventZScore) > > class DerivativeNormal(StandardNormal): > > def getCentral(self): > if self.__eventZScore < 0: > > Unless I change that last line to something like: > > if self._StandardNormal__eventZScore < 0: > > Maybe just missing the point all together, but wondering if anyone'll > point out anything a little more elegant and/or intuitive. > > Thank you and have a great day, -------------- next part -------------- A non-text attachment was scrubbed... Name: mmoales.vcf Type: text/x-vcard Size: 281 bytes Desc: Card for Mark Moales URL: From marklists at mceahern.com Tue Sep 10 15:42:48 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 10 Sep 2002 14:42:48 -0500 Subject: Reset a generator function? In-Reply-To: <%Lrf9.30107$w51.7961593@news2.news.adelphia.net> Message-ID: [Robert Oschler] > How can I reset a generator function so that it begins yielding > values as it did when first called? My braindead way of doing it is just to create another instance of the generator: $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import generators >>> def mygen(): ... i = 0 ... while True: ... i += 1 ... yield i ... >>> x = mygen() >>> x.next() 1 >>> x.next() 2 >>> x.next() 3 >>> x = mygen() >>> x.next() 1 >>> // m - From pyth at devel.trillke.net Mon Sep 30 15:53:27 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 30 Sep 2002 21:53:27 +0200 Subject: Question about __getattribute__/__getattr__ In-Reply-To: ; from jpm@papercut.org on Mon, Sep 30, 2002 at 03:04:24PM -0400 References: Message-ID: <20020930215327.X30315@prim.han.de> Joao Prado Maia wrote: > On Mon, 30 Sep 2002, Mark McEahern wrote: > > > > if cached_value == None: > > > > This is an aside, but comparison to None should be via identity rather than > > equality; e.g., > > > > if x is None: > > > > or: > > > > if x is not None: > > > > Yeah, I always forget that when switching from PHP to Python. Anyway, my > main question was how to get the list of arguments passed to a > method/function. Any ideas ? :) Probably you are interested in the Memoize recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 regards, holger From Padraig at Linux.ie Thu Sep 12 05:42:14 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Thu, 12 Sep 2002 09:42:14 GMT Subject: Anyone got a logfile script? - Help a n00b References: Message-ID: <3D806151.9020707@Linux.ie> Daniel Stuart Kelly wrote: > What I'm looking for is a little script when run will dig into a log file and > look for a variable. > > When it finds the variable I want it to print that line and the 20 or so right > above it to either screen or a plaintext file. > > I know it sounds simple, but I've only started learning this and I've no idea > where to begin.. Any tips or pointers would also be helpful... > > Thanks > /Daniel > would a "context grep" not be simpler? grep --before-context=20 log.file P?draig. From hst at empolis.co.uk Tue Sep 10 08:44:57 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 10 Sep 2002 13:44:57 +0100 Subject: Pickle problem Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D10@hendrix.empolisuk.com> Erik Price wrote: > > On Tuesday, September 10, 2002, at 06:13 AM, Harvey Thomas wrote: > > > I'm trying to pickle a complicated data structure which includes a > > dictionary whose entries are created by (simplified): > > > > a[x] = re.compile(y).match > > > > The pickle fails, however, with the error: > > > > PicklingError: Can't pickle _sre.SRE_Pattern > > object at > > 0x00838700>: it's not found as __main__.match > > > > I'd be grateful if someone could tell me if it is possible > to pickle > > the data structure and what I'm doing wrongly. > > Are you trying to store the MatchObject returned by a call to > a regular > expression object's match() method? If so, it looks like you're > forgetting the parens at the end of "re.compile(y).match". > > > > Erik > No, I haven't forgotten the parentheses. I'd like to pickle the match method of the compiled regular expression. Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From dougz at cs.washington.edu Wed Sep 4 17:24:54 2002 From: dougz at cs.washington.edu (Douglas Zongker) Date: Wed, 4 Sep 2002 21:24:54 GMT Subject: str() of a tuple Message-ID: I'm sure this is a FAQ, but I haven't found a good explanation for one of Python's most irritating behaviors: >>> a = -0.4 >>> repr(a) '-0.40000000000000002' >>> str(a) '-0.4' So far, so good. >>> b = (a,) >>> repr(b) '(-0.40000000000000002,)' >>> str(b) # argggh. '(-0.40000000000000002,)' Why, oh why does the str() of a container use the repr()s of the objects inside? This seems to violate what the docs claim str() does -- "return a nicely printable representation of an object." Would a sane implementation break something? Is there a convenient way to print out a tuple of floats so that the output is actually readable? thanks, dz From steve at ferg.org Wed Sep 11 10:41:29 2002 From: steve at ferg.org (Stephen Ferg) Date: 11 Sep 2002 07:41:29 -0700 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> Message-ID: > I don't > know of any event binding that does a proper job of emulating the > standard behavior of pressing a button. Button(command=...) > is the way to go for this. I think I found out why. At http://www.tcl.tk/man/tcl8.4/TkCmd/button.htm#M6 -- under "Button>Default Bindings" -- I found this : "[3] If mouse button 1 is pressed over a button and later released over the button, the button is invoked. However, if the mouse is not over the button when button 1 is released, then no invocation occurs." I take it that this default binding is what "command" is attached to. So no combination of "bind()" statements (well, no *easily coded* combination of bind() and callback logic) can emulate this behavior. From cnetzer at mail.arc.nasa.gov Thu Sep 26 19:13:08 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Thu, 26 Sep 2002 16:13:08 -0700 Subject: Who knows somefunction? In-Reply-To: <00d701c265a5$053d0710$df7e4e18@brianspiv1700> References: <00d701c265a5$053d0710$df7e4e18@brianspiv1700> Message-ID: <200209262313.QAA18247@mail.arc.nasa.gov> On Thursday 26 September 2002 14:38, Brian Quinlan wrote: > Nope. You might want to consider creating your own dictionary to map > ids to the objects that you are interested in. That got me thinking about whether there is an easy (and robust) way to built a dictionary of all the object-id:object pairs in the current environment. The following is some dumb code to start with. Does anyone know of a (non-ridiculous) way to improve it, out of curiosity? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def add_ids_to_dict( l, d ): all_previously_added = 1 # Add all objects to dict, unless already there for o in l: if not d.has_key( id( o ) ): d[ id( o ) ] = o # Adding a new object means they weren't already there all_previously_added = 0 # Give up if all objects in list were already in dict, otherwise # recurse on all objects in the list if not all_previously_added: for o in l: if hasattr( o, '__dict__' ): add_ids_to_dict( o.__dict__.keys(), d ) add_ids_to_dict( o.__dict__.values(), d ) else: add_ids_to_dict( dir( o ), d ) return if __name__ == '__main__': objects_dict = {} add_ids_to_dict( globals(), objects_dict ) print objects_dict print len( objects_dict.keys() ) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Chad Netzer cnetzer at mail.arc.nasa.gov From peter at engcorp.com Tue Sep 3 08:11:49 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 03 Sep 2002 08:11:49 -0400 Subject: RedHat 7.3 and Python2.2.1 References: Message-ID: <3d74a6e8@news.sentex.net> Kow Kuroda wrote: > > As a last thought, doesn't Red Hat have different versions of the 7.3 > distribution? Maybe you installed a beta? I'm pretty sure there's only one release version to date. I could be wrong. The one I installed I took from their web site just two weeks ago. uname says it's version: 2.4.18-3 #1 Thu Apr 18 07:37:53 EDT 2002 i686 and /etc/redhat-release says "release 7.3 (Valhalla)" Oh well, there's no telling with software. :) -Peter From kennethg at pd.jaring.my Fri Sep 20 12:10:28 2002 From: kennethg at pd.jaring.my (Kenneth Gomez) Date: Fri, 20 Sep 2002 16:10:28 GMT Subject: Local Python Server Installation Message-ID: <3d8b47c6.277669@news.jaring.my> Dear Group, I would like to know wich software to install if I would like to learn to use Python as a web development tool? I have installed Python 2.2.1 and Apache but I belive I would need a Python Server Program to enable Apache to render .py files, am I right? Could you kindly advise me? I am running Windows Me. Thank you. Regards, Kenneth. Cheers, Kenneth Gomez. From loewis at informatik.hu-berlin.de Sun Sep 15 14:00:27 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 15 Sep 2002 20:00:27 +0200 Subject: file mode attributes... References: Message-ID: "Bjorn Pettersen" writes: > I was wondering if this was the best way of implmenting these functions > (windows)? Yes. > It seems rather round-about, especially since the stat attributes I'm > using aren't even mentioned in the manual... On Unix, you'd normally add S_IRGRP|S_IROTH as well. Permissions, on Unix, are really a bitmap thing, so manipulating them takes place most naturally using bitmap operations. Notice that, on WNT/2k/XP, you might also need to modify the access control list to give users permissions, especially if the files are on NTFS. Access and modification of the ACL is not supported in standard Python. Regards, Martin From franke at ableton.com Mon Sep 2 11:30:48 2002 From: franke at ableton.com (Stefan Franke) Date: Mon, 02 Sep 2002 17:30:48 +0200 Subject: How to parse over a Python expr? References: <8sjvmugochmuvo4fnfaelq4m59plj6lg0r@4ax.com> <3D6FD585.111E32AE@alcyone.com> <3D7002C4.22DD2AB3@alcyone.com> Message-ID: On Fri, 30 Aug 2002 16:41:56 -0700, Erik Max Francis wrote: >Hmm, you're right. I didn't take into account the corner case where a >triple-quoted string contains single-quoted strings. Thanks for >catching that. (Fortunately, it's a rare occurrence that has certainly >never happened in the field -- you'd have to do a triple-quoted string, >then a single quoted one, _then_ an unbalanced close parenthesis.) Are you sure? I think a TQS with a single quote inside would be sufficient to miss the right TQS end: '''That's all''' These a 7 single quotes. Parsed as single-quote strings, the last one opens a string until EOF. From martin at v.loewis.de Thu Sep 12 02:51:57 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 12 Sep 2002 08:51:57 +0200 Subject: how can i make a binary executable program with a python2's script References: Message-ID: jingguoming at yahoo.com.cn (jgm2163) writes: > how can i make a binary executable program with a python2's script The easiest way is to put #! /usr/bin/env python2 into the first line of script.py, then do chmod +x script.py HTH, Martin From loewis at informatik.hu-berlin.de Fri Sep 20 16:30:14 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 20 Sep 2002 22:30:14 +0200 Subject: Python Compiling References: Message-ID: "Terje Johan Abrahamsen" writes: > Could someone write a compiler and get Python to be a compiled > language like C? Yes; there have been a few demonstrations that this is possible. > Is it not possible to write a complete compiler like the C compiler for > Python? Or is it just that nobody has done it? It has been done, see John Aycock's IPC7 paper (Converting Python Virtual Machine Code to C) for an example, and Jonathan Riehl's IPC7 paper (PyFront: Conversion of Python to C Extension Modules) for another. > Or must the language be constructed differently? To merely produce a complete "machine-code" binary, no, with Johnathan's technique. The question is: why do you want to have a compiler? Using it is much more difficult than an interpreter, and more time-consuming during development of an application. People often expect significant speed increases from compilation, but it turns out that those don't materialize. The reason for that is that any compiler would need to maintain the semantics of the Python language, which means that certain optimizations that a C compiler does for C code are not possible in Python, since, at compile time, it is uncertain whether the prerequisites for that optimization are met. HTH, Martin From jim at interet.com Mon Sep 30 09:31:27 2002 From: jim at interet.com (James C. Ahlstrom) Date: Mon, 30 Sep 2002 09:31:27 -0400 Subject: zlib needs the python15.dll on python22 ??? References: Message-ID: <3D98522F.8080508@interet.com> Ralf Claus wrote: > Hello NG, > by importing the zlib module on python 2.2 (windows) > i get a popup that means "python15.dll not found in path > //winnt/system32/......and so on... > > On that computer, there was never installed python 1.5 !? Each Python release has a new version of the Python interpreter in the PythonXX.dll. Your Python 2.2 is using Python22.dll, but you have an old version of zlib which was linked using Python15.dll. You need to find the old zlib and remove it. Then find the new zlib.pyd that uses Python22.dll and install it. Jim Ahlstrom From Padraig at Linux.ie Fri Sep 6 07:59:33 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Fri, 06 Sep 2002 11:59:33 GMT Subject: tree data structure Message-ID: Hi, I've a graph like stucture represented by a list of tuples: [(L0,S2), (S2,S0), (S2,S1), (S1,Q2), (S0,Q1), (S2,S3)] And would like to convert it to a tree structure like: S0 - Q1 / L0 - S2 - S3 \ S1 - Q2 Any tips appreciated. Thanks, P?draig. From mgerrans at mindspring.com Thu Sep 19 02:06:12 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Wed, 18 Sep 2002 23:06:12 -0700 Subject: Larry Wall's comment on python... References: Message-ID: I think "the pound-end operator" is the technical term (I'll have to defer to Guido on that). One of the niftiest things about Python is you never have to argue about whether you should put your curlies in the wrong place, like this: void foo() { //... } ...or whether you should place them correctly, like this: void foo() { //... } It saves the world from a lot of unnecessary creation and release of hot air (so Python has probably done more to help reduce the greenhouse effect than any other software technology!). ;-) From jwbaxter at spamcop.net Thu Sep 26 20:25:46 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Thu, 26 Sep 2002 17:25:46 -0700 Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> Message-ID: In article <525eaba.0209260956.72bf6786 at posting.google.com>, pknotz at sandia.gov (Pat Notz) wrote: > Is there a short (one or two syllable) pronounciation for "__" (double > underscore). Unfortunately, we can never have the definitive answer, since Victor Borge is no longer with us. (His answer would have been unspellable, of course.) --John From dsavitsk at e-coli.net Tue Sep 3 12:59:12 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Tue, 03 Sep 2002 16:59:12 GMT Subject: PIDDLE install problems Message-ID: I am trying to install PIDDLE (Win2k, 2.1.3 ). I downloaded the recent .zip file, unzipped it to C:\piddle-1.0.15, cd'd to that directory, typed "python setup.py install" and received the following error. ... copying src\piddle\python.gif -> C:\Python\piddle Traceback (most recent call last): File "setup.py", line 28, in ? packages = ['piddle', 'piddle.piddleGTK', 'piddle.piddleSVG', 'piddle.piddle TK2'] ) File "C:\Python\lib\distutils\core.py", line 138, in setup dist.run_commands() File "C:\Python\lib\distutils\dist.py", line 899, in run_commands self.run_command(cmd) File "C:\Python\lib\distutils\dist.py", line 919, in run_command cmd_obj.run() File "C:\Python\lib\distutils\command\install.py", line 484, in run self.run_command(cmd_name) File "C:\Python\lib\distutils\cmd.py", line 328, in run_command self.distribution.run_command(command) File "C:\Python\lib\distutils\dist.py", line 919, in run_command cmd_obj.run() File "C:\Python\lib\distutils\command\install_data.py", line 60, in run dir = convert_path(f[0]) File "C:\Python\lib\distutils\util.py", line 86, in convert_path if pathname[0] == '/': IndexError: string index out of range is this unusual (the same happened w/ 1.0.14), and does anyone know a way to get around this, or why it is happening? thanks, -doug From gerhard.haering at opus-gmbh.net Thu Sep 5 05:51:51 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 5 Sep 2002 09:51:51 GMT Subject: linking embedded python References: <3D7719A9.8050804@ntlworld.nospam.com> Message-ID: Keith S. wrote: > Hi, > > This might be a dumb question, but how does one link > a C++ application in Unix with embedded python? > [...] However, when I try and link, I get errors like: > > Undefined first referenced > symbol in file > dlsym You need to link against additional libraries. To find out which ones, doing a ldd (or whatever the SunOS equivalent of it is) on the python executable should tell you. Does this work for you, too?: from distutils.sysconfig import get_config_var print get_config_var("LIBS") + " " + get_config_var("SYSLIBS") It seems to work for some people, but not for everybody. -- Gerhard From lpgray at uop.com Tue Sep 17 17:05:54 2002 From: lpgray at uop.com (Lee Gray) Date: 17 Sep 2002 14:05:54 -0700 Subject: Python GUI app to impress the boss? Message-ID: <96904b50.0209171305.6d65f574@posting.google.com> I'm a fairly new programmer with experience in ASP/VBScript/DHTML. Other than small utilities, so far I've mostly written ASP apps to talk to an Oracle database on HP/UX, with Windows NT/2000 clients, and I've done maintenance work on VB and Oracle Forms apps. We're currently looking at .Net, and I'm not very impressed, for a variety of reasons. A little research makes me feel that either Java or Python would be a good alternative, and given my level of experience, I'd much prefer Python over Java. I *think* I could actually get up to speed faster with Python than with VB and ASP.Net, in spite of my ASP/VBS experience. My boss is pretty open-minded, but also needs to see something working to be convinced Python is even a viable platform (he had never heard of it). Otherwise, .Net is a given, whether it's any good or not, since corporate is MS all the way. Can someone point me to a good Python GUI app to demonstrate (other than IDLE)? It may very well be that .Net is best for me/us, but from what I've seen of Python, I *really* like the language and I'd at least like to see a good demonstration of a full-blown app before ruling it out. (Something along the lines of what I mentioned above would be ideal, but not a necessity.) Thanks! Lee Gray From usenet at thinkspot.net Tue Sep 17 21:11:51 2002 From: usenet at thinkspot.net (Sheila King) Date: Tue, 17 Sep 2002 18:11:51 -0700 Subject: timeoutsocket module help Message-ID: OK, I'm doing DNS lookups in a script I've written, to determine whether certain IP addresses are listed in DNS BL lists (for blocking spammers). Have been using the code I've written for a long time now (months) without significant problems. However, someone has made the point to me, that my code should technically have a default timeout on the socket that tries to do the DNS lookup. And they are right, so I'm trying to modify my code. So, I'm using Tim O'Malley's timeoutsocket module, or trying to. But I am not having any success with this. In the following C&P from an interactive session, it took 6 or 7 seconds to return the socket error, which is the result I would expect in the case that the host name is not in the DNS list (and in this case it is not, so this is a correct result). The problem is, that I set the default time out (I thought???) to 0.02 seconds, but the lookup went waaaayyyy past that and basically seemed to ignore the instruction. >>> import sys >>> import socket >>> sys.path.append(r'j:\web\thinkspotwebsite\xthinkspot\emailfilter_test') >>> import timeoutsocket >>> timeoutsocket.setDefaultSocketTimeout(0.02) >>> socket.gethostbyname('226.200.3.4.bl.spamcop.net') Traceback (most recent call last): File "", line 1, in ? socket.gethostbyname('226.200.3.4.bl.spamcop.net') gaierror: (7, 'getaddrinfo failed') >>> Now, I will note, that the comments in the timeoutsocket module indicate that it works for TCP connections, and I'm not sure that TCP is being used in the gethostbyname function, as it is my understanding that DNS should usually be done by UDP instead. So, maybe in this case, using O'Malley's timeoutsocket module is totally inappropriate and won't work. In any case, I'm hoping to get some clues here. Thanks, -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From claird at starbase.neosoft.com Thu Sep 19 09:06:45 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 19 Sep 2002 08:06:45 -0500 Subject: shared mem & semaphores module References: Message-ID: In article , Jeff Davis wrote: >I found a module online by "INRIA" (I don't know who that is) that seems to >wrap the C functions for shared memory management and semaphores. . . . French National Institute for Computing and Automation . As dense with the usual academic injustices as one might expect, but filled with interesting people, many of whom you've probably bumped into already. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From mwright at pro-ns.net Fri Sep 20 14:19:15 2002 From: mwright at pro-ns.net (Mark Wright) Date: 20 Sep 2002 11:19:15 -0700 Subject: Why does Tkinter do this? Message-ID: I'm trying to create a resizeable Label with an image. bind()ing to the configure event allows me to resize the image whenever the label is resized, but if I set the size of the image to the new size of the label, it is too big (which produces cascading 'configure' events and a steadily expanding Label). OK, so I try subtracting the borderwidth - which is no good either. But if I subtract the borderwidth *times two*, it works. Can anyone explain this to me? Here's my code: from Tkinter import * from PIL import Image, ImageTk class PhotoLabel(Label): def __init__(self, parent, fileName): self.startImage = Image.open(fileName) self.currentImage = self.startImage self.photo = ImageTk.PhotoImage(self.startImage) Label.__init__(self, image=self.photo, bd=5) self.bind('', self.OnConfigure) def OnConfigure(self, event): if event.type == '22': # why * 2? borderwidth = 2*int(self['borderwidth']) newHeight = max(0, event.height - borderwidth) newWidth = max(0, event.width - borderwidth) self.currentImage = self.startImage.resize((newWidth, newHeight)) self.photo = ImageTk.PhotoImage(self.currentImage) self.configure(image=self.photo) From pereira at cis.upenn.edu Thu Sep 5 04:00:41 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Thu, 05 Sep 2002 04:00:41 -0400 Subject: Why read-only nested scopes? References: Message-ID: On 9/5/02 2:41 AM, in article c0Dd9.6121$e5.1077322 at newsb.telia.net, "Fredrik Lundh" wrote: > David Eppstein wrote: > >> I'm sure there were good reasons for this decision, but it leads to ugly >> workarounds like making each nonlocal variable into a list and assigning >> to x[0] instead of x... > > when you find yourself doing that, it's a sure sign that you're > no longer using python to write python code... There is a reason why this may be puzzling to some. Other languages with non-local lexically scoped variables seem to come in two varieties: those like Pascal or Common Lisp in which all variables name assignable locations, and those like ML or Haskell in which all variables name values, and no bindings be changed. Python is a hybrid, in that variables name values, local and global bindings can be changed dynamically, but bindings established at intermediate scopes cannot. This is not a criticism of Python --- in my experience with languages like Pascal and Common Lisp, assignments to non-local, non-global variables are more confusing than they are worth --- but a suggestion of why it may seem strange at first. -- F From theoryboy at my-deja.com Tue Sep 3 14:12:38 2002 From: theoryboy at my-deja.com (Peter Saffrey) Date: 3 Sep 2002 11:12:38 -0700 Subject: efficient list merging Message-ID: I have two lists of lists of strings which I would like to merge efficiently without repeats. I assume that each list currently contains no repeats. At the moment, I have two possible implementations: for item in list2: if item not in list1: list1.append(item) which is obvious, and I suspect slow and list1hash = {} for item in list1: itemtxt = '%s' % item list1hash[itemtxt] = 1 for item in list2: itemtxt = '%s' % item if not list1hash.has_key(itemtxt) list1hash.append(item) which I thought would be quicker because it uses a hash, but it doesn't seem to be from my crude tests. Maybe it's the text conversion which is slowing it down - the strings stored in the inner lists are quite long (about 60 characters, and each inner list has up to 8 items) is there a way I can index the hash by the address of the lists? I converted to a string just as a "this is the first thing I can think of" approach. Or is there a better way? Thanks, Peter From remi at cherrypy.org Mon Sep 2 13:40:06 2002 From: remi at cherrypy.org (Remi Delon) Date: Mon, 2 Sep 2002 19:40:06 +0200 Subject: [ANN] CherryPy-0.6 released (SSL support) Message-ID: We're pleased to announce the release of CherryPy-0.6. This release adds SSL support to CherryPy (based on PyOpenSSL). Many thanks to Martin Sj?gren for his PyOpenSSL package and to Mark Wormgoor for his contribution to the CherryPy SSL code. ------------------------------------------ About CherryPy: CherryPy is a Python-based tool for developing dynamic websites. It uses many powerful concepts together, which makes it unique in its approach to website development. CherryPy sits between an application server and a compiler. You write source files, compile them with CherryPy and CherryPy generates an executable containing everything to run the website (including an HTTP server). Key properties/features of CherryPy are: - Based exclusively on Python (runs everywhere Python runs) - Delivers fast, robust, and scalable websites - Developers can use OOP as well as AOP (Aspect Oriented Programming) concepts to develop websites - True separation of content and presentation - Simple but powerful templating language - "HTML editor safe" templating language (templates can go back and forth between designers and developers) - Powerful standard libraries to make your life easy Other properties/features are: - Can be linked to many databases (Oracle, Sybase, MySql, PostgreSql, ...) - Can run behind another webserver (Apache, ...) - Easy clustering and load-balancing set up for high-traffic websites - Built-in caching capability - SSL support Remi. http://www.cherrypy.org From michaels at one.net Wed Sep 11 22:17:05 2002 From: michaels at one.net (Michael Schneider) Date: Wed, 11 Sep 2002 22:17:05 -0400 Subject: iterators and generators, is this the Python Way??? Message-ID: <3D7FF921.2040305@one.net> Hello All. I just updated my python to 2.2 and noticed that generators, and iterators were in there. I often parse through many files (one at a time), and wanted the speed of read, and the convience of for x in myGen: The code below works just fine, could you review this code against the intent of iterators and generators. Thanks, Mike ------------------------------------------------------------------------------------------------ # Goal: # # Process files quickly, by reading the file in to memory in one blast, # the adding iterator behavior # # # Michael Schneider from __future__ import generators import sys import os from stat import * class FastFile: def __init__(self, filename): """ Read in entire file into memory""" f = open(filename, 'r') fileContents = f.read(); self.lines = fileContents.split('\n') f.close() def __iter__(self): return self.fastFileGen() def fastFileGen(self): for line in self.lines: yield line # usage ..... try: myFile = FastFile(filename) except IOError, msg: print, filename , " could not open " return 1 # Process each line in the file for line in myFile: fixline(line) From wganz at imacs.com Thu Sep 5 12:17:39 2002 From: wganz at imacs.com (Ganz, Will) Date: Thu, 5 Sep 2002 11:17:39 -0500 Subject: What database should I use Message-ID: I grant that FoxPro is still a formidable competitor in the marketplace but given the size that the original poster stated of 2K-3k records; the 2gig Access limitation shouldn't come into play. In this instance, Visual FoxPro would be like using a supersonic fighter jet as a crop duster. 8-) -----Original Message----- From: Ron Darling [mailto:rond at ixsys.com] Sent: Thursday, September 05, 2002 10:30 AM To: Sathish Chandrasekaran (S); printers at sendme.cz; python-list at python.org; tutor at python.org; activepython at listserv.ActiveState.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: RE: What database should I use >> (though it's it considered obsolete now-a-days). This is only a consideration for the uni-formed or those that have never really used it. MS is still dumping lots of money into it. Just shipped v7.0 will be going into Beta with 8.0 in a couple of months. Amazing String capabilties. As a matter of fact there is now a VFP style .net class that moves a lot of the wonderful commands internal to VFP to .NET. I think the Fox Dev team created. Cursor Technology, Rushmore Speed and many other things have moved there way into not only Access but SQL Server and ADO. Due to the fact that each part of a table is its own file. .DBF is the table. .FPT is the Memo field .CDX is the index. The file size limitation of the OS of 2 gig is at the individual file level. In Access everything is stored in the same file (you could break up but not really meant to) so the 2 gig file size is limited to the app and data which is more than likely in the same file. I have dealt with lots of situations where the .DBF was 1.8 gig, the index was 1.2 gig and the FPT was another 1+ gig size. Indexes are stored in a .CDX file. A .CDX file can have as many as 255 indexes (take into account 2 gig file size). Each open table can have 10 open CDX's so you can have 2550 indexes on a table. Very Robust SQL pass Through for back end databases. There is nothing out there as fast as VFP for pure raw speed. SQL 2000 gets close but not quite there, the advantage to SQL as far speed goes is it does not bog down under load. Load means 25 + heavy users. As far as speed goes I have seen the return of queries on tables as large as 21 million records within seconds and that was pulling data across a 10 meg network with Foxpro For DOS. United We Stand (remember Ross Perot) member/prospect database. Sounds a little dated but the point is its been that way in Fox for a long time. Fox and VFP managed/tracked the military assets to the Persian Gulf and is till in use. Manages the flow of info for Chunnel. It is far more prevalent than most realize. Very good OOP. It seems that VFP is becoming known for the best language that can really implement the "Abstract Factory Pattern" Very good interface. Rich Native Controls (No OCX) and does very well with OCX's. Easy Distribution. (Drop a couple of DLLS into system directory not reg) Rich Debugger. Can access any data ODBC, ADO or ADO.Net can access. Internal XML. Select Result set from SQL into a local cursor then use CURSORTOXML(). With the XMLTOCCURSOR() and CURSORTOXML() commands it is very easy to build thin wire apps. Bind the interface to the cursor. I can try any and all commands from the command prompt and even from within a debugging suspend. Pretty much interrogate the entire system at hand very easily from a suspend. Many options for hanging VFP behind IIS and ISAPI. You can create com objects and run behind other languages even from within SQL Server or visa versa. One of the most robust SOUNDEX/Fuzzy Search add-ons available with the PHDbase Library. You can index memo fields and do 2 - 3 second searches on huge amounts of memo data. Best Table Repair Libraries that I am aware of are available. Error trapping has been far superior to VB and a lot of languages since the Fox 2.0 days (1992). Last but not least http://www.universalthread.com. Great support from all over the world. obsolete...hmmmmm maybe lack of exposure or conflicting marketing problems with MS owning Access, SQL and Fox but certainly not obsolete. -----Original Message----- From: activepython-admin at listserv.ActiveState.com [mailto:activepython-admin at listserv.ActiveState.com]On Behalf Of Sathish Chandrasekaran (S) Sent: Thursday, September 05, 2002 9:24 AM To: printers at sendme.cz; python-list at python.org; tutor at python.org; activepython at listserv.activestate.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: RE: What database should I use In that case MS-access will be better on the size issue. But on the other hand if u want ur application to be flexible and ease of use I would rather suggest FoxPro (though it's it considered obsolete now-a-days). Here Is A Test To Know Whether The Mission Of Your Life Is Over . If You Are Alive It Isn't . Sathish C Infra-Amdocs -----Original Message----- From: A [mailto:printers at sendme.cz] Sent: 05 September 2002 15:21 To: python-list at python.org; tutor at python.org; activepython at listserv.ActiveState.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: What database should I use Hello, I am going to program a small application (in Python and wxPython) which consists about 2000 - 3000 records . Can you please recommend which database is the best for that. I use Windows. Maybe MS Access or FoxPro or MySQL or better? I want to keep the program as small as possible. Thanks Ladislav _______________________________________________ ActivePython mailing list ActivePython at listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython _______________________________________________ ActivePython mailing list ActivePython at listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython _______________________________________________ ActivePython mailing list ActivePython at listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython From paul at boddie.net Fri Sep 20 11:51:15 2002 From: paul at boddie.net (Paul Boddie) Date: 20 Sep 2002 08:51:15 -0700 Subject: How to access XML passed from an XForm References: Message-ID: <23891c90.0209200751.335a84f2@posting.google.com> Jeremy Rew wrote in message news:... > > I have an XForm that passes a serialised XML document to a URI ( a python > script). Im not exactly sure of the internal representation of what it > sends, but I am having trouble just finding out how to access the XML from > within the python script. I just need to know if theres a way to store the > XML in a string or find out where I can access it from, as I already know > how to process/manipulate the XML once I can get at it. Any ideas (Im > rather new to python)? I imagine that what you want to know is documented here: http://www.w3.org/TR/2002/WD-xforms-20020821/slice11.html I suspect that you can handle the incoming data in a similar way to HTML form "file upload" information, but at the most basic level, you're most likely to be getting a generic HTTP request with certain parts of the message body containing the information you require. I wonder if some of the work around this hasn't already been done in certain XML-RPC or SOAP implementations... Paul From aahz at pythoncraft.com Tue Sep 17 00:52:09 2002 From: aahz at pythoncraft.com (Aahz) Date: 17 Sep 2002 00:52:09 -0400 Subject: Source code References: <3d868ccc$1@news.sentex.net> Message-ID: In article <3d868ccc$1 at news.sentex.net>, Peter Hansen wrote: > >Copyright is actually a passive thing now, as opposed to active. >That is, you don't have "to copyright your work", because unless >you explicitly disclaim the copyright, you automatically get it. True. >As I recall, this was not always the case in at least the U.S., but >has been the case for a number of years now. In other words, if you >don't write something like "placed in the public domain" then you still >have copyright on it and could take steps in courts of law to recover >lost income if someone else attempts to profit from your work without >permission. > >There *are* steps you can take that are considered by some to increase >the strength of the copyright (registering it officially and so forth), >but others believe this is mostly a waste of time. False (mostly). It's not the strength of the copyright, it's the amount of money that one can gain from a copyright infringement lawsuit. Registering copyright permits punitive damages; unregistered copyright permits only "actual" damages, and you have to prove every penny of it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From aahz at pythoncraft.com Sun Sep 29 11:14:13 2002 From: aahz at pythoncraft.com (Aahz) Date: 29 Sep 2002 11:14:13 -0400 Subject: A simpler singleton pattern? References: Message-ID: In article , lee lion wrote: > > singleton pattern is a way to provide one and only one object of a >particular type. There are many ways to implement a singleton pattern, is >the below one? Dunno, but the simplest way to create a singleton is to use a class (*not* an instance) or a module and set attributes on the class/module. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From bloke at ii.net Fri Sep 27 10:37:19 2002 From: bloke at ii.net (Rob Hall) Date: Fri, 27 Sep 2002 22:37:19 +0800 Subject: Problem with ClientCookie Message-ID: <3d946d0f$0$10364@echo-01.iinet.net.au> I am trying to use ClientCookie to access a HTTPS website under Win98. I have installed the W32 SSL wrappers. The code I have is similar to as follows (have removed authorisation detail): import urllib import ClientCookie if __name__ == '__main__': urllib.URLopener.version = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)' print 'Logging on...' request = urllib2.Request('https://www.quicktrade.com.au/cgi-bin/login?USERNAME=myUser Name&PASSWORD=myPassword') result = ClientCookie.urlopen(request) I have set HTTP_DEBUG = 1 in _ClientCookie.py I get the following response... Logging on... Page requested... send: 'GET /cgi-bin/login?USERNAME=myUserName&PASSWORD=myPassword HTTP/1.0\r\n' send: 'Host: www.quicktrade.com.au\r\n' send: 'User-agent: Python-urllib/2.0a1\r\n' send: '\r\n' reply: 'HTTP/1.1 200 OK\r\n' header: Date: Fri, 27 Sep 2002 14:21:31 GMT header: Server: Stronghold/2.4.2 Apache/1.3.6 C2NetEU/2410 (Unix) header: set-cookie: key=Kpfz5sbkkPrwsM7eng5ihtfuKq6sAlSdwTXhn/jUiEOSOCYJAC5r/Vlq+5uS9wqkpHJzOWHi m4v+^Va7SldrYP9Vqea2vDKtZWnOiP7Ff5ckrrM61DDM+tIGO44jUyKPt2yof5Uz7lvUu0ErVqJk DWAYX^7x66TxqZ2esB823pOue6zNxcmhY1SiS7pPTd5w3X/5ncX3njMZs_^; Path=/; secure header: set-cookie: acct=myUserName STGBNET; Path=/; secure header: set-cookie: level=1; Path=/; Domain=.quicktrade.com.au; secure header: set-cookie: ID=1802009989; Path=/; Domain=.quicktrade.com.au; secure header: set-cookie: w1=None; Path=/; secure header: P3P: CP="NON DSP ADMa OUR IND UNI FIN" header: Connection: close header: Content-Type: text/html Traceback (most recent call last): File "C:\WINDOWS\Desktop\backup\uni\project\development\htmlProcessor\htmlProcess or.py", line 22, in ? result = ClientCookie.urlopen(request) File "C:\PYTHON22\lib\site-packages\ClientCookie\_ClientCookie.py", line 1387, in urlopen return _opener.open(url, data) File "C:\PYTHON22\lib\urllib2.py", line 322, in open '_open', req) File "C:\PYTHON22\lib\urllib2.py", line 301, in _call_chain result = func(*args) File "C:\PYTHON22\lib\site-packages\ClientCookie\_ClientCookie.py", line 1334, in https_open return self.do_open(httplib.HTTPS, req) File "C:\PYTHON22\lib\site-packages\ClientCookie\_ClientCookie.py", line 1319, in do_open self.c.extract_cookies(result, req, redirect=redirect) File "C:\PYTHON22\lib\site-packages\ClientCookie\_ClientCookie.py", line 627, in extract_cookies k, v = re.split(r"\s*=\s*", param, 1) ValueError: unpack list of wrong size I can't find anything to help me debug this. Is the error because the web server is returning more than one cookie? or is it just returning a bad format? Any help is greatly appreciated. Rob From rob at zoism.org Mon Sep 16 20:39:30 2002 From: rob at zoism.org (Rob Brown-Bayliss) Date: 17 Sep 2002 12:39:30 +1200 Subject: Socket server and threads In-Reply-To: <1032217212.2735.21.camel@caspian.everglade> References: <1032217212.2735.21.camel@caspian.everglade> Message-ID: <1032223169.2736.24.camel@caspian.everglade> Hi, I am trying to write an app. it Has a gui, and I am using xmlrpc via socket server to communicate with other apps on other machines. I currently have the socket server running as a thread like so: args = (('', 48002), BHH_Communication.BHH_DMHandler, self) self.server = None self.tserver = thread.start_new_thread(BHH_Communication.BHH_TCPServer, args) while (self.server == None): pass where BHH_TPCServer is: class BHH_TCPServer(SocketServer.TCPServer): def __init__(self, server_address, RequestHandlerClass, parent): SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass) self.BHH = parent self.BHH.server = self # so handlers have access to # GUI app self.in_comms = [] self.in_comms.append(self) self.out_comms = [] while 1: rtoread, rtowrite, err = select.select(self.in_comms , self.out_comms, [], 5.0) if (len(rtoread) != 0): rtoread[0].handle_request() So with this my handler class can call functions in the main app via self.server.BHH.some_function() My question is what do I need to do to make sure it is safe, what happens if the thread and the parent app are trying to call the same function at the same time? What about if two or more request handlers are running and want the same function at the same time (via a threaded TCP handler class? -- * * Rob Brown-Bayliss * From erikprice at mac.com Tue Sep 10 08:41:45 2002 From: erikprice at mac.com (Erik Price) Date: Tue, 10 Sep 2002 08:41:45 -0400 Subject: Pickle problem In-Reply-To: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D0E@hendrix.empolisuk.com> Message-ID: On Tuesday, September 10, 2002, at 06:13 AM, Harvey Thomas wrote: > I'm trying to pickle a complicated data structure which includes a > dictionary whose entries are created by (simplified): > > a[x] = re.compile(y).match > > The pickle fails, however, with the error: > > PicklingError: Can't pickle object at > 0x00838700>: it's not found as __main__.match > > I'd be grateful if someone could tell me if it is possible to pickle > the data structure and what I'm doing wrongly. Are you trying to store the MatchObject returned by a call to a regular expression object's match() method? If so, it looks like you're forgetting the parens at the end of "re.compile(y).match". Erik -- Erik Price (zombies roam) email: erikprice at mac.com jabber: erikprice at jabber.org From kodokuchef at yahoo.com Fri Sep 20 01:37:12 2002 From: kodokuchef at yahoo.com (akirasugiura) Date: 19 Sep 2002 22:37:12 -0700 Subject: newbie seeks advise. Message-ID: <77c84db2.0209192137.51167ebb@posting.google.com> Hi, I've been learning python for about a month. I had no prior knowledge of programming. My question is, I have a tuple which is, data = (69, 40, 74, 41, 56, 57, 38, 58, 26, 55). How I can make a function that picks up a largest number from this "data" tuple. If "data" was a 'List' I would be able to use "sort" but since sort doesn't work with tuple. I am stuck here. Thanks in advance Sincerely, From robin at jessikat.fsnet.co.uk Wed Sep 18 15:13:12 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 18 Sep 2002 20:13:12 +0100 Subject: cgi binary upload Message-ID: I know there's a lot of skilled people using python so I thought I'd ask how one can get an HTML page to do a proper binary upload using the form tag. We want to do this for PDF documents, but it seems as though IE/Mozilla/Netscape clients insist on putting Content-Type: data/pdf or similar headers into the multi part file section and the files have their line endings corrupted. On the receiving side using cgi.py we are certainly seeing some filetypes OK eg zip files, but surely we should be able to fix this more reliably. I should note that experimentally renaming the file as xxx.xpdf made no difference as the mime type was being correctly determined by the browser. -- Robin Becker From jtk at yahoo.com Mon Sep 30 16:15:17 2002 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Mon, 30 Sep 2002 16:15:17 -0400 Subject: Using __import__ to access a local module attribute Message-ID: I'm trying to use __import__ to dynamically import a module in a customized Zope Formulator python product, and thereby access a singleton instance attribute of the primary class wtih a call to getattr. I can get it to work with hardcoding the module name, but I don't see what I'm missing when I try to use __import__. The code below is just an early version of a means to an end, and I'm wide open to better ways accessing the instance attribute. Metaprogramming babysteps, I guess... The MyExtClassInstance attribute in MyExtModule.py that I'm trying to access is defined like this: MyExtClassInstance = MyExtClass() just like the widget and validator formulator classes are. MyExtModule.py is in the same product directory with my customized formulator filesystem product, call it 'FormulatorMyExt'. --- FieldRegistry.py ------------------------------------------------------ def initializeFieldForm(field_class, components=('widget','validator')): """ """ from Form import BasicForm from DummyField import fields form = BasicForm() override_form = BasicForm() tales_form = BasicForm() for component in components: if component not in ('widget','validator'): # when the seq is ('widget','validator','myExtModule') import MyExtModule # This works ... # but what I intend is a working form of either of these next lines.... # __import__(component.capitalize(), globals(), locals()) #__import__(getattr(Products.FormulatorMyExt,component.capitalize()), globals(), locals()) setattr(field_class, component, getattr(MyExtModule,component.capitalize()+'Instance')) I get errors like: NameError: global name 'Layout' is not defined (in the first case, and) NameError: global name 'Products' is not defined (in the second case) Does anyone see my mistakes here? And obviously, I want to get that last line of hardcoded MyExtModule name out of there, but it obfuscated the problem to add that here. I can do it with a getattr call, I think, contingent on solving the former problem. Thanks for any help with using __import__, including the from list, or suggestion of a completely different way to do it as appropriate. From mail at peterbe.com Thu Sep 26 18:44:07 2002 From: mail at peterbe.com (Peter Bengtsson) Date: 26 Sep 2002 15:44:07 -0700 Subject: Integrate with Flash MX Message-ID: <322e5959.0209261444.797a936e@posting.google.com> I want to use Flash MX to build a GUI for use on the desktop on windows, not embedded in a webpage. ActionScripts don't do it for me so I want to use Python for the business logic. Is there some way to enable this connection? Maybe this is more of a Flash question. I suppose my python module could spit and swallow XML that the Flash app could pick up, but wouldn't want to use HTTP for that. Anybody got any experience with this? Cheers, Peter From duncan-news at grisby.org Sun Sep 1 18:25:17 2002 From: duncan-news at grisby.org (Duncan Grisby) Date: Sun, 01 Sep 2002 22:25:17 GMT Subject: Python IPC options References: <1030829572.943495@irys.nyx.net> Message-ID: In article , holger krekel wrote: >> Corba 2.2 -> http://www.fnorb.org > >CORBA 2.0 AFAIK. Fnorb is CORBA 2.0, and does not (yet) follow the official standard Python language mapping. omniORBpy is CORBA 2.6, and does follow the standard language mapping: http://omniorb.sourceforge.net/ Cheers, Duncan. (omniORBpy author) -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From duncan at NOSPAMrcp.co.uk Fri Sep 20 04:50:29 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 20 Sep 2002 08:50:29 +0000 (UTC) Subject: Avoiding referencing (was: Python sequences reference - problem?) References: Message-ID: Thorsten Kampe wrote in news:amejvb$55qsi$1 at ID- 77524.news.dfncis.de: > Obviously I did not pass 'foo' "by value" to function 'part' but by > reference and obviously not only local variable 'seq' was modified in > the function but "outer" variable 'foo', too. > > So how to deal with that? > You missed out option number 4: Don't write code that modifies its arguments unless you always want the arguments modified. In general, if you want to modify an argument, but don't want the change reflected back to the caller, make a copy of the argument. If you want the change reflected back to the caller always, then go ahead and modify the argument, but make it clear from the function name that it does that. If you want the function to sometimes modify its argument, then write it so that it never modifies the argument but returns a modified value as a result. Then the caller can decide whether to use that result or EXPLICITLY ignore it. For the specific example you gave, there was no reason to modify the argument, the code is just as simple without either copying or modifying: >>> def part(seq, indices): partition = [] start = 0 for slice in indices: partition.append(seq[start:slice]) start = slice partition.append(seq[start:]) return partition >>> foo = [11, 22, 33, 44, 55, 66, 77] >>> part(foo, [2, 3]) [[11, 22], [33], [44, 55, 66, 77]] >>> foo [11, 22, 33, 44, 55, 66, 77] >>> -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From hwlgw at hotmail.com Sun Sep 29 16:23:55 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 29 Sep 2002 13:23:55 -0700 Subject: Tkinter: bind Alt + mouse click References: Message-ID: [Ulrich Goertz] > I am puzzled why I cannot bind events of the type "Alt" button press plus > mouse click. Those Alt-keycombos are probably catched by a master widget. It could help if you do self.master.unbind('-s') this assumes self is your widget and you have the master widget saved in a .master attribute, as many widgets do in their __init__ constructor. ''' A major, with wonderful force, Called out in Hyde Park for a horse. All the flowers looked round, But no horse could be found; So he just rhododendron, of course. ''' From chris.gonnerman at newcenturycomputers.net Thu Sep 19 23:00:49 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 19 Sep 2002 22:00:49 -0500 Subject: Nokia 3310 SMS Application, done:connecting to serial port(linux/win), done:reading some hex like \x00 . . ., problem:write/send command! noresponse References: <52facf1d.0209190533.3048e62c@posting.google.com> Message-ID: <004701c26051$f13fc160$0101010a@local> ----- Original Message ----- From: "Polerio Babao Jr.II" << hack hack hack >> > Now I've tried sending commands using the Nokia AT Command > which was taken from this link here -> > http://3ton.com/besik/ATNOKIA.pdf > > The problem is, this still gives no response, when I type > ser.write('ATCGMI') or any other command, I get no response. << hack hack hack >> Ah... shouldn't that be: ser.write('ATCGMI\r') ... as in, don't you need the command-line-terminator? Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From gregory.p.green at boeing.com Thu Sep 12 15:14:36 2002 From: gregory.p.green at boeing.com (Greg Green) Date: Thu, 12 Sep 2002 19:14:36 GMT Subject: Extending a C++ App References: <996eade8.0209120912.3a653d7@posting.google.com> Message-ID: Embedding python inside an application can be simple. The basic step is to call Py_Initialize(). After that you can execute python code with the PyRun_* functions. Of course, in practice, there is a lot more to worry about. Threads and the GIL, if you are using a GUI, you have to worry about the event loop, etc. Accessing your c++ object model requires you to wrap them just as if you were going to use the model in a python program. The normal answers are swig, sip, boost and some others. I've used both swig, sip, and writing the wrapper by hand. All will work. Once the api is wrapped, the resulting code is either statically or dynamically linked to your exe. -- Greg Green From pyth at devel.trillke.net Fri Sep 27 16:57:04 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 27 Sep 2002 22:57:04 +0200 Subject: ENOSPC doesn't cause exception? In-Reply-To: <20020927195418.GF5941@unpythonic.net>; from jepler@unpythonic.net on Fri, Sep 27, 2002 at 02:54:19PM -0500 References: <20020927195418.GF5941@unpythonic.net> Message-ID: <20020927225704.S30315@prim.han.de> Jeff Epler wrote: > Can someone tell me why this doesn't cause an exception? > $ python -c print > /dev/full > > (/dev/full is a special device found on at least some kinds of Linux, > which always returns -ENOSPC when written) > > if I use 'strace', I can see that -ENOSPC is returned from write(): > $ strace -e write python -c print > /dev/full > write(1, "\n", 1) = -1 ENOSPC (No space left on device) > > I would expect this to print something like > Traceback (most recent call last): > File "", line 1, in ? > OSError: [Errno 28] No space left on device > > I tested this on Python 1.5.2 and Python 2.3a0 CVS, so it doesn't appear > to be anything new... very interesting. If i have a file which contains: f = open('/dev/full','w') f.write('hallo') f.close() and do python /tmp/q i get the expected behaviour (no space ...). If you leave out 'f.close()' you don't get the exception any more. But even running with 'python -cu print >/dev/full' (stdout is unbuffered) this doesn't throw an exception. hmmm. Wildly guessing, during interpreter shutdown this exception (and possibly others) seem to be ignored?! At least the following code class a: def __del__(self): raise OSError, "hello" a1=a() produces [hpk at cobra /tmp]$ python q Exception exceptions.OSError: in > ignored [hpk at cobra /tmp]$ Couldn't easily find the place in the C-source where this happens, though. regards, holger From support at internetdiscovery.com Mon Sep 30 13:56:48 2002 From: support at internetdiscovery.com (Mike Clarkson) Date: Mon, 30 Sep 2002 17:56:48 GMT Subject: Doc for Tix / Python ? References: <3D9382F9.7040407@novagrid.com> Message-ID: <3d988f49.6335208@nntp.ix.netcom.com> On Thu, 26 Sep 2002 23:58:17 +0200, olivier Ravard wrote: >Hi, > >Is someone know where we can find some documentation >or tutorial about using Tix with Python ? http://www.python.org/doc/current/lib/module-Tix.html and the references contained therein, and the library documentation distributed with Python. >I try to use PanedWindow without succes... What exactly is the problem? Have your tried the demos in the source distribution (Demo/tix). I think there's one that uses PanedWindow. Mike. From martin at v.loewis.de Thu Sep 5 14:46:44 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 05 Sep 2002 20:46:44 +0200 Subject: Why read-only nested scopes? References: Message-ID: bokr at oz.net (Bengt Richter) writes: > How about introducing an optional "degree of globalness" for the > global declaration? E.g., > > x = 1 > def foo(): > x = 2 > def bar(): > x = 3 > def baz(): > global(1) x > x = 4 > > would go outwards 1 nested scope and thus target the x in bar, > rebinding it from 3 to 4. That would work - although I'd claim that some users will find that notation plain ugly. It will also have confusing results: x = 1 def foo(): print x def bar(): global(1) x x = 1 At the moment, the "print x" in foo prints the global x, since there is no assignment to x, and hence there is no local variable foo. With the global statement, you declare that there is a local variable foo::x. As a result, since there is no assignment to foo::x, this would raise an UnboundLocal error. Regards, Martin From r.l.richardson at verizon.net Mon Sep 9 21:33:55 2002 From: r.l.richardson at verizon.net (Rick Richardson) Date: Mon, 9 Sep 2002 18:33:55 -0700 Subject: IDLE In-Reply-To: References: Message-ID: <20020910013604.SLEV16391.out018.verizon.net@there> On Monday 09 September 2002 05:54 pm, you wrote: > Why won't my IDLE work? well. given your amount of included information, I can only assume that either a: Your computer is off. b: You don't have the proper tk libs. c: You don't have python installed. d: Your computer is an atari 2600. e: The planets are misaligned. f: your dog snuck in in the middle of the night and rewrote the IDLE code so it only works when he/she is logged in. Hope that helps. Rick Richardson. From missive at frontiernet.net Thu Sep 26 18:27:48 2002 From: missive at frontiernet.net (Lee Harr) Date: Thu, 26 Sep 2002 22:27:48 -0000 Subject: curses troubles References: Message-ID: > I'm trying to take user entered data input and store it as a var. > > inside an __init__ I have curses set up a window, and display some > options. Then I use: > while 1: > self.k = self.stdscr.ch() > if self.k == ord('G'): do_this() > elif self.k == ord('P'): do_another() > elif self.k == ord('Q'): break > > Now, when running this, if I hit either G or P, the applications closes as if I'd hit Q > Hi; I made a pretty large application which uses curses. The trouble is that it can be tough to debug, since all the screen output is going through curses. What i ended up doing is creating a log function which i can call with various strings and variables and which writes its output to a file... then on another terminal I can just tail that file to see what is going on. So what i would do is create such a function, then log the value of self.k in that loop so you can see exactly what is going on. From aleax at aleax.it Thu Sep 26 09:55:58 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 13:55:58 GMT Subject: comparing all values of a list to regex References: Message-ID: Delaney, Timothy wrote: ... >> num_matches = [ there.match(item) is not None for item in >> alist ].count(1) ... > # Expanded out for clarity - could be one line > matches = map(regexp.match, alist) > matches = filter(None, matches) > matches = len(matches) The list-comprehension equivalent of this would be: matches = len([ item for item in alist if there.match(item) ]) and may indeed be clearer than the .count approach I originally proposed (except that I think that naming the variable matches is ambiguous -- num_matches or numMatches & being preferable). A more concise expression of your approach would of course be: matches = len(filter(there.match, alist)) I don't see exactly what value the call to map adds in your case. > # Find out which list to append to > > match_list = match_all > > if not matches: > match_list = match_none > elif matches == 1: > match_list = match_one > elif matches != len(alist): > match_list = match_some > > match_list.append(alist) Yes, choosing a list first and then appending to the chosen list is nicer, but you cannot do that within the original specs (for all I know the match_some list might grow unbearably large over time, in this case). > Note that I added an additional case - where more than one matched, but > not all. Yep, that's the part that's out of the original specs. The concise equivalent alternative here might be (e.g.): {0:match_none, 1:match_one, len(alist):match_all}.get( matches, match_some).append(alist) or to get back in the original specs: match_list = {0:match_none, 1:match_one, len(alist):match_all}.get(matches) if match_list is not None: match_list.append(alist) Alex From dhein at acm.org Sun Sep 15 16:20:46 2002 From: dhein at acm.org (Coot) Date: 15 Sep 2002 13:20:46 -0700 Subject: Popup menu won't hide on Linux Message-ID: When a popup menu is displayed, I expect that it should goes away when one of the menu items is clicked (button <1>) or when I click anywhere else (such that the focus is no longer on the popup menu). However, on Linux, the latter behavior doesn't happen. The popup remains on top of the main app window and the only way to get rid of it is to click one of its menu command items or close the application. This behavior isn't there on Windows. Can anyone tell me how to solve, or work around, the problem??? Here is some example code you can use to demonstrate this problem for yourself (taken from http://www.pythonware.com/library/tkinter/introduction/x5819-patterns.htm): # menu-example-4.py from Tkinter import * root = Tk() def hello(): print "hello!" # create a popup menu menu = Menu(root, tearoff=0) menu.add_command(label="Undo", command=hello) menu.add_command(label="Redo", command=hello) # create a canvas frame = Frame(root, width=512, height=512) frame.pack() def popup(event): menu.post(event.x_root, event.y_root) # attach popup to canvas frame.bind("", popup) mainloop() From dgallion1 at yahoo.com Wed Sep 18 22:31:57 2002 From: dgallion1 at yahoo.com (darrell) Date: Thu, 19 Sep 2002 02:31:57 GMT Subject: RegEx editors References: Message-ID: import re while 1: buf=eval('"""%s"""'%raw_input("Enter string to search:")) print buf while 1: pat=raw_input("Enter pattern:") if len(pat)==0: break mo=re.search(pat, buf) if mo: print mo.groups() else: print "" ########################################## Enter string to search:now is the \n time for now is the time for Enter pattern:(?s)now(.*?)for (' is the \n time ',) --Darrell Eric Arnold wrote: > Does anybody know of any good graphical regex editors out there? > > Eric From emile at fenx.com Sun Sep 22 13:25:29 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 22 Sep 2002 10:25:29 -0700 Subject: How to get memory usage on Windows? References: Message-ID: GerritM: [snip] > how much memory is used per phase and/or per function. Is there any function > returning this information. I noted that on Unix the resource module gives > access to this kind of information, but I could not find any Windows > alternative. > You could try pslist from the pstools package at www.sysinternals.com to get an idea of total memory in use by process. -- Emile van Sebille emile at fenx.com --------- From erikprice at mac.com Sun Sep 1 11:57:06 2002 From: erikprice at mac.com (Erik Price) Date: Sun, 1 Sep 2002 11:57:06 -0400 Subject: yield keyword reserved Message-ID: <770604FC-BDC3-11D6-8A4A-00039351FE6A@mac.com> I'm sorry if this is an easily answered-question. I have Python2.2 running on my system (it is installed on Darwin by default in Mac OS X 10.2), and am learning about iterators from , but the keyword doesn't appear to be present on my system: Python 2.2 (#1, 07/14/02, 23:25:09) [GCC Apple cpp-precomp 6.14] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> def generate_ints(N): ... for i in range(N): ... yield i :3: Warning: 'yield' will become a reserved keyword in the future File "", line 3 yield i ^ SyntaxError: invalid syntax >>> Is my Python not a true 2.2 release, or do I have something wrong in my syntax? For that matter a recompile wouldn't be so bad since this build doesn't have readline :( Erik -- Erik Price email: erikprice at mac.com jabber: erikprice at jabber.org From mcherm at destiny.com Wed Sep 11 09:45:10 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 11 Sep 2002 09:45:10 -0400 Subject: Multi-threading python References: Message-ID: David Brown wrote: > I've just been reading a little about the GIL and threading in python, and I > have a couple of questions that I hope someone can answer. I'm not an expert, but I'll try. > Am I right in thinking that threading in Python does not use the underlying > OS's threads, but effectively implements its own scheduler? Or does it use > the OS's threads, but uses the GIL to ensure that only one is runable at a > time? It uses the OS's threads, and then uses the GIL to ensure that only one is executing Python bytecodes at a time. However, other threads may be runable... they could be blocked waiting on I/O, or executing some C code from a module that releases the GIL before performing a long-running computation. > On a dual-processor system, does this mean that only one thread of a Python > program can run at a time, even when both CPUs are free, so that two > seperate python interpreter processes are needed to take advantage of the > two CPUs? Yes. > What about when a Python thread is blocked for some other reason, such as > while waiting for a file read - will that block other threads, or will the > waiting thread definitely release the GIL and allow other threads to run? Depends on what it's blocked for. If it's blocked for I/O, then the GIL is released and the other threads will run. I'm not sure what else it would block for that might be a problem. But you could certainly CREATE a problem if you tried... simplest way would be to write C code which ran for a long time WITHOUT releasing the GIL. It would be much more difficult to block things through badly written Python code, since after each bytecode the interpretor can switch to a different thread. > If the GIL does block all threads in this manner, are there any plans to > introduce more fine-grained locking to improve scalability, analagous to > locking in the Linux kernel? No. The general consensus is that eliminating the GIL would be quite difficult and that there's not really all that much to gain. (Most casual users don't have multi-processor systems; serious users of this sort probably use Numeric and/or put the tight loops into C anyhow.) However, if you know someone who's good with this stuff and wants to volunteer, I'm sure they wouldn't turn down working code (unless it introduced other problems). -- Michael Chermside From jp at NOSPAMdemonseed.net Wed Sep 18 12:04:10 2002 From: jp at NOSPAMdemonseed.net (jason petrone) Date: Wed, 18 Sep 2002 16:04:10 +0000 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: Lee Gray wrote: > Can someone point me to a good Python GUI app to demonstrate (other > than IDLE)? You could bring him the Star Wars: Episode II DVD: http://www.python.org/Quotes.html A few other polished programs written in python: Visual Python: http://www.activestate.com/Products/Visual_Python/ PySol: http://www.oberhumer.com/opensource/pysol/ Sketch: http://sketch.sourceforge.net/ Grail: http://grail.sourceforge.net/ Visual Python probably has the prettiest screenshot. Jason From jdavis at empires.org Thu Sep 19 00:26:49 2002 From: jdavis at empires.org (Jeff Davis) Date: Thu, 19 Sep 2002 04:26:49 GMT Subject: Problem with urllib References: Message-ID: I can't reproduce the error either way (interactive or otherwise). Are you use that you're using the same python interpreter version for both? Regards, Jeff Jean-Paul Mi?ville wrote: > I don't understand why with some URL I have got [Errno 57] Socket is not > connected. > > The code is : > > import urllib2 > > page = urllib2.urlopen(' http://www.python.org/doc/NonEnglish.html') > print page.read() > > If I do the same thing with python interactive, I can't reproduce the > error. > > Thanks in advance, > Jean-Paul From stevena at neosynapse.net Sat Sep 7 16:29:15 2002 From: stevena at neosynapse.net (Steven D. Arnold) Date: Sat, 7 Sep 2002 16:29:15 -0400 Subject: Possible bug in Email and Multifile Modules ? Message-ID: <180174913421.20020907162915@neosynapse.net> I'm picking up on a very old thread because I am only now encountering issues related to it. > On Mon, Feb 04, 2002 at 01:01:43AM -0800, Sheila King wrote: >> >>> msg = email.message_from_file(open('virus.txt')) >> Traceback (most recent call last): >> File "", line 1, in ? >> File "E:\PYTHON\PYTHON22\lib\email\__init__.py", line 35, in >> message_from_file >> return _Parser(_class).parse(fp) >> File "E:\PYTHON\PYTHON22\lib\email\Parser.py", line 40, in parse >> self._parsebody(root, fp) >> File "E:\PYTHON\PYTHON22\lib\email\Parser.py", line 116, in _parsebody >> raise Errors.BoundaryError( >> BoundaryError: Couldn't find terminating boundary: >> ====_ABC1234567890DEF_==== >> =============(end interpreter session)================ >> >> Now, it turns out that this message is not well formed. Instead of the >> correct closing boundary at the end of the message, it has a boundary which >> indicates that another part should follow. >> >> > No parts were removed, it's 100% intact. And you're right, it's not >> > well-formed, but that's the whole idea behind it. It tricks Outlook >> > into executing the attachment. >> > But not being well-formed shouldn't break anything... > > GIF viewer should not display EXE-files. PDF viewer should not print > broken PDFs. And email scanner should not scan files that are not emails. > Just drop it on the flor and forget. I disagree. Excellent GIF viewers should do their best to display even broken GIF files. Same goes for PDF, etc. Likewise, an excellent Python email library will do its best to handle and correctly process broken emails. I would say the above represents an unfortunate prima donna attitude which ultimately reduces the utility of Python's libraries. In my application, I'm trying to process a message based on its header, but I can't even get the header information, because instead of trying to intelligently handle a broken MIME message, an exception is raised. Since I have no alternative but to find a way to automatically handle even broken messages, I either have to patch the email module to do what I want or reproduce much of the same logic in my own module. I'd like to patch the email module and submit the patch for inclusion in the standard library. What is the process for this? Any other suggestions or comments would be appreciated as well. -------------------------------------------------------------- Steven D. Arnold Neosynapse stevena at neosynapse.net Managing Partner AIM: abraxan MSN: neosynapse at hotmail.com From op73418 at mail.telepac.pt Thu Sep 26 11:58:44 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Thu, 26 Sep 2002 16:58:44 +0100 Subject: design question Message-ID: <1ha6pukqdqell8f31q1k7rtor2rv5ogjs0@4ax.com> Hi, My problem is the following: I have a module to which I want to build a more useful interface. An example would be a third-party extension module where many of the classes are begging to be dressed in Python's specific protocols (as sequences, mappings, etc.). To make matters even more concrete, suppose that among the classes to be wrapped we have Class1 | | Class2 Where the dashed line means a parent-child relationship. Now what I want is something like Wrapper1 | | Wrapper2 where Wrapper1 (Wrapper2) wraps Class1(Class2) and the inheritance reltionships between the several wrappers mirror those of the classes they wrap -- but as I said, the protocol that the wrappers have can be substantially different from the classes they wrap. Leaving aside the question of the usefulness of doing all this, I would like to ask how would you proceed? Making Wrapper derive from Class is stupid since their protocols can differ widely and I would end up with lots of diamonds in the inheritance graph. On the other hand I could just do: class Wrapper1(object) def __init__(self, ): self.__wrap = Class1() But then if I did the same with Wrapper2, it would be at least quirky since it inherits from Wrapper1 but it wraps Class1 I know I am being a little vague in my question, but does anyone have any ideas? Open-source code where this "same problem" has been tackled? With my best regards, Gon?alo Rodrigues From gerson.kurz at t-online.de Sat Sep 28 03:28:16 2002 From: gerson.kurz at t-online.de (Gerson Kurz) Date: Sat, 28 Sep 2002 07:28:16 GMT Subject: Lambdaizing Python Code Message-ID: <3d9559c4.14281625@news.t-online.de> A really usefull study ... NOT. http://p-nand-q.com/e/quicksort_lambda.html also known as "making Guido regret he put lambda in THE BEST PROGRAMMING LANGUAGE IN THE WORLD(TM)". From peter at engcorp.com Wed Sep 11 08:33:06 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 11 Sep 2002 08:33:06 -0400 Subject: deleting the first and the last character of a string References: <3D7F2960.20507@Linux.ie> Message-ID: <3d7f37ee$1@news.sentex.net> Padraig Brady wrote: > Manuel Hendel wrote: > >> Is there anything which says delete the first or last >> character of a string? [snip] >> for line in inputfile.readlines(): >> fields = string.split(line, "|") >> lineN = string.join(fields[1:-1], "|") >> >> Isn't there any better solution? ;-) >> > How about: line = line[1:-1] Which doesn't quite work as-is for the OP, since he's using readlines() to bring in the lines and this will delete only the trailing newline, not the final | character. The basic idea is sound though, but susceptible to problems if there is any leading or trailing whitespace as well. The OP didn't specify whether that was possible. -Peter From marklists at mceahern.com Wed Sep 4 10:48:34 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 4 Sep 2002 09:48:34 -0500 Subject: efficient list merging In-Reply-To: <1031150751.2615.40.camel@tass1.localdomain> Message-ID: Question: What if lol1 had ['g', 'f']? Would that be considered the same as ['f', 'g']? Anyway, here's yet another approach: #! /usr/bin/env python lol1 = [['a'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j']] lol2 = [['d', 'e', 'f'], ['k', 'l', 'm'], ['d'], ['f', 'g'], ['a']] def mergelists(*lists): d = {} for each_list in lists: for item in each_list: key = str(item) if key not in d: d[key] = item ret = d.values() ret.sort() return ret mergelol = mergelists(lol1, lol2) expected = [['a'], ['a', 'b', 'c'], ['d'], ['d', 'e', 'f'], ['f', 'g'], ['g', 'h', 'i', 'j'], ['k', 'l', 'm']] assert mergelol == expected // m - From dougfort at dougfort.net Mon Sep 23 15:07:47 2002 From: dougfort at dougfort.net (dougfort) Date: Mon, 23 Sep 2002 12:07:47 -0700 (PDT) Subject: Dynamic loading of modules Message-ID: <20020923120748.18158.h006.c001.wm@mail.dougfort.net.criticalpath.net> On Mon, 23 September 2002, "Andreas Lydersen" wrote: > > Hi, > I'd like to load a set of modules from a directory. I have tried to use the > __import__(...) statement to do so, but with no success. > ? > The static approch works (of course), but the dynamic does not! > > static: > import plugins.Password > > dynamic atttempt: > __import__("plugins.Password") > > I have tried 'exec "plugins.Password"', and that works. However, I need to > get a list of pointers to the modules I import in order to work with them > later. > > Bottom line is: I need to know how to dynamically load modules and get a > pointer to the same module. > > Any help is appreciated. > Here's something my friend Joe found for a project we're working on Regarding loading python "modules" from a directory... check out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82234 Additional info: Title: Importing a dynamically generated module Submitter: Anders Hammarquist (other recipes) Last Updated: 2001/10/17 Version no: 1.0 Category: System Doug Fort http://www.dougfort.net From b.maryniuk at forbis.lt Mon Sep 2 06:28:58 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 2 Sep 2002 12:28:58 +0200 Subject: Why it is so dramatical? In-Reply-To: References: Message-ID: <200209021228.58453.b.maryniuk@forbis.lt> On Monday 02 September 2002 11:57, Duncan Booth wrote: > None of this is specific to Python, the same issues arise in almost any > programming language (although not always the same solutions). Almost... Keep in mind, that here is the range 0-0xffffff, what is quite bigger that 0-0xfff: ----------------------8<--------------------------- #!/usr/bin/perl $b = ''; $data = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; for $a (0..0xffffff) { $b += $data; } ----------------------8<--------------------------- Since time() always show me zero, I've used UNIX time command: ----------------------8<--------------------------- *bo at oberon:(~/work/spike/benchmarks) time perl str_vs_list.pl real 0m8.734s user 0m8.710s sys 0m0.010s ----------------------8<--------------------------- As you see, adding string to the string isn't a huge problem for Perl as for Python. What's "wrong" with Perl? -- Regards, Bogdan Un*x admins know what they are doing by definition. -- Bernd Petrovitsch From mstenner at phy.duke.edu Fri Sep 27 16:35:03 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Fri, 27 Sep 2002 16:35:03 -0400 Subject: watching mutables? In-Reply-To: ; from theller@python.net on Fri, Sep 27, 2002 at 10:06:41PM +0200 References: Message-ID: <20020927163503.A17848@phy.duke.edu> On Fri, Sep 27, 2002 at 10:06:41PM +0200, Thomas Heller wrote: > "Michael Stenner" wrote ... > > I am also interested in this module (curiosity, mostly) and would > > appreciate a working link if you have one. > > > Here's what seems to be available: > http://oomadness.tuxfamily.org/downloads/ > and this is obviously where the EventObject is contained in: > http://oomadness.tuxfamily.org/downloads/EditObj-0.3.tar.gz Well, I'm not sure what makes it obvious, but it is correct :) Thanks! -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From rjones at ekit-inc.com Wed Sep 18 20:22:40 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 19 Sep 2002 10:22:40 +1000 Subject: Python doesn't suck! In-Reply-To: References: Message-ID: <200209191022.40648.rjones@ekit-inc.com> On Thu, 19 Sep 2002 2:31 am, rzed wrote: > "Domenico" wrote in message > news:e34e8ce6.0209180737.49868d9f at posting.google.com... > > > http://www.theperlreview.com/at_a_glance.html > > > > According to the most accurate algorithm, Python is the second > > less-sucking language. > > Behind PHP (?!) if I read the charts right. Says a lot about the > languages. Actually, that page says stuff-all. A friend wrote another version of the sucks-rules-ometer that filtered out a bunch of false positives and negatives for a bunch of different languages (Monty Python hits, for example, were filtered out of the Python results). IIRC Python had a significantly better standing than the results on the perl review's site :) Richard From r.kalbermatter at hccnet.nl Wed Sep 18 16:48:58 2002 From: r.kalbermatter at hccnet.nl (Rolf Kalbermatter) Date: Wed, 18 Sep 2002 22:48:58 +0200 Subject: Python as shared library on Unix Message-ID: I'm currently in the process of porting a Python embedding from Windows to Linux and have come across an appearent problem. Under Windows I have linked my app dynamically to the pythonXX.dll using LoadLibrary/GetProcAddress and that works very nicely. Under Linux I see no option to build a python.so.2.2.1 or similar to link my application to with the dl* functions. My question is if I have overlooked some option in ./configure or somewhere else or if this is not possible out of the box? If it is not available as a standard, what are the changes to get it working by modifying the ./configure and or Makefile scripts? I read in the documentation that under Windows one needs to link to the DLL in order to have dynamic module loading available, for the Mac OS X part there where some adjustments in the past to make sure that sys.executable was pointing to the user executable instead of the shared module. I could think of several such pitfals which could show up when creating a Linux shared library. I can of course always link the Python core into my application which by the way is a shared library itself which is loaded dynamically into the main application but coming from the Windows world, this seems kind of unelegant to me. Rolf Kalbermatter From member at dbforums.com Fri Sep 13 23:20:26 2002 From: member at dbforums.com (hpyhpy) Date: Sat, 14 Sep 2002 03:20:26 +0000 Subject: Anyone can tell me why? Message-ID: <1815200.1031973626@dbforums.com> hi,everybody: I'm puzzled about SWIG. On sco openserver5,I try swig's example: /****************************/ example.c /* File : example.c */ /* A global variable */ double Foo = 3.0; /* Compute the greatest common divisor of positive integers */ int gcd(int x, int y) { int g; g = y; while (x > 0) { g = x; x = y % x; y = g; } return g; } /****************************/ example.i /* File : example.i */ %module example extern int gcd(int x, int y); extern double Foo; /****************************/ And I do : #gcc -c example.c #swig -python example.i #gcc -c example_wrap.c -I/usr/local/include/python2.2/ #gcc -G -Wl example.o example_wrap.o -o _examplecmodule.so Then it has these files: example.c example.i example.o example_wrap.c example_wrap.doc example_wrap.o _examplecmodule.so So I wonder where is the "example.py"??? So I can't "import example" Traceback (most recent call last): File "", line 1, in ? ImportError: No module named example *_* *_* *_* Who can tell me why,please help me,I'm a tyro^_^ Thank! -- Posted via http://dbforums.com From vze3myxh at verizon.net Fri Sep 20 19:29:46 2002 From: vze3myxh at verizon.net (Satheesh Babu) Date: Fri, 20 Sep 2002 23:29:46 GMT Subject: pyrhon and oracle References: <5b8834c2.0209201412.50e77861@posting.google.com> Message-ID: cx_Oracle might be the *easiest* to use. I use DCOracle while working with Zope, but for standalone development, cx_Oracle is tops. Download the driver from http://www.computronix.com/utilities.shtml go to Python DB-API specs http://www.python.org/topics/database/DatabaseAPI-2.0.html Here's an example using DB-API http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 vsb http://vsbabu.org/ > hi , i just want to have some detail about python and oracle what ca i > use to query oracle with python ? > > i jsut want a little exemple > > thanks From gua81 at XXXyahoo.com Wed Sep 25 08:12:24 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Wed, 25 Sep 2002 22:12:24 +1000 Subject: Strange python and cgi! References: <3D9158F4.F826F039@alcyone.com> Message-ID: yeah in my uni's it's /web/log/apach1.3.0/error_log or something like that....... anyway thanks for all who responded. "Erik Max Francis" wrote in message news:3D9158F4.F826F039 at alcyone.com... > Tim Roberts wrote: > > > If you are running Linux, check the log file at > > /var/log/httpd/error-log. > > The problem is that the log location depends entirely on how Apache is > configured, which in turn depends upon the version, the distribution > (which often choses different locations for different log files), and > the local configuration. It could be /var/log/error_log, > /var/log/errors, /var/log/apache/errors, etc. > > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ > __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE > / \ Music washes away from the soul the dust of everyday life. > \__/ Berthold Auerbach > 7 Sisters Productions / http://www.7sisters.com/ > Web design for the future. From fredp at mygale.org.nospam Wed Sep 18 03:20:00 2002 From: fredp at mygale.org.nospam (Fred Pacquier) Date: 18 Sep 2002 07:20:00 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: lpgray at uop.com (Lee Gray) said : > I'm a fairly new programmer with experience in ASP/VBScript/DHTML. > Other than small utilities, so far I've mostly written ASP apps to > talk to an Oracle database on HP/UX, with Windows NT/2000 clients, and > I've done maintenance work on VB and Oracle Forms apps. > We're currently looking at .Net, and I'm not very impressed, for a > variety of reasons. A little research makes me feel that either Java > or Python would be a good alternative, and given my level of > experience, I'd much prefer Python over Java. I *think* I could > actually get up to speed faster with Python than with VB and ASP.Net, > in spite of my ASP/VBS experience. > My boss is pretty open-minded, but also needs to see something working > to be convinced Python is even a viable platform (he had never heard > of it). Otherwise, .Net is a given, whether it's any good or not, > since corporate is MS all the way. > Can someone point me to a good Python GUI app to demonstrate (other > than IDLE)? In addition to what's already been suggested, you may want to look at the "samples" (demos) in the PythonCard distribution. They're small apps, but quite demonstrative, especially considering the size of the code and ease of use : http://pythoncard.sourceforge.net/ Of course, PythonCard is based on wxPython, and that has a nice showcase demo suite as well. Finally, a nice (very VB-like) IDE for wxPython is Boa Constructor, although you'll need to pull the matest version from CVS : http://boa-constructor.sourceforge.net/ HTH, fp -- YAFAP : http://www.multimania.com/fredp/ From jubafre at brturbo.com Fri Sep 13 14:14:45 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Fri, 13 Sep 2002 15:14:45 -0300 (GMT-03:00) Subject: transform list of int in a list of string?? Message-ID: <-1483717605.1031940885180.JavaMail.nobody@webmail2.brturbo.com> How can i transform a list of integer numbers in a list of string numbers, like that: x=[1,2,3,4] to y=['1', '2'...]???????? Juliano Freitas www.gebrasil.hpg.com.br From gerhard.haering at opus-gmbh.net Tue Sep 3 09:17:44 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 3 Sep 2002 13:17:44 GMT Subject: How to avoid freeing memory on exit? References: Message-ID: Roy Smith wrote: > [...] Is there any way to get the interpreter to just exit without doing all > that memory cleanup? os._exit -- Gerhard From Oschler at earthlink.net Mon Sep 2 07:24:57 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Mon, 2 Sep 2002 07:24:57 -0400 Subject: Must have Python modules? Message-ID: <_THc9.42153$vY2.1039887@e3500-atl2.usenetserver.com> I've scanned Vaults of Parnassus and several other hot Python sites and was overwhelmed by the amount of stuff that is available. So I'm asking you, what is your favorite, absolute must-have Python module? thx From marklists at mceahern.com Mon Sep 30 18:22:02 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 30 Sep 2002 17:22:02 -0500 Subject: Question about __getattribute__/__getattr__ In-Reply-To: Message-ID: [Joao Prado Maia] > My question is, how do I get the actual argument list from inside > __getattr__, so I can create an unique method/argument list signature for > the cached files ? :) __getattr__ may not be the ticket. I can sketch one possibility, but sadly I don't have time to flesh it out fully: When you init your Cache class, dynamically build proxy methods for each method in the cached class. Something like this: import inspect class Foo(object): def do_something(self, *args, **kwargs): # whatever class Cache(object): def __init__(self, cached_class): self._inst = cached_class() for m in inspect.getmembers(self._inst, inspect.ismethod): # m is a tuple, m[0] is the method name, m[1] is the method setattr(self, m[0], MemoizedFunction(m[1])) Cheers, // m From marco at reimeika.ca Wed Sep 25 19:33:06 2002 From: marco at reimeika.ca (marco) Date: 25 Sep 2002 19:33:06 -0400 Subject: "which" command? Message-ID: Hi, A few days ago there was a discussion here about a "which" written in python (as opposed to running the OS "which" command). Any pointers to that thread? As you can imagine it's been difficult to make a sensible google groups query since I can't think of any reasonably specific terms to search for... Cheers, -- marco at reimeika.ca Gunnm: Broken Angel http://reimeika.ca/ From duncan at NOSPAMrcp.co.uk Thu Sep 5 04:42:24 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 5 Sep 2002 08:42:24 +0000 (UTC) Subject: Why read-only nested scopes? References: Message-ID: martin at v.loewis.de (Martin v. Loewis) wrote in news:m3bs7da0zs.fsf at mira.informatik.hu-berlin.de: >> OTOH, if "everything is an object," then the namespace of >> an enclosing scope could also be an object, and as such >> could support rebinding of names therein ;-) > > It is an object - the frame object. There is just no easy way to refer > to that object. And don't forget that when the nested function is called the frame object may no longer exist: nested scope variables can continue to exist after the frame in which they were created has been destroyed. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From david.abrahams at rcn.com Sun Sep 8 09:42:36 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Sun, 8 Sep 2002 09:42:36 -0400 Subject: C++ and Python References: Message-ID: "Tony Leotta" wrote in message news:mailman.1031460196.14007.python-list at python.org... > Does any one know of any examples written in C++ that use Python as a > scripting language? > > I have been looking at VBA.but I don't know all that COM interfacing > gets me down. :( > You might try posting your question to c++-sig at python.org (http://www.python.org/sigs/c++-sig/ to subscribe). I know other people on that list have been using Python to add scripting to C++ apps. -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From robin at alldunn.com Thu Sep 19 21:42:24 2002 From: robin at alldunn.com (Robin Dunn) Date: Thu, 19 Sep 2002 18:42:24 -0700 Subject: ANNOUNCE: wxPython 2.3.3.1 Message-ID: <3D8A7D00.8030002@alldunn.com> wxPython 2.3.3.1 has just been released! You can get binaries for Win32, Mac OS X or Linux, as well as sources, documentaion, etc. from http://wxPython.org/ or directly from SourceForge at http://sf.net/project/showfiles.php?group_id=10718&release_id=111669 wxPython is an extension module for Python that provides access to many of the wxWindows GUI C++ classes from applications written in the Python programming language. It uses native controls wherever possible providing native Look and Feel as well as the speed you would expect from natvie compiled applications. Major changes from the previous release are listed below. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! Changes in 2.3.3.1 ------------------ Added wxSplashScreen. Added wxGenericDirCtrl. Added wxMultiChoiceDialog. The calltip window and autocomplete window in wxSTC will now use a wxPopupWindow if available on the platform (and functioning correctly) so they can extend beyond the client area of the STC if needed. Finished wrapping and providing typemaps for wxInputStream and also added the stream ctor and other methods for wxImage so images can now be loaded from any Python "file-like" object. Changed the img2py tool to use PNG instead of XPM for embedding image data in Python source code, and the generated code now uses streams to convert the image data to wxImage, wxBitmap, or wxIcon. Added the wxPython.lib.rcsizer module which contains RowColSizer. This sizer is based on code from Niki Spahiev and lets you specify a row and column for each item, as well as optional column or row spanning. Cells with no item assigned to it are just left blank. Stretchable rows or columns are specified and work the same as in wxFlexGridSizer. Updated XRCed from Roman Rolinsky Added wxBufferedDC. Upgraded wxSTC from Scintilla 1.40 to Scintilla 1.45, and then again to version 1.47, and one more time to 1.48! UNICODE! wxWindows/wxPython can be compiled with unicode support enabled or disabled. Previous to wxPython 2.3.3 non-unicode mode was always used. Starting with 2.3.3 either mode is supported, but only if it is also available in wxWindows on the platform. Currently wxWindows only supports unicode on MS Windows platforms, but with the recent release of GTK+ 2.0 it is only a matter of time until it can be done on wxGTK (Linux and other unixes) as well. Unicode works best on platforms in the NT branch of the Windows family tree (NT, win2k, XP) but it is now also possible to use the same unicode binaries on win95/98/ME platforms as well! This is done by using a special library and DLL with the application called MSLU, (Microsoft Layer for Unicode). It simply gets out of the way if the app is run on an NT box, otherwise if run on a win9x box it loads a special DLL that provides the unicode versions of the windows API. So far I have not been able to get this to work perfectly on win9x. Most things work fine but wxTaskBarIcon for example will cause a crash if used with the unicode build on win95. So how do you use it? It's very simple. When unicode is enabled, then all functions and methods in wxPython that return a wxString from the C++ function will return a Python unicode object, and parameters to C++ functions/methods that expect a wxString can accept either a Python string or unicode object. If a string object is passed then it will be decoded into unicode using the converter pointed to by wxConvCurrent, which will use the default system encoding. If you need to use a string in some other encoding then you should convert it to unicode using the Python codecs first and then pass the unicode string to the wxPython method. Added wxListCtrlAutoWidthMixin from Erik Westra. Added wxIconBundle and wxTopLevelWindow.SetIcons. Added wxLocale and wxEncodingConverter. A little black magic... When the C++ object (for a window or whatever) is deleted there is no way to force the Python shadow object to also be destroyed and clean up all references to it. This leads to crashes if the shadow object tries to call a method with the old C++ pointer. The black magic I've done is to replace the __class__ in the Python instance object with a class that raises an exception whenever a method call (or other attribute access) is attempted. This works for any class that is OOR aware. Added OOR support for wxGridCellRenderer, wxGridCellEditor, wxGridCellAttr, wxGridCellAttrProvider, wxGridTableBase and their derived classes. Added wxImage.GetDataBuffer which returns an in-place edit buffer of the image data. (Patch #546009) Added a sample that shows how to embed wxPython in a wxWindows C++ application. Added wxPyWindow, wxPyPanel and wxPyControl which are just like their wx counterparts except they allow some of the more common C++ virtual methods to be overridden in Python derived classes. The methods supported are: DoMoveWindow DoSetSize DoSetClientSize DoSetVirtualSize DoGetSize DoGetClientSize DoGetPosition DoGetVirtualSize DoGetBestSize InitDialog TransferDataFromWindow TransferDataToWindow Validate AcceptsFocus AcceptsFocusFromKeyboard GetMaxSize AddChild RemoveChild If there are other methods that you think should be supported please let me know. Changed wxGenButton to derive from wxPyControl and overload DoGetBestSize and AcceptsFocus. Added wxArtProvider. Added wxCallAfter which is a helper function that registers a function (or any callable Python object) to be called once the next time there are no pending events. This is useful for when you need to do something but it can't be done during the current event handler. The implementation is very simple, see wxPython/wx.py. Fixed a boatload of reference leaks. Added a demo of using a sizer in a wxScrolledWindow, in effect creating a ScrolledPanel. Added a sample to the demo that shows how to use radio menu items, and other menu stuff. Added wxIEHtmlWin. This is essentially the same as using IE with the ActiveXWrapper already in the library, but it is implemented all in C++ and therefore does not need any of the modules from win32all and so it is less fragile in the face of changes. Fixed the ActiveXWrapper problem. Looks like when the win32com modules make a "callback" that they (incorrectly, IMHO) allocate a transient thread state structure. Since wxPython is now saving tstates for it's own callbacks it ended up using garbage after win32com got rid of the temporary tstate... Added a generic static text control to wxPython.lib.stattext. This is so things like Boa and PythonCard can have a static text that can respond to mouse events and etc. Changed the wxDateTime.Parse* methods to return an int that will be -1 on failure, and the index where parsing stopped otherwise. Moved tools to be a Python package in wxPython.tools, added scripts to import and launch each tool. This will let you import and use the tools in your own scripts or apps as needed. On Linux and OS X the tool scripts are installed to {prefix}/bin so you should be able to easily launch them from the command line. For example, PyCrust can be started with just the "pycrust" command. Added a sample to the demo that catches various key events and displays the details of the event. Added wxWizard, wxWizardPage, wxWizardPageSimple and wxPyWizardPage. Added wxXmlResourceHandler which allows you to create custom handlers for nonstandard class types in XRC resources. See the demo for an example. Added wxPython.lib.mixins.rubberband module from Robb Shecter. Added wxTimeCtrl from Will Sadkin. From ianholmes01 at lycos.com Thu Sep 19 10:39:12 2002 From: ianholmes01 at lycos.com (Ian Holmes) Date: 19 Sep 2002 07:39:12 -0700 Subject: monetary applications (et al) References: Message-ID: terry wrote in message news:... > >>>>> Chris wrote: > ------------------------------------------------- > class money: > def __init__(self,name): > self.name = name > > unitprice = money(100) > qty = 2 > amount = qty * unitprice > > terry at terry:~> python money.py > Traceback (most recent call last): > File "money.py", line 7, in ? > amount = qty * unitprice > TypeError: unsupported operand type(s) for *: 'int' and 'instance' > ------------------------------------------------- not that I want to do all your work for you but >>> unitprice = money(100) >>> qty = 2 >>> amount = qty * unitprice.name #as .name as the var that was assigned a value >>> amount 200 >>> taxrate = 0.06 >>> taxedamount = qty * unitprice.name + (qty*unitprice.name)*taxrate >>> taxedamount 212.0 >>> From ben at remove.Stanford.EDU Tue Sep 17 01:58:21 2002 From: ben at remove.Stanford.EDU (Ben Escoto) Date: Mon, 16 Sep 2002 22:58:21 -0700 Subject: Large file support and stat vs stat64 in extension modules References: Message-ID: On Tue, 10 Sep 2002 16:03:40 -0700, Ben Escoto wrote: > Does anyone know how to correctly stat a file within an extension > module? Why does: Someone (Russ Allbery) recently helped me with this, so I thought I might as well try answering my own question in case anyone else has this problem. The basic answer seems to be to define _LARGEFILE_SOURCE and _FILE_OFFSET_BITS=64. In fact, looking at Python's configure.in we see: AC_DEFINE(_LARGEFILE_SOURCE) AC_DEFINE(_FILE_OFFSET_BITS, 64) so just compile everything with -D_LARGEFILE_SOURCE and -D_FILE_OFFSET_BITS=64. If using distutils, adding define_macros=[("_LARGEFILE_SOURCE", 1), ("_FILE_OFFSET_BITS", 64)] when declaring the ext_modules does something similar and seems to work. Again, this is a bit ad hoc, but seems to work, and I don't know of a better way. -- Ben Escoto From lordmacro at hotmail.com Mon Sep 30 04:09:54 2002 From: lordmacro at hotmail.com (Tom Widrick) Date: Mon, 30 Sep 2002 03:09:54 -0500 Subject: sizeof PyTypeObject difference References: Message-ID: > > I'm trying to make a metatype in C, but there seems to be some difference > > between the size of the type object. > > > > typedef struct { > > PyTypeObject type; > > } MyMetaObject; > > > > > > and in the tp_basicsize field I place sizeof(MyMetaObject) the value is only > > 196. > > This is a type declararation. In C, you cannot put values into a type > declaration. So I assume you are creating a value (an object) of > struct MyMetaObject, and you put 196 into this value. Well, I didn't specify but I figured it obvious the sizeof(MyMetaObject) goes into the PyTypeObject of the metatype, i.e. PyTypeObject MyMetaType_Type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "MyMetaType", /*tp_name*/ sizeof(MyMetaObject), /*tp_basicsize*/ > If so, you misunderstand the meaning of tp_basicsize: It does not > describe the size of the type object, but the size of instances of the > type. Well, aren't instances of a metatype types? I know this statement was probably made from invalid assumptions, but just as a point. Since types are variable sized, as you say, how does this tie in with tp_basicsize and metatypes? > That is hard to believe. Declaring the typedef alone can't cause a > core dump. Defining an object of that type, and putting the value of > 196 into it can't cause a core dump, either. You must be doing other > things, like using the resulting object in some way, to cause a core > dump. Trying to use the metatype as a metaclass for a python class. > > What is the cause of this difference? > > The type type is really a variable-sized object. You are seeing the > size of struct etype, which is hidden in typeobject.c. > > You can't currently declare a type with additional C fields, since > type objects are variable-sized. One approach is to put additional > things into the type's __dict__. Another approach is to use Christian > Tismer's patches to overcome this limitation; I recommend that you > contact Christian. Thanks for the info on that one. Very helpful. Wish that was stuck in PEP 253. As an aside, are there any other quarks about making metatypes in C? the xxsubtype.c example in the distrib is helpful, along with the PEPs, but I'm yet to find a good example of a metatype implemented in C (besides the 2 builtin metatypes, but I don't think those serve as great minimalistic examples). Tom From erikprice at mac.com Thu Sep 12 23:31:12 2002 From: erikprice at mac.com (Erik Price) Date: Thu, 12 Sep 2002 23:31:12 -0400 Subject: ANN: NINZ 1.2.1 In-Reply-To: <20020912191701.A20774@ibook.distro.conectiva> Message-ID: <40197710-C6C9-11D6-B141-00039351FE6A@mac.com> On Thursday, September 12, 2002, at 06:17 PM, Gustavo Niemeyer wrote: > In particular, ZSI parses and generates SOAP messages, > and converts between native Python datatypes and SOAP syntax. This is sort of OT, but is this what is sometimes referred to as "data marshalling"? Erik -- Erik Price (zombies roam) email: erikprice at mac.com jabber: erikprice at jabber.org From eric.brunel at pragmadev.com Mon Sep 9 04:38:59 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 9 Sep 2002 10:38:59 +0200 Subject: Creating a Text widget in a Dialog (Tkinter) References: Message-ID: Aki Niimura wrote: > Hi, > > I'm trying to create a simple dialog which has a Text with > scrollbars(H and V) > in a dialog. (I'm inherting Tkinter Dialog class) BTW, if it's for a real application, have you considered the Pmw package? See: http://pmw.sourceforge.net/doc/refindex.html The TextDialog class already does exactly what you want. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From duncan at NOSPAMrcp.co.uk Fri Sep 13 04:26:51 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 13 Sep 2002 08:26:51 +0000 (UTC) Subject: wrapping yield ? References: Message-ID: "Michael Sparks" wrote in news:alqehl$9qv$1 at nntp0.reith.bbc.co.uk: > I'd like to be able to wrap "yield" in a function - is that > possible, and if not (my eading of stuff I've seen so far > says not) are there any plans to make it possible? > > Whilst it may seem odd, I'd like to be able to do this: > > def my_generator(arg): > dostuff.... > while(1): > waitForSomethingCheckingPeriodically() > processit > > where > > def waitForSomethingCheckingPeriodically(): > found = 0 > while(not found): > x = checkTheThing() > if foundRightThing(x): > found = 1 > else: > yield "foo" > return x > You have to propogate the yield up to the top level by yielding from each intermediate generator, and your generator cannot return a value so you should yield the returned results. So something like this should work: def my_generator(arg): dostuff.... for item in waitForSomethingCheckingPeriodically(): if item is None: yield None else: processit(item) def waitForSomethingCheckingPeriodically(): while 1: x = checkTheThing() if foundRightThing(x): yield x else: yield None -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From jepler at unpythonic.net Wed Sep 11 21:57:58 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Wed, 11 Sep 2002 20:57:58 -0500 Subject: ntpath bug or expected? In-Reply-To: References: Message-ID: <20020911205757.C1555@unpythonic.net> On Thu, Sep 12, 2002 at 01:18:21AM +0000, dsavitsk wrote: > python 2.1.3. this is pretty minor ... os.path.join() on win32 fails if the > first path component is C: (or any other letter). that is, if the first > component is a drive letter, it must contain either '\\' or '/' or else the > path is wrong. this makes it the only component which must have slashes. > > example > >>> os.path.join('C:', 'path', 'to', 'file.txt') > C:path\\to\\file.txt Sure. This is the file on drive C which is in the relative path "path\\to\\file.txt" from the current directory of drive C. Remember, DOS maintains a separate working directory for each drive. A first element of C:/ would make the path absolute, and a first element of C: would make the path relative to the current directory of C. I think that is why >>> ntpath.join("C:", "/path", "to", "file.txt") 'C:/path\\to\\file.txt' is "correct". This is the one I wonder about, though: >>> ntpath.join("C:", "/a", "/b", "x.txt") '/b\\x.txt' >>> ntpath.join("C:/a", "/b", "x.txt") '/b\\x.txt' if the drive letter is preserved in my first example, why isn't it in the last two? Jeff From bloke at ii.net Thu Sep 19 22:31:01 2002 From: bloke at ii.net (Rob Hall) Date: Fri, 20 Sep 2002 10:31:01 +0800 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <96904b50.0209181149.429e8533@posting.google.com> Message-ID: <3d8a887f$0$31798@echo-01.iinet.net.au> Hi. > I've written a quite big wizard for 3D image processing > with wxPython, PIL, Stackless. I wouldn't mind a look - whats the address for your wizzard? Rob From pinard at iro.umontreal.ca Sun Sep 1 20:45:58 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Sun, 01 Sep 2002 20:45:58 -0400 Subject: Making regex suck less In-Reply-To: (Carl Banks's message of "Sun, 1 Sep 2002 19:17:19 -0400") References: <3d725881.345921@news.t-online.de> Message-ID: [Carl Banks] > You might want to look at the Plex package. [...] > > First, this will certainly be slower than regular expressions, since > there are many Python calls needed to build the structure. (Of course, > after you've compiled it, it can be as fast as regexps.) The Plex matching engine does not backtrack, which might be an advantage over Python regexps at matching time, at least theoretically for some regexps. Building the matching tables, however, consumes a lot of time. So I guess that for most usual regexps, Python regexps are quite OK. > Second, even if you use re module, it is still nowhere near Perl-ish > ugliness. You still have Python's clean syntax outside of the pattern. A clear and definite advantage! :-) :-) > Third, readability is not a unilateral good thing; conciseness is also > important [...] Python regexps, given some flag at compilation time, may allow for embedded whitespace and comments. With proper care, difficult regexps could be made less compact and more readable, without changing at all how they behave at run-time. Conciseness is a quality for short regexps. Horrid regexps are more advantageously written non-compactly. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From aleax at aleax.it Thu Sep 26 10:03:18 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 14:03:18 GMT Subject: object changing itself to another object References: Message-ID: Glen Murphy wrote: >> You have not checked O'Reilly's Python Cookbook, I think, because >> this particular idea of changing an object's __class__ is exemplified >> there. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429 >> in the online version, but I think you'll find the discussion more >> complete, &c, in the printed version. > > Thanks Alex, I have actually subscribed to the book on Safari, but it's > kinda hard to flick through there :D Yep -- I love Safari for certain things, but I *still* stock up on the paper versions too:-). Alex From duncan at NOSPAMrcp.co.uk Wed Sep 4 11:34:23 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 4 Sep 2002 15:34:23 +0000 (UTC) Subject: newbie-question: difference between classmethod and staticmethod in Python2.2 References: <3D7619AE.3050605@snafu.de> Message-ID: "T. Kaufmann" wrote in news:3D7619AE.3050605 at snafu.de: > > When should I use staticmethod or classmethod in classes? > > I thought a staticmethod is a classmethod like in C++/ Java? A staticmethod is like a static method in C++/Java. A classmethod has no direct equivalent in C++/Java. Use a staticmethod when you know which class you want to access as you are writing the code. class C: def smethod(newX): C.x = newX # Update class variable smethod = staticmethod(smethod) Use a classmethod if you have a class hierarchy and want the method to operate on the actual class used in the call rather than the class where it was defined: >>> class C: def cmethod(cls, newX): cls.x = newX cmethod = classmethod(cmethod) >>> class D(C): pass >>> c = C() >>> d = D() >>> c.cmethod(5) # or C.cmethod(5) >>> print c.x 5 >>> print d.x 5 >>> d.cmethod(42) # or D.cmethod(42) has the same effect. >>> print c.x 5 >>> print d.x 42 So here we have two separate class variables, one in C and one in D but both are set by the same method. It is a fairly specialised and not very common requirement to do this. Mostly you probably want a staticmethod instead. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From gerhard.haering at gmx.de Fri Sep 13 23:34:43 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 14 Sep 2002 03:34:43 GMT Subject: Question regarding mysqldb module and variable table names References: <45ac92e5.0209131920.23b1c22a@posting.google.com> Message-ID: Glenn Scott wrote in comp.lang.python: > c.execute("""INSERT INTO %s \ > SET playerkey=%s, link=%s, snippet=%s, time_created=%s, \ > last_seen=%s, relevancy=%s, doc_title=%s """, \ > (infoTable, playerKey, urlLink, snippetText, > self.getCurrentTime(), self.getCurrentTime(),\ > noOfMentions, re.escape(str(self.doc_title))) ) sql = """INSERT INTO %s (playerkey, link, snippet, time_created, last_seen, relevancy, doc_title) VALUES (%%s, %%s, %%s, %%s, %%s, %%s, %%s)""" % infoTable c.execute(sql, (...)) The reason why your original approach didn't work is that DB-API quoting is different from Python-quoting. So MySQLdb quotes your table name for SQL insertion, and adds apostrophes around it. You can use Python quoting as above to work around this. Also, forget about re.escape. The DB-API module will quote the values appropriately for insertion into SQL. -- Gerhard From cliechti at gmx.net Sun Sep 1 17:47:01 2002 From: cliechti at gmx.net (Chris Liechti) Date: 1 Sep 2002 23:47:01 +0200 Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: "Robert Oschler" wrote in news:wmvc9.21757$FJ1.3181934 at e3500-atl1.usenetserver.com: > Some interesting tidbits I > found while trying out your suggestions, as you will see in the two > ".py" files that follow, I discovered that to create a method you can > dynamically add to a class _instance_, you need to omit the 'self' > parameter in the method declaration. For a method you add dynamically > to a class definition itself, then you must include the 'self' > parameter in the method declaration. If not, you will get an argument > count mismatch complaint from the interpreter. Fascinating stuff. that's just the differece between a "function" and a "method". a method works on an object and that is passed explicit as first argument. "explicit is better than implicit" (you can read this and some other design ideas by typing ">>> import this" ;-) > I'm running 2.1.1, anybody know if 2.2.2 is going "disable" either of > these abilities? (class or class instance dynamic method addition). I > saw a note about such activities requiring a "dynamic" keyword, which > is fine. I'd really miss either of these abilities. nah. "classic classes" stay the way they are and are available until 3.0 new style classes, those that inherit from "object" or "type", will need the marking as "dynamic". chris -- Chris From sholden at holdenweb.com Mon Sep 30 07:58:50 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 30 Sep 2002 07:58:50 -0400 Subject: Python's import: why doesn't it work? References: Message-ID: <%VWl9.23638$F21.9224@fe02> "Paul Pichaureau" wrote in ... > > "Tim Peters" a ?crit dans le message de news: > mailman.1033322378.3697.python-list at python.org... > > > The docs are exactly as good as volunteers have made them (well, actually > > better, thanks to Fred ). When you find an explanation inadequate > to > > your needs, suggesting specific improvements in the right place is the > only > > way it will improve. > > Then, these are my suggestions to improve documentation on installing and > managing module : > [reasonable suggestions] And one of the reasons the documentation doesn't improve faster is that apparently intelligent people, confronted with an explicit quotation of explicit adice about how to improve it *still* appear to think that a post of c.l.py will suffice to make a change. It can't be stated often enough: if you want a change made, SourceForge is the appropriate place to suggest it. In the case of the documentation, Fred Drake is very responsive, and emailing him via python-docs at python.org usually works (but this makes extra work for Fred, who's probably busy enough). regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From zopestoller at thomas-guettler.de Mon Sep 16 04:01:16 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Mon, 16 Sep 2002 10:01:16 +0200 Subject: Book for win32? Message-ID: Hi! I am interested in book about Python on win32. I found one from o'reilly: "Python on win32" Are there better books or alternatives? I am *not* looking for a python introduction, I am programming more than one year with python, but up to now mostly on unix. Now I am intersted in win32 stuff: - Opening a file-dialog - COM - Accessing the registry - Maybe GUI Programming .... thomas From theller at python.net Wed Sep 4 09:05:51 2002 From: theller at python.net (Thomas Heller) Date: Wed, 4 Sep 2002 15:05:51 +0200 Subject: newsgroup for zope References: <3d75fddc@news.sentex.net> Message-ID: "Peter Hansen" wrote in message news:3d75fddc at news.sentex.net... > stephan wrote: > > Hi perhaps a stupid question, > > > > but does there exist a newsgrup for zope centric items? > ^^^^^^^^ > You spelled "newsgroup" wrong. It's spelled "mailing list" and > you can find out about them here: > > http://www.zope.org/Resources/MailingLists > > :-) > > -Peter > > (There's no actual newsgroup though.) > But then there's news.gmane.org. Read mailing lists with your newsgroup reader... Thomas From dsavitsk at e-coli.net Sun Sep 15 12:51:05 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sun, 15 Sep 2002 16:51:05 GMT Subject: win32security.LogonUser not working References: Message-ID: I have gone so far as to assign every possible right in dir(ntsecuritycon), but i am still getting the same error. I have also assigned nearly everyone and every thing on my network the right to act as the os. any ideas? -d "dsavitsk" wrote in message news:L9Pg9.8440$yt3.4474038 at newssrv26.news.prodigy.com... > should have mentioned > python: 2.1.3 > win32all: 145 > win2k: sp2 > > > "dsavitsk" wrote in message > news:x6Pg9.8439$yt3.4473830 at newssrv26.news.prodigy.com... > > I am trying to run code as another user. I copied the code below from > ASPN, > > so it would seem that someone has gotten this to work. I keep getting the > > error > > > > pywintypes.api_error (1314, 'LogonUser', 'A required privilege is not held > > by the client.') > > > > Google has revealed that others gave had the same problem. does anyone > know > > a solution, or even a different way to do this? > > > > -doug > > > > link to the original of code below > > > http://www.google.com/search?q=cache:Jnbt2XVyGfUC:aspn.activestate.com/ASPN/ > > > Python/Reference/Products/ActivePython/PythonWin32Extensions/Windows_NT_Secu > > > rity_.2d.2d_Impersonation.html+self.handel%3Dwin32security.LogonUser&hl=en&i > > e=UTF-8 > > > > --------------------------------------------- > > import win32security > > import win32con > > import win32api > > import sys > > > > > > class Impersonate: > > > > def __init__(self): > > self.domain = '.' > > self.login = 'myusername' > > self.password = '**********' > > > > def logon(self): > > self.handel=win32security.LogonUser(self.login, > > self.domain, > > self.password, > > > > win32con.LOGON32_LOGON_INTERACTIVE, > > > > win32con.LOGON32_PROVIDER_DEFAULT > > ) > > win32security.ImpersonateLoggedOnUser(self.handel) > > > > def logoff(self): > > win32security.RevertToSelf() #terminates impersonation > > self.handel.Close() #guarantees cleanup > > > > > > > > > > if __name__ == '__main__': > > a=Impersonate() > > try: > > a.logon() #become the user > > print win32api.GetUserName() #show you're someone else > > a.logoff() #return to normal > > except: > > print sys.exc_type , sys.exc_value > > > > > > From lordmacro at hotmail.com Fri Sep 20 18:37:33 2002 From: lordmacro at hotmail.com (Tom Widrick) Date: Fri, 20 Sep 2002 17:37:33 -0500 Subject: implementing reduce protocol in C References: <3D8A7DA1.7090506@hotmail.com> <62Ai9.136323$pX1.4852975@news2.tin.it> <3D8AF51D.5040305@hotmail.com> Message-ID: "Alex Martelli" > I recommend you use "ANSI C" style as a habit: > > static PyObject* > proto_reduce(HyProtoObject* self) That's what I get for copy/pasting from the python source code. > Rather, you probably want to expose a factory function to be > passed as the first item in the tuple returned by __reduce__ > (you may then want to return a 2-items tuple rather than a > 3-items one from __reduce__, perhaps). Just make sure said > first item exposes an attribute named __safe_for_unpickling__ > with a true value, or register it as a "safe constructor" with > module copy_reg. If it's not one thing, it's another. I decided to try this route but have been barricaded again. I stuck a _build function in the module method table and used copy_reg in the init function to make it a "safe constructor." module = PyImport_ImportModule("copy_reg"); if(module == NULL) return; method = PyDict_GetItemString(PyModule_GetDict(module), "constructor"); if(method == NULL) return; func = Py_FindMethod(mod_methodlist, NULL, "_build"); if(func == NULL) return; args = PyObject_CallFunction(method, "(O)", func); Py_DECREF(func); if(args == NULL) return; else Py_DECREF(args); Now cPickle is complaining that _build is not found as __main__._build. I tried, in my python script, to directly stick it in the namespace, but it says it's not the same. from proto import proto import cPickle Root = proto('Root') Root.spam = 'spam' d = cPickle.dumps(Root) cPickle.PicklingError: Can't pickle : it's not found a s __main__._build and when I put from proto import proto, _build cPickle.PicklingError: Can't pickle : it's not the sam e object as __main__._build I was easily able to do this in pure python using copy_reg, but the reason why I even started to port this type to C was because it was pickling/unpickling too slowly. I have a feeling this has something to do with wrapping the function object from C into python. My next attempt will be to create a factory type, like _protobuilder, that will be the first element of the tuple returned by __reduce__. I have the pickling working, now I just have to figure out how to make _protobuilder return a proto object. Tom From mertz at gnosis.cx Mon Sep 23 14:18:47 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 23 Sep 2002 14:18:47 -0400 Subject: conditional expressions References: Message-ID: "Delaney, Timothy" wrote previously: |This type of thinking is one very good reason why bool() is a Good Thing |(TM). A large number (my guess is the majority) of Python users do not know |about operator.truth(). Well... Python users won't necessarily innately know about bool() when it is available in 2.3 (or 2.2.x). In either case, users will gain the knowledge from documentation/discussion. While I'm not against the new boolean type, or built-in bool(), it's not impossible simply to let users know they can write: from operator import truth as bool at the top of their module. For that matter, they could also write: bool = lambda x: not not x if you really wanted to save 8 characters :-). Yours, Lulu... -- mertz@ _/_/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: \_\_\_\_ n o gnosis _/_/ Postmodern Enterprises \_\_ .cx _/_/ \_\_ d o _/_/_/ IN A WORLD W/O WALLS, THERE WOULD BE NO GATES \_\_\_ z e From mdketj at dwdddaae.com Thu Sep 5 19:45:35 2002 From: mdketj at dwdddaae.com (mdketj at dwdddaae.com) Date: Thu, 5 Sep 2002 23:45:35 +0000 (UTC) Subject: empresario frustrado e impotente Message-ID: <1031269091.522331@proxynews1> ############ http://burlasleo1.cjb.net ############# - ACT TO STOP CRIMINALS AND ABUSE OF POWER IN ENTERPRISES - HAJA PARA PARAR COM CRIMINOSOS E ABUSO DE PODER EM EMPRESAS ############ http://burlasleo1.cjb.net ############# sgzzkq From david at no.westcontrol.spam.com Fri Sep 27 08:21:51 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Fri, 27 Sep 2002 14:21:51 +0200 Subject: a python puzzle References: Message-ID: I'm not too interested in the crypogram puzzle, but your solution here has just given me a solution to something that has been bugging me for some time - finding an easy way to convert a list of characters into a string: >>> a = "Hello" >>> b = [x for x in a] >>> b ['H', 'e', 'l', 'l', 'o'] >>> "".join(b) 'Hello' >>> Thanks ! > > def decrypt(yourstring): > dedict = {'F': 'S', 'I': 'C', 'H': 'I', 'a': 't', 'c': 'f', 'b': 'v', 'e': 'n', > 'd': 'o', 'f': 's', 'i': 'c', 'h': 'i', 'k': 'p', 'j': 'h', 'm': 'l', > 'l': 'j', 'o': 'm', 'q': 'u', 'p': 'w', 's': 'b', 'u': 'z', 't': 'd', > 'w': 'y', 'v': 'x', 'y': 'e', 'x': 'a', 'z': 'g', 'g': 'k'} > return "".join([dedict.get(i,i) for i in yourstring]) > From syver-en+usenet at online.no Thu Sep 12 16:13:40 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Thu, 12 Sep 2002 20:13:40 GMT Subject: embedded Python sample References: <2a0f4cc4.0209100520.1d3a723b@posting.google.com> Message-ID: Michael Chermside writes: > bruno Monnet wrote: > > Hi, > > I'm trying to call a python script from my c++ code. All I need is > to > > > invoke the script and check the return status. > > does anyone has a simple example ? All I found until now is very > > complex and ugly code :-(( > > Regards, > > Bruno > > Why not just execute as a sub-process... invoke it as a shell command > just as you'd do with "ls". > > -- Michael Chermside > Yes that is also an option, use system("python your_script.py"); -- Vennlig hilsen Syver Enstad From aleax at aleax.it Tue Sep 17 08:27:46 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Sep 2002 12:27:46 GMT Subject: threads or queue for this task References: Message-ID: <6dFh9.120102$pX1.4321019@news2.tin.it> James J. Besemer wrote: > I also sense that I've somehow done something to piss you off. I'm > sorry if I did but I can't think what it would have been. I apologize in turn for giving that unintended impression. My reaction to your previous post can be well summarized with the words of Bjorn Pettersen's post (sent 3 minutes before mine, but I had not seen it as I composed mine): "You must be kidding (or you can't have written any significant amount of multithreaded code)". Taking it for granted that one wouldn't pontificate without vast relevant experience, I further surmised the "You must be kidding" part had to be correct -- e.g., that having posted an over-general assertion (something that happens to all) you were now bloody- mindedly defending the indefensible. Now it appears that you're substantially convinced of that assertion -- even though it appears so patently false as to be indefensible to both me and Mr Pettersen -- and am left to wonder about how our experiences can be so vastly different. Perhaps the hint is in Mr Pettersen's mention of "processing too many 16-GB files" vs your insistence on "capacity to handle the expected traffic", "time-critical requests", "the work requests may be created on a different machine", etc. I.e., you're focusing (perhaps because of how life shaped your experience of threading) on a "server" process or machine that is just responding to traffic originating elsewhere, while I'm giving at least equal weight to a process that's "just" doing a lot of batch-like work, e.g. generated by splitting up the task of processing a "16-GB file" or the like, and using threading to ensure the best throughput (implies that substantial parts of processing each work request happen in C code that release the GIL, be it within the Python core or in extensions). Thus, work requests can typically be generated quite fast (just a matter e.g. of sucking in some more of the "16-GB file" and finding the right boundaries therein for each work-unit to request), it IS crucial to consider the ratios of WU-preparation to WU-processing times, the total number of requests (say 1G requests if the average work-request deals with about 16 bytes of the 16-GB file...:-), and other such issues that you dismiss from "the general case". In such cases, the number of work requests is unbounded when generating a work-request is a matter of "rolling dice" a few times. For example, generating a work request might mean dealing and selecting a "suitable" bridge deal, and processing the request might mean simulating double-dummy play over such a deal and posting the result. The number of possibilities is NOT truly unlimited in such cases (there are, after all, just 5.3E28 possible bridge deals:-) but it's generally simplest to consider it unlimited, as it's large enough;-). If this is the root of our disagreement, I suggest you reconsider whether "the general case" need ONLY include "networked" situations, which seem to be what you istinctively think of in this context, or "threading to slice up a big batch of work" too. I think it definitely must cover both scenarios. In this case, we DO want to include bounded queues as a part of the "general case" -- and I think we should. "Optional embellisment": if e.g. the total number of requests won't cause the machine to trash, bounding the queues doesn't matter. But it's such a simple thing to do, that it can and should be considered in most such cases. >>>>>Generally, Queues never get "full" and you generally don't care if ... > I took your point to be that a bounded queue also is sometimes useful, > which I do not and did not dispute. Right: therefore, your here-re-quoted assertion is false. Queues DO get full when you set them to be bounded, and this need not cause substantial complication. > It goes without saying that if the designer knows in advance that he > doesn't have the throughput to handle incoming requests, then a ...if requests are "incoming" independently from what the designer can do, which is not the case when the process is dealing with a big batch of predefined work, e.g. processing a 16-GB file... > significantly more complicated solution is called for. I alluded to ...but setting a Queue to bounded, and implicitly sleeping when trying to add one more item to a full Queue, is NOT significantly more complicated. It's strongly parallel to sleeping just as implicitly when trying to peel an item from an empty Queue. The symmetry, when applicable, may be considered more elegant than an *asymmetric* solution, after all. > So at a high level I am at a loss, as you seem to be picking a fight I > did not intend to participate in. Like I said, I thought we were > largely in agreement, while expanding upon different scenarios. Again I apologize for giving the impression of "picking a fight". We can't be "largely in agreement" if you insist that your assertion: Generally, Queues never get "full" was correct and helpful to the OP, while I keep believing it was a dangerous over-simplification. But at least we can agree to disagree civilly, whence my apologies for appearing unwilling to do so in my earlier post. > In this, I am "coming from" the standpoint of Extreme Programming -- you > may recall -- that dictates you start by writing the simplest solution > you don't know won't work. Performance optimization and other > "embellishments" are always deferred unless/until you can't avoid it. But from my POV this generally goes for *threading in general*! I always consider a first-cut solution WITHOUT multi-processing, which is a huge complication in itself, more often than not. Therefore when I consider how to refactor an architecture for processing a batch of work into a threaded one I'm *ALREADY* dealing with performance optimization -- if my performance was good enough without threading, I wouldn't be threading, I'd be using some simpler approach (generally event-driven, if I must appear to be doing several things at once, e.g with GUIs, networks, etc). > That simplest, initial solution IMHO, is an unbounded queue. I further > characterize it as "elegant" as it's fully functional for many > applications and it's as simple as it gets. To me, real world > complications, however realistic, tend to result in less "elegant" > solutions but perhaps you disagree. I do disagree, and this may be a philosophical point in part. E.g., some Renaissance architects dreamed of "ideal cities" and went so far as to design and even build some. MY idea of the most elegant city-plan produced during the Renaissance is Ferrara's, where the architect (Rossetti) brilliantly *integrated* real-world complications (there's a river here, a marsh there, a hill yonder, a major thoroughfare from X to Y, ...) rather than brushing them aside or trying to ignore them. Indeed, Ferrara is the only "designed" (as opposed to "organically grown") city I know where I wouldn't mind living. Of course, not everybody can have Rossetti's genius, but to my mind THAT is the goal to aim for. And in fact, in their everyday professional practice, even Alberti and even more strikingly Palladio *integrated* "real-world complications" to produce their most elegant work, whatever they were saying in their theoretical treatises (I'll never forgive them for placing "venustas" BEFORE "utilitas", thus betraying Vitruvius' real heritage and helping start the split between architecture and engineering that broke the single concept of "techne" into artificial contrasts between "art" and "technique"... but when I consider what they actually BUILT rather than what they WROTE, I see great engineers at work, not "would-be-pure artists" frustrated in an abstract quest for elegance by the down-and- dirty "real-world complications"...!). But that's by the by. In practice, the amount of "complication" in setting a Python Queue instance to be bounded is trifling, anyway. > Yes. If you make them too small they will overflow. Nope! Rather, the thread that is trying to put one more item on an already-full Queue will implicitly and simply sleep until a slot becomes free, exactly the same way as one trying to pull one more ifem off an already-empty Queue will implicitly and simply sleep until an item is placed there. No intrinsic complications here. > Bounded queues are A solution to some problems but not The solution for > all situations. Of course not! Never did I assert nor imply that you should make ALL of your Queue instances bounded -- that would be silly indeed. But the ability to make SOME Queue's bounded, and still handle them without fuss, IS important in a vast enough number of cases that ruling this possibility out is a serious didactic mistake, IMHO. > And as I said, they push part of the problem to some other place in the > design, which may or may not be a good thing. In particular, when preparing work-requests is part of the design's task (e.g. by analyzing pieces of a huge existing file), a bounded Queue can simply and without problems do some appropriate balancing within the system between the amount of resources devoted to preparing work requests, and the amount devoted to processing them. It's as simple as that! >>bad way to teach: everything must be kept as simple as possible, >>*but no simpler than that*. > > Is it my turn to retort with a Monsieur de La Palice allusion? Perhaps, but this is a straight quote from Albert Einstein, of course, therefore you should take the matter up with him... Alex From aleax at aleax.it Tue Sep 24 03:40:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 07:40:05 GMT Subject: confusion about opening files References: Message-ID: Arief wrote: [ I'm putting last things first here...:-) ] > I hope it would help you. Any correction is welcomed ... No corrections -- just a few extra tidbits... > The os.open is os syscall (system call). It is used to open file, fifo, > device, etc in UNIX or Linux environment (I don't know about MS Windows). On Windows, Visual C++'s runtime libraries simulate the Unix/Linux/BSD system calls open / read / write / etc to some extent, basically to ease porting programs originally written for Unix &c. > The built in function: "open" uses c function "fopen". It is a buffered > version of os syscall "open" implementation. You should use appropriate You can, if you wish, open a file in unbuffered mode, too. > function for further operation too, for example: > > fname = '/tmp/a.txt' > f = open(fname, 'w') f = open(fname, 'w', 0) gives you an unbuffered file object f. > It is "not guaranteed" that as soon as you complete the f.write call, the > file is written with data you've feed. Because it is a buffered operation. > So to assure the OS to write your text immediately, you should do this: > > fname = '/tmp/a.txt' > f = open(fname, 'w') > f.write('this is only example\n') > f.flush() # flush buffered data for previous write operation > f.close() No need to flush right before closing, ever -- close flushes all that needs to be flushed. No need to flush if you open the file in unbuffered mode. With unbuffered files, or frequent flushing, I/O performance may degrade. Flush, and unbuffered files, ASK the OS to please, please write the data out -- but not all OS's comply. A traditional problem with DOS and related systems (I'm pretty sure it still was in Windows/98) is that the OS _doesn't_ comply with your kind request: if your program crashes without closing files, the files may end up empty even though you wrote and flushed repeatedly. The only "cure" (HA!) to this horrid situation was to *CLOSE AND REOPEN FOR APPEND* such files periodically (talk about performance being degraded...!!!). I hope (but don't know for a fact) that there are no such horrid issues with current OS'es such as Win/XP. Alex From user at domain.invalid Fri Sep 6 18:35:55 2002 From: user at domain.invalid (ryan) Date: Fri, 06 Sep 2002 22:35:55 GMT Subject: old ODBC module Message-ID: Does anyone know where I can find the old free odbc module? Not the mxODBC module, but the other (apprently not very well supported) one. I've been looking for a while without success. Thanks! ryan. From Chris.Barker at noaa.gov Wed Sep 18 14:42:11 2002 From: Chris.Barker at noaa.gov (ChrisBarker) Date: Wed, 18 Sep 2002 11:42:11 -0700 Subject: don't understand error message References: Message-ID: Manuel Hendel wrote: > if domainfield in domain: > domainlines.append(line) > [....] > > This should work if the domainfield and domain got the following > values, shouldn't it? > > domainfield = 1234.ab.cdef.de > damain = 1234.ab.cdef.de Nope. the "in" operator looks for an itme in a sequence. a string is a sequence of charactors, so you can only do something like: if 'f' in 'a long string' but not: if 'this' in 'a long string' what you want is one of the string methods: if domain.find(domainfield) >= 0 : domainlines.append(line) string.find() returns the index of the substring if it finds it, and -1 otherwise. Since 0 is a valid index (and so is -1) you have to check if the index >= 0 to see if it is found. -Chris -- Christopher Barker, Ph.D. Oceanographer NOAA/OR&R/HAZMAT (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception Chris.Barker at noaa.gov From gerhard.haering at gmx.de Sun Sep 1 11:47:48 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 1 Sep 2002 15:47:48 GMT Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: Robert Oschler wrote in comp.lang.python: > [Glyph said:] > "One of the eye-popping cool features of Python is the ability to > change code and have existing instances update to use the new > methods automatically. " > > Can someone point me to a code snippet shows how to do this? >>> class Foo: pass ... >>> foo = Foo() >>> foo.bar() Traceback (most recent call last): File "", line 1, in ? AttributeError: Foo instance has no attribute 'bar' >>> def bar(self): print "bar" ... >>> Foo.bar = bar >>> foo.bar() bar >>> -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From skip at pobox.com Tue Sep 3 18:36:41 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 3 Sep 2002 17:36:41 -0500 Subject: Would you like a Snobol pattern matcher? (Re: Making regex suck less) In-Reply-To: References: <3d725881.345921@news.t-online.de> <3D740DFC.1040009@something.invalid> Message-ID: <15733.14713.557144.930672@12-248-11-90.client.attbi.com> John> One of the things Perl has right now is the ability to use spaces John> within regular expressions via a suffix flag. In Perl 6, this will John> become standard, and will include the ability to include comments! Python also supports that with the re.VERBOSE flag. Skip From neal at metaslash.com Tue Sep 3 22:27:47 2002 From: neal at metaslash.com (Neal Norwitz) Date: Wed, 04 Sep 2002 02:27:47 GMT Subject: how do i know i built python --with-threads References: Message-ID: On Tue, 03 Sep 2002 20:22:09 -0400, Mark McEahern wrote: > Suppose somebody else installed python on my system--e.g., my evil > twin--and I wanted to determine whether the python was built like so: > > ./configure --with-threads --without-pymalloc > > How would I do it? For threads, you can probably do: >>> import sys >>> print 'thread' in sys.builtin_module_names pymalloc is off by default. The only way I can think of is to do an nm on the executable and see if there are any pymalloc symbols: nm python | grep -i arenabase Neal From eagle at unicode.cz Wed Sep 4 06:11:49 2002 From: eagle at unicode.cz (Jirka 'Eagle' Novak) Date: Wed, 04 Sep 2002 12:11:49 +0200 Subject: Why Python? References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 | I.e.: first try to make your programming needs clear, and then you can | evaluate advice on which programming language to use. | | Cheers, I'm afraid one cannot solve everything with only one language. - -- Jirka 'Eagle' Novak registered linux user #173581 E-Mail: eagle at unicode.cz ICQ: 46044619 HomePage: http://seal.unicode.cz/~eagle/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6-2 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAj113GQACgkQ3C/LHJbMZlKVugCgpHuScHt9IhJiljSPj3dTrMDH Gz0An1tn20rWUGyXV+zKC0bDKjVguxk0 =ME+3 -----END PGP SIGNATURE----- From mertz at gnosis.cx Thu Sep 26 00:20:33 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Thu, 26 Sep 2002 00:20:33 -0400 Subject: a python puzzle References: <3D9284CF.2B1161F2@alcyone.com> Message-ID: |the fact that it was mostly Python code would have |likely skewed the letter frequencies, since Python keywords, modules, |and builtin names appear more frequently in Python code than general |user-chosen identifiers; the letter frequency of the code would be |biased against the letter frequency of the common "words" in Python, |which is likely to be somewhat different from English as a whole. I wonder about that. Python reserved words (and pseudo-reserved names) are all rather ordinary English words. I have a hunch that their letter distribution falls pretty close to that of English prose. Of course, you'd have to decide how to weight things. If you merely did a histogram on a list of keywords, you might get a somewhat different pattern than if you checked actual scripts (with the comments and variable names removed). For example, most scripts have just a few 'import's at the top, but a whole bunch of 'if's 'for's and 'in's scattered throughout the body. Maybe I'll try an experiment. Yours, Lulu... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From jepler at unpythonic.net Sun Sep 15 18:06:25 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sun, 15 Sep 2002 17:06:25 -0500 Subject: Popup menu won't hide on Linux In-Reply-To: References: Message-ID: <20020915170616.A8221@unpythonic.net> Using menu.tk_popup() instead of menu.post() takes care of grab & other details. However, this seems to unpost the menu as soon as the button is released. Jeff From manuel at hendel.net Tue Sep 17 05:44:10 2002 From: manuel at hendel.net (Manuel Hendel) Date: Tue, 17 Sep 2002 11:44:10 +0200 Subject: don't understand error message In-Reply-To: References: Message-ID: <20020917094410.GF23629@partagas.as.de.cw.net> On Tue, Sep 17, 2002 at 09:12:06AM +0000, Duncan Booth wrote: > It simply means that at least one line of your file doesn't have 4 fields > after you have finished your processing. If the line only has two "|" > characters in it, then you will only get three fields which you can access > with indices 0 to 2. Trying to use an index out of range for a list will > produce this error. > > Try sticking a "print fields" line just before the if statement, the last > line printed will show you which line didn't match. My script already changed a little bit, I tried to fix it by my self, but it seams, that I just moved the error. How would you check the lines for the number of fields? Actually, I think I found that problem. I forgot some "---|--|--" at the end. But I already got a new one. [....] if domainfield in domain: domainlines.append(line) [....] This should work if the domainfield and domain got the following values, shouldn't it? domainfield = 1234.ab.cdef.de damain = 1234.ab.cdef.de But I get this error message: TypeError: 'in ' requires character as left operand Manuel -- A beautiful man is paradise for the eyes, hell for the soul, and purgatory for the purse. From kingprad at mail.com Wed Sep 25 11:47:40 2002 From: kingprad at mail.com (Carl) Date: 25 Sep 2002 08:47:40 -0700 Subject: general thoughts References: Message-ID: <668b76ce.0209250747.1b764286@posting.google.com> I've had the same problem from time to time in my programming explorations of the last few years. One of my interests is language, which you mentioned as your field of study. I played for a long time with some fun language stuff - no real scientific value, but interesting, fun, not difficult to understand, and let me explore lots of ways of doing things. I decided to work on the idea that given enough time, monkeys could randomly reproduce Shakespeare. I thought it would be fun to simulate the monkeys statistically. First I wrote a program to read in a text file and calculate the percentage frequency of each character, then use random number generator to generate text. The larger the text, the 'more correct' distribution of letters (28 characters from 26 letters, space, and apostrophe), so it would read in e-books by Poe, Dostoevsky, etc (Shakespeare after removing plays' character-cue lines like 'HAMLET: blah blah' so the cues wouldn't warp the frequencies. Then I went to a second-order analysis, calculating frequencies for each 2-letter group, 'aa, ab, ac, ..., th, ... zz' and generating from that. That produced much more valid output, as in more english words, better spacing and such. At third level groups (called it third order) it produces mostly words, occasional valid short phrases and such. Of course the interesting thing is trying different authors because the output is recognizable as a particular author's. Similarly other languages (german, french, etc) are recognizable in first order, but in higher orders produce just as interesting output as teh english - language is irrelevant, because words are built on letter frequencies. Of course, at higher order you get sentences and all sorts of interesting things out. The statistics can be used for author-identification, encryption, test compression, and all sorts of things. There is a measure of entropy in language (not real sure what it means) that can be taken and compared as well. Really neat project and fun programming, because it produces real results, encourages repeated optimization tests. After I had the basic operations going I had fun building a menu application around it with all sorts of tools, results display, automation, etc. great stuff. this was all in QBasic, but I'm eventually going to move it to Python. Also I have the analysis engine written in C that I will probably call, as it is much faster than QBasic or python for the actual text processing. but python is fast enough for up through 4th order. I bet you'd like something like this. It will probably give you ideas for other projects as well. Carl From ruediger.maehl at web.de Tue Sep 10 03:47:43 2002 From: ruediger.maehl at web.de (Rüdiger Mähl) Date: 10 Sep 2002 07:47:43 GMT Subject: Interrupting Python References: Message-ID: "Bob Easton" wrote in news:yz5e9.4237$rU2.145619 at news4.srv.hcvlny.cv.net: > I have a script that can run, accessing network resources, for several > days. Since the script does not normally need keyed input, exception > processing does not raise the keyboard exception until after the > program ends normally. I would like to be able to interrupt if from > the keyboard, but have not learned the trick. How can I do this? Hi Bob, you are perhaps looking for this: # ===== import time import atexit import signal CONTROL_C = False def program_exit(): # clean up before exiting if necessary print "Exiting application" def ctrlCHandler(*whatever): global CONTROL_C CONTROL_C = True print print "Interrupt caught! Please wait..." print # You must check CONTROL_C in your program signal.signal(signal.SIGINT, ctrlCHandler) # optionally, if you need clean up actions atexit.register(program_exit) # do your task while 1: print "Waiting for Control-C" time.sleep(2) if CONTROL_C: break print "Finished" # ===== HTH, R?diger From david.abrahams at rcn.com Fri Sep 20 11:29:36 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Fri, 20 Sep 2002 11:29:36 -0400 Subject: [newbie] Calling Python from C++ References: <8L5i9.841$Ew4.62552@newsfep2-gui> <3D8B3EA0.6050500@thinkware.se> Message-ID: "Magnus Lyck?" wrote in message news:3D8B3EA0.6050500 at thinkware.se... > Morfeas wrote: > I'm really as clueless as you are about this, but as far > as I understand, there are better tools than SWIG to > connect Python with C++. SWIG is really a C thing rather > than a C++ thing, right? > > Boost and CXX comes to mind. See > http://www.thinkware.se/cgi-bin/thinki.cgi/UsingPythonWithOtherLanguages While I appreciate the plug and I do think Boost.Python is a great solution for C++, SWIG has evolved since I first did my analysis and it understands a lot more of C++ than it used to, though it is still missing the ability to instantiate templates. The Boost comparisons page is woefully outdated and I've been waiting for David Beazley to write a new blurb for SWIG. -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From rgkindya at yahoo.co.in Sat Sep 7 21:18:10 2002 From: rgkindya at yahoo.co.in (rgkindya) Date: 7 Sep 2002 18:18:10 -0700 Subject: gettting input in a python embeded GUI app ... Message-ID: Dear Newser, I'm a newbie for python. I wish to embed Python interpreter into my vc++ GUI app(for ms-windows only). when executing input statements (eg raw_input()) , in pythonwin environment (activepython) , it gets input using a new small input window, in IDLE , it gets input in its own window (next line). please help me to do these two type of inputs in my embeded GUI app. my app is only GUI , there is no console mode. please debug my engliz bugs ... From jwold at min.midco.net Tue Sep 24 20:53:08 2002 From: jwold at min.midco.net (Jarrett L Wold) Date: Tue, 24 Sep 2002 19:53:08 -0500 Subject: PyXML Building on OS X? References: Message-ID: Thanks Martin! I just opted to install YDL 2.3, I have been meaning to move to Linux for some time now. I apologize for not testing that out for you, however I'm liking Linux much better ;) Martin v. Loewis wrote: > Jarrett Wold writes: > >> extensions/expat/lib/xmlparse.c:3056: warning: `regparm' attribute >> directive ignored > > I see. Please edit internal.h to replace > > #if defined(__GNUC__) > #define FASTCALL __attribute__((stdcall, regparm(3))) > #elif defined(WIN32) > #define FASTCALL __fastcall > #else > #define FASTCALL > #endif > > with > > #define FASTCALL > >> cc -L/sw/lib -bundle -flat_namespace -undefined suppress >> build/temp.darwin-5.5-Power Macintosh-2.2/pyexpat.o >> build/temp.darwin-5.5-Power Macintosh-2.2/xmlparse.o >> build/temp.darwin-5.5-Power Macintosh-2.2/xmlrole.o >> build/temp.darwin-5.5-Power Macintosh-2.2/xmltok.o -o >> build/lib.darwin-5.5-Power Macintosh-2.2/_xmlplus/parsers/pyexpat.so >> -flat_namespace >> /usr/bin/ld: -undefined: unknown argument: -lbundle1.o >> error: command 'cc' failed with exit status 1 > > Very strange. Can you please invoke > > cc -L/sw/lib -bundle -flat_namespace -undefined suppress > build/temp.darwin-5.5-Power Macintosh-2.2/pyexpat.o > build/temp.darwin-5.5-Power Macintosh-2.2/xmlparse.o > build/temp.darwin-5.5-Power Macintosh-2.2/xmlrole.o > build/temp.darwin-5.5-Power Macintosh-2.2/xmltok.o -o > build/lib.darwin-5.5-Power Macintosh-2.2/_xmlplus/parsers/pyexpat.so -v > > on the command line, and report the output? > > Regards, > Martin From cbbrowne at acm.org Sat Sep 21 09:40:34 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 21 Sep 2002 13:40:34 GMT Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> <7xn0qcfafp.fsf@ruckus.brouhaha.com> <7xwupf52jx.fsf@ruckus.brouhaha.com> Message-ID: A long time ago, in a galaxy far, far away, Paul Rubin wrote: > Christopher Browne writes: >> REALITY CHECK for a moment. >> >> What do you think A Real Live bank uses to compute interest? > > If I had to guess, I'd guess they use floating point. > > I do know that financial modelling software I worked on that was > sold to banks used floating point. Also, spreadsheets use floating > point. > > But it's possible (likely even) that some bookkeeping applications > use BCD. One that I worked on actually used exact, multi-precision > rational arithmetic, but I think that's unusual. Ask yourself: Q: When did banks start automating their operations? (A: Roughly the 1960s.) Q: What were the major language choices at that time? (A: COBOL, FORTRAN, PL/1) Q: Did they use FORTRAN for all their applications? (A: No, that's for the science people. Who would do financial apps in FORTRAN?.) Q: What sorts of programmers were they looking for to do Y2K remediation work about three years ago, in great hordes? (A: COBOL, PL/1) Q: Might these questions suggest any reason to expect that they might have been using languages where money, which is their raison d'etre, might have been expressed in BCD? Can you suggest languages that would be widely used in an MVS environment that WOULDN'T include BCD arithmetic? I would expect that even C for S/390 would include a BCD arithmetic language extension, because BCD gets used /everywhere/ on MVS-based systems, and that is the classic OS platform of banking. -- (concatenate 'string "aa454" "@freenet.carleton.ca") http://cbbrowne.com/info/advocacy.html "Not only do I strongly recommend against using PC NFS, but I'm willing to bet you won't find anyone willing to code a free PC NFS client. I bet even Richard Stallman would charge for a PC NFS client." -- Steve Conley From news at nospam.eml.cc Wed Sep 25 10:24:23 2002 From: news at nospam.eml.cc (Mahesh Padmanabhan) Date: Wed, 25 Sep 2002 14:24:23 GMT Subject: List/Tuple bug or feature? References: Message-ID: <87ofamgnbh.fsf@nospam.eml.cc> "Mark McEahern" writes: > You don't really say much about how you generated this large list, but one > idea would be to automate the process of generating it and/or fix whatever > bug led to the omission of the comma. > > I don't have anything more clever than that to offer; perhaps someone else > does. > It is simply a list of constants so I could not generate it automatically. I then use this list to filter out one element of the list using the builtin filter function. I don't think I can break down the list so that I can view missing commas easier because all constants seem to logically group together. Something like this: constantList = [1,2,3,4,5] filteredList = filter(some_function, list) Thanks. -- Mahesh Padmanabhan ------- Replace nospam with prana to email me. From marklists at mceahern.com Sat Sep 14 16:07:24 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 14 Sep 2002 15:07:24 -0500 Subject: newbie-question: abstract classes In-Reply-To: <3D839852.2060405@snafu.de> Message-ID: > I want to create an abstract class but it doesn't work. __init__ doesn't return. // m - From dsavitsk at e-coli.net Fri Sep 13 10:41:27 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 13 Sep 2002 14:41:27 GMT Subject: Newbie Looking for direction References: Message-ID: "Stephen Ferg" wrote in message news:b16e4ef7.0209130506.457b1db3 at posting.google.com... > > So far it seems like I'm a long way away from being able to be productive > > with Python... > > This might help in getting you productive quickly: > > http://www.ferg.org/easygui/ is there a license associated with this? is it public domain? From chris.gonnerman at newcenturycomputers.net Mon Sep 30 09:10:41 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 30 Sep 2002 08:10:41 -0500 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xelbcgo56.fsf@ruckus.brouhaha.com> <7x65woks0i.fsf@ruckus.brouhaha.com> <7xit0oj859.fsf@ruckus.brouhaha.com> Message-ID: <001301c26882$c8638e00$ba01010a@local> ----- Original Message ----- From: "Paul Rubin" > "Chris Gonnerman" writes: > > > With decimal arithmetic, you get $2.97 the first way and > > > $3.00 the second way. > > > > Excellent example, wrong focus. The business user (in this > > case, the retail store owner/manager) would define which > > method, and which results, are right. The second mode is > > the "canonical" way in the manual system, but lately I've > > realized that many (most?) retail POS systems can do it > > "both" ways, handling single items by a variation of method > > 1 which gives answers consistent with method 2. > > > > I'm glad I didn't have to write and debug that code. > > I'm really skeptical that any "business user" can specify a > set of rules that gets all this stuff straight for a complex > business involving cents-off coupons, percentage advertising > discounts, etc. Usually, in the "canned" systems I've seen, those 3 for a buck deals are supported by allowing three to five decimal places rather than just two for amounts. Results come out much as you are expecting there. It seems that what you are finding fault with (IMHO) is not decimal arithmetic, it's *fixed* decimal arithmetic. What I am finding fault with isn't floating point arithmetic, it's floating *binary* point arithmetic. Later today (tonight probably) I plan to post a test module comparing the very simple "tax" calculation I've been using as an example. My code isn't quite clean enough to show yet, and given the nature of this discussion I want it real clean. However, here are some interesting results so far: 5% of $0.50 = 0.02 decimal, 0.03 float 5% of $0.70 = 0.04 decimal, 0.03 float 6% of $0.75 = 0.04 decimal, 0.05 float 9% of $0.50 = 0.04 decimal, 0.05 float Sell a lot of fifty-cent items in a 5% tax district, and you'll wind up with a large discrepancy in your sales tax. Of course, it'll be long rather than short... just watch out for those seventy-five cent items. If you sell exactly as many $0.75 as $0.50, you're OK... In other words, it's just not good enough. Now, if you can point me at a *floating decimal* math library, THAT would be COOL. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From stephen at theboulets.net Sat Sep 7 02:53:31 2002 From: stephen at theboulets.net (Stephen Boulet) Date: Sat, 07 Sep 2002 01:53:31 -0500 Subject: py2exe and a single exe file? References: <3D792351.3070008@motorola.com> Message-ID: Thanks for both your replies. After thinking about it, I can live with the extra files. ;) -- Stephen I wrote: > I'm trying to get py2exe to work for me, and I must be doing something > wrong. > > I have a script that uses easygui (which uses Tkinter) and Numeric. It > also imports a small module from the same directory that the script > resides in. > > I try building it like this: > > python setup.py py2exe -d N:\ -i easygui > > It builds and runs, but only with the other stuff in the build directory > with the generaged exe. The other stuff is: > > tcl directory containing tcl8.3 and tk8.3 directories > _numpy.pyd > _sre.pyd > _tkinter.pyd > multiarray.pyd > umath.pyd > > What I would like to accomplish is just having a single exe file lumping > everything together. Is this possible? > > -- Stephen From mikkelfj-anti-spam at bigfoot.com Sun Sep 29 07:46:55 2002 From: mikkelfj-anti-spam at bigfoot.com (MikkelFJ) Date: Sun, 29 Sep 2002 13:46:55 +0200 Subject: 'File name' is not recognized as an internal or external command, operable program References: <576c1752.0209280718.331fe456@posting.google.com> Message-ID: <3d96e77f$0$69067$edfadb0f@dspool01.news.tele.dk> "mike henley" wrote in message news:576c1752.0209280718.331fe456 at posting.google.com... > rsrchstr at hotmail.com (mike henley) wrote in message news:<576c1752.0209271443.1ea61518 at posting.google.com>... > (p.s. advising the poster to start a new command > windows for the environmental effects to take place is not a good > reply when the poster said he already restarted the machine, but > thanks anyway to those who suggested it for their wish to help :):) ) Actually that wasn't stated, on the contrary it was hinted that it might help to restart. Mikkel From skip at pobox.com Tue Sep 17 10:53:18 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 17 Sep 2002 09:53:18 -0500 Subject: Modify AD key fields programmatically via ADSI or VB Script In-Reply-To: <1824301.1032265587@dbforums.com> References: <1824301.1032265587@dbforums.com> Message-ID: <15751.16862.454609.277008@12-248-11-90.client.attbi.com> MPS> I am new to ADSI and was wondering if anybody knows a way to modify MPS> AD key fields (i.e./ DN) programmatically via ADSI or VB Script? MPS> Here is the exact scenario: ... [ snip ] ... MPS> Thanks a million for any help - MPS Maybe post to an ADSI or VB Script group of some sort? It's not obvious to me that this has anything to do with Python. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From timr at probo.com Wed Sep 25 02:07:11 2002 From: timr at probo.com (Tim Roberts) Date: Tue, 24 Sep 2002 23:07:11 -0700 Subject: Strange python and cgi! References: Message-ID: "CheapSkate" wrote: >Hi I made a cgi script in python and successfully compiled it. > >the script is some thing like this > >#! usr/lib.../python > >import ... >def kickass(xxx) >... > >... >print "
"
>kickass(xxx)
>print "
>... > >when I go to the webpage, it stops halfway and in "view source: it only show >the code till the open "pre". >however when I output it to an html file: >python nameofscript.cgi >app.html >.... >app.html works fine just as I want it to be. > >What seems to be the problem here. Does "kickass" read or write any files? Remember that the web server runs as a special and unprivileged user. If you are running Linux, check the log file at /var/log/httpd/error-log. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bokr at oz.net Mon Sep 9 19:26:48 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Sep 2002 23:26:48 GMT Subject: a re question References: Message-ID: On Mon, 09 Sep 2002 16:10:39 -0400, Rajarshi Guha wrote: >Hi, > I have a file with lines of the format: > >001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23 >001 Xya FGh 143557789 7 100 09/05/2002 20:23:23 > >I am trying to extract the 9 digit field and the single digit field >immediatley after that. > >When I use Visual Regexp to try out the regexp > >(\d{9,} {3,}\d) > >it highlights the 2 fields exactly. > >But when I use the following Python code I get None: > >>> s='001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23' >>> p = re.compile(r'(\d{9,} {3,}\d)') >>> print p.match(s) >>> None > >Could anybody point out where I'm going wrong? > >Thanks, >>> import re >>> s='001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23' >>> p = re.compile(r'(\d{9,} {3,}\d)') >>> print p.match(s) None >>> print p.search(s).groups() ('123456789 7',) But if you want them separately, >>> p = re.compile(r'(\d{9,}) {3,}(\d)') >>> print p.search(s).groups() ('123456789', '7') Or as actual integers, >>> map(int, p.search(s).groups()) [123456789, 7] match starts at the beginning of the string. See http://www.python.org/doc/current/lib/matching-searching.html so for your pattern you might be able to prefix ".* " (i.e., anything ending in a space before your 9 or more digits etc), e.g., >>> p = re.compile(r'.* (\d{9,}) {3,}(\d)') >>> print p.match(s).groups() ('123456789', '7') where s is still >>> s '001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23' BTW, you did want to get extra digits beyond 9 and *no* extra digits in the second single digit number, right? E.g., >>> s='001 Abc D Efg 1234567890 70 100 09/05/2002 20:23:23' incl--^ ^--not incl >>> p = re.compile(r'(\d{9,}) {3,}(\d)') >>> print p.search(s).groups() ('1234567890', '7') ^ ^--single digit guaranteed irresp of next Regards, Bengt Richter From gtasker at allenbrook.com Fri Sep 6 08:24:59 2002 From: gtasker at allenbrook.com (Tasker,George) Date: Fri, 6 Sep 2002 07:24:59 -0500 Subject: What database should I use Message-ID: MS Access works. Fox Pro has not been tested that I know of. If you are using VC6 Professional/Enterprise, along with an MSDN subscription, you can get MSDE (the stripped down version of SQL Server 7). g -----Original Message----- From: A [mailto:printers at sendme.cz] Sent: Thursday, September 05, 2002 9:21 AM To: python-list at python.org; tutor at python.org; activepython at listserv.ActiveState.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: What database should I use Hello, I am going to program a small application (in Python and wxPython) which consists about 2000 - 3000 records . Can you please recommend which database is the best for that. I use Windows. Maybe MS Access or FoxPro or MySQL or better? I want to keep the program as small as possible. Thanks Ladislav _______________________________________________ wx-users mailing list wx-users at lists.wxwindows.org http://lists.wxwindows.org/mailman/listinfo/wx-users From aleax at aleax.it Mon Sep 23 03:08:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 23 Sep 2002 07:08:53 GMT Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> Message-ID: <96zj9.150553$pX1.5399868@news2.tin.it> Greg Ewing wrote: > Courageous wrote: > >> One should use spaces >> and not tabs in Python code. Otherwise, any python file where >> tabs and spaces are mixed is also a choice of which indentation >> level other viewers of the code MUST use in their editors. > > If you use spaces only, you're also choosing how other > people will see it in their editors (unless they're > willing to use a tool to re-indent it). > > Using *tabs* only is the only way to get truly > preference-independent indentation. ...unless other people use tools that do NOT let them change the ways tabs are displayed, and that way is intolerably incompatible with your use of tabs. Both Outlook Express and KDE's KNode (in KDE 2.2 at least -- that's what I'm using today) are good examples of such tools that are in everyday use by many people. The amount of space displayed for a leading tab is ZERO. Just imagine how neat this makes reading Python code posted to this newsgroup, when the poster uses tabs there (for example because they use tabs normally in their on-disk sources, and copy and paste is the best way to post some snippet). That's just one example (well, two, since KNode and OE are completely separate programs) -- anybody who prints your source code is similarly at the mercy of their printer's drivers (many of which don't allow tabs to be changed), etc. Unless you KNOW all the tools that will ever be used to look at your source code -- which basically means, you will never distribute your source code outside of a small group under your strict control, never post any snippet thereof to c.l.py to ask a question nor to aswer it, etc -- I consider using tabs to be anti-social and a massive annoyance. Follow the style guide and use 4 spaces per indentation level, if you like to think of yourself as a 'good citizen', rather than a missionary who wants to force everybody to read news with Emacs (or whatever other highly-flexible tool of choice). Alex From duduca007 at yahoo.com Tue Sep 24 18:04:07 2002 From: duduca007 at yahoo.com (Carlos Moreira) Date: Tue, 24 Sep 2002 15:04:07 -0700 (PDT) Subject: PyBrenda Updates and some Problems In-Reply-To: <20020924213528.79691.qmail@web11403.mail.yahoo.com> Message-ID: <20020924220407.2832.qmail@web11402.mail.yahoo.com> Ok, I found the problem again...:)))) for curious people: Brenda.py: 285 line host = socket.gethostbyname( socket.gethostname() ) Of course, primarily, this was for my personal use.... and before show this code for people I must to talk with PyBrenda's author.... []'s Cadu Moreira KaduSoft President ----------------------- [......] --- Carlos Moreira wrote: > Hi, > > I did some updates in PyBrenda for my particular > use: > > Brenda.py > old: sock.connect(host, port) > new: sock.connect(host, port) > > old: sock.bind(host, port) > new: sock.bind((host, port)) > > old: command = ('rsh ' + > self._nodelist[self._nodeIndex] + ' python ' + > tmpFile) > new: command = ('ssh ' + > self._nodelist[self._nodeIndex] + ' $PYTHON/python ' > + > tmpFile) > > Well, I need real parallelism (as you can see), so, > first of all, I performed tests/test3.py, that > result > in a "error message" below: > > :ts got conn 0x81b3594> from ('10.16.165.38', 34043) > :tcr: command is ssh glover /home/pgs/carlos/py > /home/pgs/carlos/.PyBrenda.tmp/@13190.0 > :ts: > pend (in) ('workerDone',) > carlos at glover's password: > Traceback (most recent call last): > File "/home/pgs/carlos/.PyBrenda.tmp/@13190.0", > line > 14, in ? > c = Brenda.TupleClientRsh('isere', 2012) > File > "/home/pgs/carlos/python/Python-2.2/lib/python2.2/site-packages/Brenda.py", > line 387, in __init__ > TupleClientCds.__init__(self, host, port) > File > "/home/pgs/carlos/python/Python-2.2/lib/python2.2/site-packages/Brenda.py", > line 297, in __init__ > self._conn = self._connectTo(host, port) > File > "/home/pgs/carlos/python/Python-2.2/lib/python2.2/site-packages/Brenda.py", > line 313, in _connectTo > sock.connect((host, port)) > socket.gaierror: (-2, 'Name or service not known') > > I need your help. Do I some mistake? What I can do > for > repare this and configure PyBrenda correctly? > > []'s > > Cadu Moreira > KaduSoft President > ----------------------- > [......] > > __________________________________________________ > Do you Yahoo!? > New DSL Internet Access from SBC & Yahoo! > http://sbc.yahoo.com > > -- > http://mail.python.org/mailman/listinfo/python-list __________________________________________________ Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! http://sbc.yahoo.com From mcfletch at rogers.com Thu Sep 26 17:21:39 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 26 Sep 2002 17:21:39 -0400 Subject: Silly question about ungzipping a file References: <7396d2b2.0209261311.1fdd2d3a@posting.google.com> Message-ID: <3D937A63.90904@rogers.com> Try something like (untested): chunk = 4096*1024 # 4MB chunks, play with this value to suit myFile = gzip.open( 'blah.gz' ) # this is binary if I recall correctly outFile = open( 'blah','wb') # note wb mode for windows machines! data = myFile.read( chunk ) while data: outFile.write( data ) data = myFile.read( chunk ) outFile.close() myFile.close() HTH, Mike Lemniscate wrote: > Hi everyone, > > This may be a ridiculously easy question, but I've kind of hit a wall > and I was wondering if I am just missing something. I want to > automate the retrieval and unzipping of a *.gz file. The issue is > that the file, when it is unzipped, usually has a size somewhere in > the range of 128MB. Occassionally, I get memory errors when I try to > run it. Here is a quick idea of what I am doing... > > >>>>import gzip >>>>myFile = gzip.open('LL_tmpl.gz') >>>>file('output.txt', 'w').write(myFile.read()) >>>> >>> > > Now, is there any way to do this so that less memory is used? I mean, > if I wanted to do some processing on the resulting output file, I > would use xreadlines or something like that to keep memory consumption > to a minimum. Is there something roughly equivalent that I am not > noticing in the gzip documentation. Let me also say that I have tried > the following as well: > > >>>>myFile = gzip.open('LL_tmpl.gz') >>>>fout = file('output.txt', 'w') >>>>while myFile.readline(): >>> > ... fout.write(myFile.readline()) > ... fout.write('\n') > ... > >>>>fout.close() >>>>myFile = gzip.open('LL_tmpl.gz') >>>>fout = file('output2.txt', 'w') >>>>while myFile.readline(): >>> > ... fout.writelines(myFile.readline()) > ... > >>>>fout.close() >>> > > > These do solve my memory problem, but there are other issues. First > of all, my CPU gets pegged and it takes FOREVER (okay, not forever, > but about ...let me test real quick... at least 4-5 times as long, and > my computer is pretty much useless during that time (side note: can > you tell I am working on a woefully underpowered machine?)). Is there > something in-between that anybody can think of? The other, and much > more immediate, issue is puzzling to me. It seems that the resulting > files from the code are only about 65MB (64.7 to be exact) versus > 129MB. I'm sure I'm just missing something simple, but why is that? > Thanks for your time. > > Lem -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From sebastian-huber at web.de Fri Sep 13 01:49:47 2002 From: sebastian-huber at web.de (Sebastian Huber) Date: Thu, 12 Sep 2002 22:49:47 -0700 Subject: Callback function call from C++ Message-ID: <200209122249.47697.sebastian-huber@web.de> Hello, I want to install a Python callback function in a C++ extension module. Everything works as desired, but is it possible to get the argument list length and types of the function in advance. For example: PyCallable_Check( o) != 0 get the arglist and return 0 if not ok install the callback function At the moment I get an error at the first call if the arglist is not ok, and I want to avoid this. Ciao From thoa0025 at mail.usyd.edu.au Sun Sep 15 19:12:54 2002 From: thoa0025 at mail.usyd.edu.au (:B nerdy) Date: Sun, 15 Sep 2002 23:12:54 GMT Subject: raw post data Message-ID: how would i retrieve the raw post data in cgi python scripts ? cheers From anthony at computronix.com Mon Sep 30 23:27:02 2002 From: anthony at computronix.com (Anthony Tuininga) Date: Mon, 30 Sep 2002 21:27:02 -0600 Subject: redhat8 In-Reply-To: <87ofafxocv.fsf@flibuste.net> References: <873crr4fy6.fsf@flibuste.net> <87ofafxocv.fsf@flibuste.net> Message-ID: <1033442823.3504.0.camel@localhost> Yes. It is /usr/bin/python; Python 1.5 is history... :-) On Mon, 2002-09-30 at 13:35, William wrote: > Anthony Tuininga writes: > > > According to the release documentation: > > > > Python 2.2.1 is on the CD. > > great, but i would like to know if it's the default version, linked with > /usr/bin/python... > > -- > William Dod? - flibuste.net > http://wikipython.tuxfamily.org > -- > http://mail.python.org/mailman/listinfo/python-list From park997 at aol.comnotospam Wed Sep 18 10:53:32 2002 From: park997 at aol.comnotospam (Park997) Date: 18 Sep 2002 14:53:32 GMT Subject: Tkinter:select directory dialog? Message-ID: <20020918105332.00910.00007029@mb-ch.aol.com> Hi, I have written an application that reads in several data files located in a single directory. Currently the directory is hard coded in a module as a string variable. On other computers, the data may be located in other directories. Is there a Tkinter dialog for choosing a directory, but not picking a file to open or write to? An entry field could be OK, but that would involve typing in a path, and probably validity checking, etc. A nice graphical "choose a directory" Dialog would help. Does such a thing exist? Thanks, Wendell Cropper From b.maryniuk at forbis.lt Tue Sep 3 06:24:45 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 3 Sep 2002 12:24:45 +0200 Subject: code doesn't work: question In-Reply-To: <1551859543.20020903130305@is.lg.ua> References: <1551859543.20020903130305@is.lg.ua> Message-ID: <200209031224.45948.b.maryniuk@forbis.lt> On Tuesday 03 September 2002 12:03, Ruslan Spivak wrote: > Hello python-list user, > I want somebody to explain me why next code doesn't work: > > var = 5 > > if (tmp = var) == 5: # this is the error line > print "ok" > else: > print "error" You probably want other operator than '='. e.g.: if (tmp + var) == 5: pass Because the code: tmp = var ..is not a logical stuff and returns nothing. -- Regards, Bogdan "While preceding your entrance with a grenade is a good tactic in Quake, it can lead to problems if attempted at work." -- C Hacking From st03210 at student.uib.no Tue Sep 17 08:26:38 2002 From: st03210 at student.uib.no (Steinar Dragsnes) Date: Tue, 17 Sep 2002 14:26:38 +0200 Subject: File upload script Message-ID: <3D871F7E.C313ADD2@student.uib.no> Hi! I'm a complete newbe in python and have never written anything more advanced then the classical Hallo World example. I have already programmed an applet where users should be able to upload images and or other files from their local pc. This is of course not possible due to the applet security model (sandbox) in Java. But I can start a python-script from the running java applet which can do the actual file upload for me and save the file to a specific directory on the apache server. Since the applet that needs the information about what file has been uploaded into what node, I need a way to send back information to the applet calling the script. I wonder if this is possible at all? Usually scripts generate html-pages and call applets from there on they fly, with the right paranemer tag values. Is this possible when the applet is already running? Would it not destroy the applet context? If this is the case, a workaround could be to write the output from the script to a text-file. The information I need to write is sessionID, userID, nodeID and file name. This is a "hairy" solution, but the most important thing for me is a solution that works right now. My main problem is that I do not know how I can pass the parameters of type String; sessionID, userID and nodeID, from the appleten to the called python-script. I need to know how to write a function that will receive these parameters. The python script below is written by a colleague of mine, and he is now on a sick-leave....and I need to figure this out soon.... In the java code I call the upload.py script like this: java.net.URL url=new java.net.URL("http://"+ip+"/cgi-bin/upload.py"); applet.getAppletContext().showDocument(url,"_blank"); Below is the script that I need to rewrite so that it can take the parameters I mentioned above: Thanks in advance, Steinar Dragsnes. --------------------------- #!/usr/bin/python import cgi form = cgi.FieldStorage() print 'Content-type: text/html' print if not form: print """ File Upload

Upload an image.

""" elif form.has_key("fila"): item = form["fila"] if item.file: data = item.file.read() filnavn = item.filename filen1 = filnavn.split('\\') filen2 = filen1[len(filen1)-1] #filen2 = 'd.txt' open('/var/www/html/bilete/' + filen2,'wb').write(data) print """ File Upload File has been uploaded. """ print """

""" print cgi.escape(filen2) print '' ------------------------------------------ From martin at v.loewis.de Mon Sep 30 01:50:28 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Sep 2002 07:50:28 +0200 Subject: XMLRPC calls don't work in threads, or rather, they don't play well with others ! (help) References: <3D97D190.9030003@bcm.tmc.edu> Message-ID: Steve Ludtke writes: > Hi. I've been trying to write a python app that makes somewhat > time-consuming XMLRPC calls. I planned to have several calls going at > once using threads, but it seems like something in the XMLRPC client > code isn't releasing the python interpreter lock properly. This is unlikely. xmlrpclib does not use threads. I don't know what xmlrpclib_auth is, so all bets are off. If it doesn't use any threading facilities, either, blocking calls will occur eventually only in the socket read/write calls, which do allow other threads to run, and do release the interpreter lock properly. > Is there something I can do at the Python level to deal with this > issue ? I'd add print statements at all levels of the code, to see where exactly it is blocking. Regards, Martin From leithp at selector.com Sun Sep 15 11:27:01 2002 From: leithp at selector.com (Leith Parkin) Date: Sun, 15 Sep 2002 15:27:01 GMT Subject: regular expression help [port] References: Message-ID: <20020916012701.3e606886.leithp@selector.com> Here is what i use import re def valid(email): x = re.match("^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,3 }$", email); if x == None: return 0; else: return 1; Sorry about the formatting errors Leith On Sun, 15 Sep 2002 09:56:38 GMT ":B nerdy" wrote: > Greetings, this is a regular expression for an email address > "^[a-z0-9_]+@[a-z0-9\-]{2,}\.[a-z0-9\-\.]{2,}$" > > i wish to valid a variable against this string. would someone be so kind > to supply a few lines of code to do this? > > cheers > > -- It is Texas law that when two trains meet each other at a railroad crossing, each shall come to a full stop, and neither shall proceed until the other has gone. From flognat at flognat.myip.org Tue Sep 24 05:44:11 2002 From: flognat at flognat.myip.org (Andrew Markebo) Date: Tue, 24 Sep 2002 09:44:11 GMT Subject: Downloading huge files via urllib References: Message-ID: | response = urllib.urlretrieve(serverURL, 'run.log') | | However, I then get a MemoryError. Tracking down the source of the | error, I see the offending function in httplib: | | def makefile(self, mode, bufsize=None): | """Return a readable file-like object with data from socket. [...] | The returned object contains *all* of the file data | """ | | I think the problem is that bufsize argument that is ignored. Does Read the docs, and you will see "the bufsize argument is ignored" and "The returned object contains *all* of the file data", so it tries to squeeze in 20 megs there.. | anyone know if this is correct, and what I can do about it? I would | like to automate the process of downloading this file, but is it | possible? Maybe read directly with recv() from the [Fake]Socket instead of doing makefile.. And well this requires you probably to use httplib instead of urllib, shouldn't be any problems I think. Or maybe throw an eye at my implementation on the http-standard, should be able to chew https also, http://flognat.myip.org/hacks/ it is webification.tgz that might interest you. /Andy -- The eye of the beholder rests on the beauty! From skothal at versant.com Wed Sep 25 01:39:45 2002 From: skothal at versant.com (Sujata Kothalkar) Date: Wed, 25 Sep 2002 11:09:45 +0530 Subject: AIX5.1 python 2.1.3 download???????? Message-ID: <3D914C21.FBC5503E@versant.com> Hello, Where can I find the downloadable for python 2.1.3 for AIX 5.1. If there's no direct downloadable available, what procedure can be followed for building the sources and where can these sources be found? Thanx, --Sujata Kothalkar. From phoebe_1 at att.net Fri Sep 20 22:44:33 2002 From: phoebe_1 at att.net (Holden Caulfield) Date: 20 Sep 2002 19:44:33 -0700 Subject: Solaris 64 bit compilation Message-ID: Greetings, This is my first attempt at compiling Python v2.2.1 in *64bit* mode on a Solaris 5.9 system. I am using the Sun Compiler (the latest I do not remember the version). I am migrating a few of my apps (all developed on 64bit platforms) to Solaris, so I *need* the 64bit mode. But, it is failing miserably. It compiles *fine* in 32bit mode (the default), but it does me no good. As some of the extensions library that I have are 64bit. Before, I start hacking I thought I would give a query here and see if anyone had any success? Here are my preliminary results: - Flags used "-xarch=v9 -xcode=pic32". The first thing I get is the bail-out in "pyport.h": Where the #LONG_BITS != (8 * sizeof(LONG)) fails!!! So, I commented it out, first to proceed and see what happens. Most of them compiled fine except, I got some serious errors in the: fileobject.c file probably related to the LP64 model. I will try to add more info, when I get around to it. If anyone has successfully done this, I would appreciate if they can share the info. Thanks From fperez528 at yahoo.com Wed Sep 18 18:14:10 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 18 Sep 2002 16:14:10 -0600 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: Lee Gray wrote: > > Can someone point me to a good Python GUI app to demonstrate (other > than IDLE)? Why don't you look at MayaVi (http://mayavi.sourceforge.net)? It's very impressive, and runs both under Un*x and Windows. It's a great show of python's strenghts: use Tk for the GUI, Vtk for the heavy lifting (3d rendering) and python for all the logic elsewhere which isn't super intensive computationally. Cheers, f. From narnett at mccmedia.com Wed Sep 4 19:08:37 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Wed, 4 Sep 2002 16:08:37 -0700 Subject: Bind threads to addresses -- Windows & urllib? In-Reply-To: Message-ID: It's a machine with multiple IP addresses bound to one adapter. I want each spider thread to use a different address... -- Nick Arnett Phone/fax: (408) 904-7198 narnett at mccmedia.com > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Gerhard H?ring > Sent: Wednesday, September 04, 2002 10:41 AM > To: python-list at python.org > Subject: Re: Bind threads to addresses -- Windows & urllib? > > > Nick Arnett wrote: > > I can't see an obvious easy way to bind threads to IP addresses on a > > Win2K machine. I have a multi-threaded Web spider, which uses urllib to > > retrieve pages, and would like to bind each thread to a > different address > > on the machine, if possible. > > I'm not sure what you mean. This is a multithreaded HTTP client > app, right? > Do you have multiple network connections and want to use more than one? > > If yes, then that's an issue of configuring the routing on your computer > appropriately (if that is at all possible, I doubt it's easy). > > I'd also be surprised if you could saturate a 100 MBit link with a HTTP > spider. > > -- Gerhard > -- > http://mail.python.org/mailman/listinfo/python-list From klausman-un080902 at tuts.net Sun Sep 8 06:13:00 2002 From: klausman-un080902 at tuts.net (Tobias Klausmann) Date: 8 Sep 2002 10:13:00 GMT Subject: Python plugins Message-ID: Hi there, For an open source project that needs to be extensible by its users, I would like to create a plugin architecture. Mind you, I'm not trying to use Python as a plugin language only like XChat or Gnumeric do. Let me illustrate: I have a directory somewhere in PYTHONPATH (let's just assume it's in the CWD) that contains lots and lots of *.py files with a defined set of functions (or, at least one: register()). What I'd like to do now is being able to load these plugins at program start and reload them if I'd like to later. Problem is that the program has to figure out by itself what *.py files are there - and I have to make sure somehow that I get a grip on the loaded files. What I tried is this: I created a subdir called "pi" to hold the files and created a file __init__.py inside it. Code follows: from os import listdir modlist=[] def rel(): for fn in listdir(__name__): if fn != "__init__.py": if fn[-3:] == ".py": mod=fn[:-3] if mod not in modlist: exec("import %s"%mod) modlist.append(mod) else: exec("reload (%s)"%mod) return(modlist) Now I can just "import pi" and execute pi.rel() which in turn loads all the modules that are there ('cept the ones that only exist as pyc or pyo, but that's okay). But now I have two problems: first, I have no idea how to call, say pi.someplugin.dostuff(args) except constructing each and every call as a string and exec() it - which is both error-prone and awkward IMHO. Second, reloading just does not seem to work right as Python is too smart ;) for me: it knows all of them have been loaded. So I added the reload code above but to no avail. For testing purposes, I created a.py ... l.py containing this: print __name__ def register(): return ("I work for %s%s",__name__,__name__) I get the feeling that there is something fundamentally wrong with my approach. What would you do? Greets, Tobias From lbrannma at cablespeed.com Sat Sep 28 13:29:44 2002 From: lbrannma at cablespeed.com (Lance) Date: Sat, 28 Sep 2002 10:29:44 -0700 Subject: How to add recently edited files to IDLE? Message-ID: Hi All again, It would also be nice to add a list of recently edited files to the File menu in IDLE. Any suggestions would be appreciated. Thanks, Lance From aglyportREMOvethispart at nospam.yahoo.com Fri Sep 6 00:21:03 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Thu, 05 Sep 2002 21:21:03 -0700 Subject: Coredumps (Python 1.4) References: <3D7579F1.1090500@nospam.yahoo.com> Message-ID: <3D782D2F.20603@nospam.yahoo.com> Skip Montanaro wrote: > Anton> ... I coredump on this line ever since I linked with Electric > Anton> Fence memory debugging lib. Any ideas why? > > Not off the top of my head... > > Anton> This is with Python 1.4 on SCO. Any know issues with memory > Anton> allocation there? I'm building 2.2 now, but it will take a while. > > Give up on 1.4. It took me awhile (an hour or so) several months ago to get > Python 2.1 (I think) to build on SCO. You'll be better off solving 2.2 > build problems than struggling with what might be a bug in 1.4. > The problem was in my code. I've included a header before #include that had this define in it: #define DEBUG(a) { fprintf(stderr,"DEBUG: %s",a); } which caused the crashes, duh. Once I removed it my program stopped crashing. So, I'll keep 1.4 on SCO and simply wait for SCO to die off instead of wasting my time trying to get 2.2 to build on SCO. From grzegorz.rumatowskiNOSPAM at chello.at Fri Sep 13 04:14:46 2002 From: grzegorz.rumatowskiNOSPAM at chello.at (Grzegorz Rumatowski) Date: 13 Sep 2002 08:14:46 GMT Subject: Question about Tutorial-Unicode Message-ID: Hello All! I'm new to Python. Playing with it since some days. And last time I was playing with unicode strings. THen I've realized a problem. Okey, I thought let's look into tutorial on python.org. Looked into it and was wondering. In the section "3.1.3 Unicode Strings" there is a following example: >>> u"???" u'\xe4\xf6\xfc' But If I'm trying the same I'm getting: >>> u"???" UnicodeError: ASCII encoding error: ordinal not in range(128) This whole with Python 2.2.1 on Win I can't find any explanation. Mayby anyone of you? Greetingx Grzechu -- G.R.Z.E.C.H.U.: General Robotic Zombie Engineered for Calculation and Hazardous Utility From shalehperry at attbi.com Tue Sep 3 14:33:42 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 3 Sep 2002 11:33:42 -0700 Subject: trailing newline in string.splitfields() In-Reply-To: References: Message-ID: <200209031133.42429.shalehperry@attbi.com> On Tuesday 03 September 2002 07:17, Micah Mayo wrote: > I was splitting up some fields in a textfile using string.split, which > works fine, but that it usee ' ' as the delimiter. I've found that some > of the things I want to split include a space or two, so I've gone to > using string.splitfields, which also works fine, but for one thing. > Unlike string.split() it also grabs the newlne('\n') at the end of each > line. > > The way I've worked around this is as such: > > var1,var2,var3 = string.splitfields(stringtosplit,',') > list.append(var1) > list.append(var2) > list.append(var3[:-1]) > > So, I slice of the character, easy enough. And I'm generally satisfied > with that - but I was wondering if there may be, for the cause of more > beautiful code, a way to tell string.splitfields() to do it automatically. > > Thanks, > Micah there is always rstrip() which removes any trailing whitespace, including the newline. From kroc at blueyonder.co.uk Mon Sep 23 17:04:08 2002 From: kroc at blueyonder.co.uk (Keith) Date: Mon, 23 Sep 2002 21:04:08 GMT Subject: Elementary confusion Message-ID: <878z1s1kqf.fsf@smtp.blueyonder.co.uk> Hi, I am working through O'Reilly's "Learning Python". I am up to page 33, and already I have a problem. The text outlines a cli entry about math operators, all really straight forward; .>>>a=3 .>>>b=4 .>>>b/2+a 5 .>>>b/(2.0+a) 0.8 This is so straight forward that I wasn't going to type it in, but I did anyway, and got instead of '0.8' something I cannot account for. I got '0.80000000000000004'. So after 32 pages, I am already flumoxed. What is going on -- Keith. From tdelaney at avaya.com Mon Sep 23 02:31:39 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Mon, 23 Sep 2002 16:31:39 +1000 Subject: conditional expressions Message-ID: > From: Bruce Dawson > > Basically, construct a two entry list of the two items and then index > that with your expression, converted to bool. The bool function is > essential since there was previously no generic way of getting the > true/false value of an expression. Ignoring everything such as short-circuiting ... This type of thinking is one very good reason why bool() is a Good Thing (TM). A large number (my guess is the majority) of Python users do not know about operator.truth(). Tim Delaney From christophe.delord at free.fr Wed Sep 18 17:21:01 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Wed, 18 Sep 2002 23:21:01 +0200 Subject: Is there a list comprehension to do this? References: Message-ID: <20020918232101.0e950ad7.christophe.delord@free.fr> This solution is just the same as yours. The same loop, with the same expression (xx[i+1],xx[i]) but using list comprehension. >>> xx = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) >>> [ (xx[i+1], xx[i]) for i in range(0,len(xx),2) ] [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)] >>> On Wed, 18 Sep 2002 20:45:58 GMT "Joe Sixpack" wrote: > Is there a list comprehension or other 'cleaner' or 'prettier' way > to do the following: > > >>> xx = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) > >>> ww = [] > >>> for i in range(0, len(xx), 2): > ww.append((xx[i+1],xx[i])) > > >>> ww > [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)] > >>> > > Thanks in advance... > > -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From oren-py-l at hishome.net Wed Sep 18 01:29:20 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 18 Sep 2002 01:29:20 -0400 Subject: monetary applications [was: Python GUI app to impress the boss?] In-Reply-To: References: Message-ID: <20020918052920.GA81158@hishome.net> On Tue, Sep 17, 2002 at 09:40:34PM -0400, terry wrote: > As long as Python refuses to admit that money is the focus of most of > the world's software, Python will be relagated to the same status as > FORTRAN, BASIC, and etc - except COBOL and VB. > > Is there any way to get the Python world to allow for the processing of > monetary applications without some hokey 60's constructs that involve > in-line conversions or anticipations of calculation characteristics? I don't understand what exactly you are complaining about but is sounds interesting - can you elaborate? Oren From sludtke at bcm.tmc.edu Mon Sep 30 00:22:41 2002 From: sludtke at bcm.tmc.edu (Steve Ludtke) Date: Mon, 30 Sep 2002 04:22:41 GMT Subject: XMLRPC calls don't work in threads, or rather, they don't play well with others ! (help) Message-ID: <3D97D190.9030003@bcm.tmc.edu> Hi. I've been trying to write a python app that makes somewhat time-consuming XMLRPC calls. I planned to have several calls going at once using threads, but it seems like something in the XMLRPC client code isn't releasing the python interpreter lock properly. That is, as soon as the XMLRPC call is made, none of the other threads do anything until it returns. Just to make sure this was what was happening, I wrote a little test thread that prints out messages every half-second, and indeed, as soon as an xmlrpc call is made, nothing happens. This code needs to be cross-platform compatible, so I'm rather leery of editing any of the associated C source. Anyone have any ideas. Is there something I can do at the Python level to deal with this issue ? TIA PS - here's the code for the thread that doesn't seem to release: class getThread(threading.Thread): def __init__(self,queue,login): threading.Thread.__init__(self) self.queue=queue self.login=login self.transport=xmlrpclib_auth. BasicAuthTransport(self.login[1],self.login[2]) def run(self): while (1): item=self.queue.get(1) if (item=="EXIT") : return server=xmlrpclib_auth.Server(self. login[0]+item.idpath(),self.transport) try: lst=server.do_list() # processing omitted nv=server.values() # more processing omitted except: #error processing Both of the server.() calls prevent other threads from running From jnana4 at DELETEhotmailCAPS.com Sun Sep 1 19:00:43 2002 From: jnana4 at DELETEhotmailCAPS.com (jano) Date: Sun, 01 Sep 2002 23:00:43 GMT Subject: EOFError using cPickle.load References: <6avc9.264595$me6.34329@sccrnsc01> Message-ID: wrote in message news:mailman.1030915575.26265.python-list at python.org... > either do not use Windows, or make sure you open with 'rb' and 'wb'. > > Jeff > Thank you very much! When it said that 'load' automatically figured out if it was a binary file or not, i forgot about specifying 'rb' in open. thanks, jano From f.marani at REMOVETHIStin.it Sat Sep 28 10:32:47 2002 From: f.marani at REMOVETHIStin.it (Federico) Date: Sat, 28 Sep 2002 14:32:47 GMT Subject: Making directory in cgi! References: Message-ID: use os.mkdir() in os module es: os.mkdir("homer/simpsons"); if the directory exists, it will probably generate an exception, look at the manual... "CheapSkate" ha scritto nel messaggio news:an15s8$slv$1 at lust.ihug.co.nz... > and one more thing...... > > what's going to happen if let say, the directory simpsons already exist > inside homer. > What will happen to the files inside simpsons??? > > Thanks. > > "CheapSkate" wrote in message > news:an15gg$s3h$1 at lust.ihug.co.nz... > > HI, > > let say my createdir.cgi is in > > /bug/ger/createdir.cgi > > and doing ls in /bug/ger/ will list out > > . > > .. > > (file)createdir.cgi > > (dir)homer > > how do I create directory inside homer? > > like homer/simpsons/ > > ??? > > what are the library that I need to import? > > Thanks...... > > (I know this is a simple Q, so please excuse me... im a newbiee) > > From Peer.Griebel at entire.de Mon Sep 16 09:01:38 2002 From: Peer.Griebel at entire.de (Griebel, Peer) Date: Mon, 16 Sep 2002 15:01:38 +0200 Subject: Mutable Stings Message-ID: <673E8D215B3BD311A9C90090279BBB8402829E77@mail.ebssoftware.de> Hi, I do understand that strings are immutable. This is the reason (I think) that the class str does not define the methods e.g. __iadd__(). Now I had a look at UserString.py. It says that the class UserString provides a wrapper class for immutable strings. Therefore it can safely define the method hash(). (In contrast the class MutableString raises an exception when hash() is going to be called.) My problem now is that UserString does provide the method __iadd__ which does an in-place modification of the string (self.data)! This would result in a non constant hash value! So my question: Is this correct - or did I overlook something? connection reset by Peer -- Dr. Peer Griebel Tel: +49(0) 731 / 9 74 95-0 Dipl. Inform. Fax: +49(0) 731 / 9 74 95-20 Entire Software AG mailto:Peer.Griebel at entire.de Pfarrer-Wei?-Weg 10 - 12 D-89077 Ulm http://www.entire.de From lists at gregfortune.com Thu Sep 12 00:10:50 2002 From: lists at gregfortune.com (Greg Fortune) Date: Wed, 11 Sep 2002 21:10:50 -0700 Subject: I must be an idiot, please pity me! References: Message-ID: <3d801224$0$309$39cecf19@nnrp1.twtelecom.net> Sure, make another module named db. Provide a couple functions in db like connect and query. Then in CGI1.py import db import mod1 import mod2 db.connect(host, db_name, user, pass) #do your stuff And in mod1 import db def functiona(): return db.query('SELECT * FROM some_table') The db module would need to look something like this #assuming you are using MySQL import MySQLdb THE_CURSOR = None def connect(host, db_name, user, pass): global THE_CURSOR the_db = MySQL.connect(user=user, passwd=pass, db=db_name, hostname=host) THE_CURSOR = the_db.cursor() def query(query_string): return THE_CURSOR.execute(query_string) Of course, that doesn't take into account connecting to multiple database, connections sharing, closing the connection, etc... But it should work for what you're trying to do. If you'd like a more powerful db module, let me know and I can share some of the code I've developed over the past couple years. Greg Fortune Fortune Solutions newbie wrote: > Hello all. I'm getting very desperate now, so I have to ask for some help. > I'm working on a small project and have slipped into what must be > namespace hell. > > I have a few controlling CGI scripts that use functions from other modules > to build parts of a page. Each function in these other modules contains > the SQL processing and HTML building code grouped by related data. The > idea being I can reuse the functions in the other scripts. All works fine, > providing each modules connects to the database as a stand alone job, or I > pass a database connection object thing to each and every function. I > suspect that both of these are wrong, due to the ugliness or nasty system > overhead of the datbase connections. > > What I thought I should be able to do is: > > CGI1.py: > > import mod1, mod2 > > connect to database > > create part of page using mod1.functiona > create part of page using mod1.functionb > create part of page using mod2.functionz > > close database > > > But it doesn't seem to work like that. I've trawled though google and deja > for days (plus a couple of new rider books), and no one seems to hit this > problem. I must have a HUGE misunderstanding somewhere. I know mod1 and > mod2 cannot see CGI.py namespace, but there must be a way of sharing the > database connection, mustn't there? > > Help or a kick up the bottom would be really appreciated here! > > Sammy. From tjreedy at udel.edu Thu Sep 19 14:52:13 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Sep 2002 18:52:13 GMT Subject: strong/weak - dynamic/static [Was: Getting started] References: Message-ID: "Alex Martelli" wrote in message news:Ugmi9.114712$ub2.2441284 at news1.tin.it... > Terry Reedy wrote: ... > > Python objects are typed at creation. Is that dynamic or static? > Judge for yourself: > >>> x.__class__ = Y I specifically *excluded* this type of assignment and the changed behavior of new-style classes from my discussion when I wrote "[Discussion of old and new classes and modification of instance.__class__ omitted.]" Classically, and in the C code, x has type 'instance' (of a user-defined-class) both before and after the class mod. But this gets into the lengthy and most likely inconclusive discussion that I intentionally avoided. > If you find a way to name this behavior "static", you'll be well > placed for the yearly Humpty Dumpty award. This is pretty inane. Again, I specifically excluded 'this behavior' from my comments. Anyway, my question *rhetorically* asked whether creation-time typing (which is fixed except for the exception that I excluded) is (to quote the OP) 'dynamic or static'. I then suggested that this dichotomy does not fit Python very well. Terry J. Reedy From yves_breemersch at hotmail.com Mon Sep 2 09:53:39 2002 From: yves_breemersch at hotmail.com (yves) Date: 2 Sep 2002 06:53:39 -0700 Subject: call by reference from automation objects Message-ID: <8f2ca1f9.0209020553.7646a6c3@posting.google.com> Hello, I have an automation object generated from VC6: BEGIN_DISPATCH_MAP(CSNMPManager, CCmdTarget) //{{AFX_DISPATCH_MAP(CSNMPManager) DISP_FUNCTION(CSNMPManager, "Get", Get, VT_I4, VTS_I4 VTS_VARIANT VTS_VARIANT) //}}AFX_DISPATCH_MAP END_DISPATCH_MAP() long CSNMPManager::Get(long RID, const VARIANT FAR& OIDs, const VARIANT FAR& Result) { ... PerformGet(RID, vaSNMPObject, vaValues, lErrorCode); // Copy the result vaDetachedValues = vaValues.Detach(); VariantClear(Result.pvarVal); Result.pvarVal->vt = vaDetachedValues.vt; Result.pvarVal->parray = vaDetachedValues.parray; lRetVal = lErrorCode; return lRetVal; } My Python script is loaded as code file from my C++ application and the appropriate IDispatch pointers are supplied to the script to be able to call the object. When I call the method from Python the result lst stays empty: lst=() lstMIBObjects=["1.3.6.1.2.1.2.2.1.10.1",] lRetval=Snmp.Manager.Get(557848457, lstMIBObjects, lst) lst is an empty tuple although the safearray contains actual values. As I understand it Python does not support call by reference and parameters that are changed within a method should be returned as multiple return values. Does this also applies to methods called from automation objects and do I have to encapsulate multiple return values in a safearray? kind regards yves From jhorneman at pobox.com Sun Sep 29 15:19:40 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: Sun, 29 Sep 2002 21:19:40 +0200 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <3d9739c7$0$19818$91cee783@newsreader01.highway.telekom.at> <3D973DA4.4040600@nospam.attbi.com> Message-ID: <3d9751ec$0$20510$91cee783@newsreader01.highway.telekom.at> "djw" wrote in message news:3D973DA4.4040600 at nospam.attbi.com... > > Although I believe that the Python docs are a bit on the brief side > sometimes, I don't think this topic has this problem... if you look at > the package docs at: > > http://python.org/doc/current/tut/node8.html#SECTION008400000000000000000 > > ... it has a nicely done example of a directory layout and how the > __init__.py files fit into the picture. What I would fault the docs with > is the fact that (having gone through this fustration myself) this > information is not easily discoverable. How was I supposed to know that > I needed a "package" in order to import a module from a subdirectory? > I'm sure many would say, go buy a Python book and look there... but I > did that, and the books aren't any better in my opinion in this area. > This topic of importing modules from various directories has been my > biggest fustration with the language... definitely a "wart" in my > opinion. Don't get me wrong, discovering Python-and-All-Its-Splendor has > changed my whole approach to software development (and made it fun > again), but there are still a few things that could use some polish. > Well, like I said (admittedly not as succinctly as I might have) I found that (after a while), tried it, and it didn't work. It now appears that problem was related to my Python installation: after reinstallation it worked fine. And for what it's worth, if I didn't like Python I would have stayed with C++ ;) Jurie. From pknotz at sandia.gov Fri Sep 27 08:25:37 2002 From: pknotz at sandia.gov (Pat Notz) Date: 27 Sep 2002 05:25:37 -0700 Subject: Searching for and sorting files by date and compiling stats in Windows References: Message-ID: <525eaba.0209270425.55885f9d@posting.google.com> "James Kew" wrote in message news:... > > os.path.walk and match a regular expression against each file in names on > each callback. > There's also the fnmatch module (and glob) for shell like file name matching... From lutz at lutz-horn.de Tue Sep 17 04:13:29 2002 From: lutz at lutz-horn.de (Lutz Horn) Date: 17 Sep 2002 10:13:29 +0200 Subject: Best way ( easiest ) to generate RSS/RDF on MySQL-data ?? References: Message-ID: "Thomas Weholt" <2002 at weholt.org> writes: > Any hints or clues on how to generate RSS/RDF-files, not even > related to this problem in particular would be highly appreciated. Do you know about the Redland library[1]? It's written in C but has a Python API. Regards Lutz [1] http://www.redland.opensource.ac.uk/ From jb at cascade-sys.com Fri Sep 20 08:32:36 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Fri, 20 Sep 2002 05:32:36 -0700 Subject: Larry Wall's comment on python... References: <006501c25fd5$ecc80740$0101010a@local> <3D8AAC3C.9020300@cascade-sys.com> <003001c2609e$04d0fea0$0101010a@local> Message-ID: <3D8B1564.5000507@cascade-sys.com> Chris Gonnerman wrote: >----- Original Message ----- >From: "James J. Besemer" > > > >>They are a hell of an improvement over "begin" and "end". >> >> > >I disagree slightly... I don't have to shift for the literal >"begin" and "end" statements, and I don't have to reach either. >I'm left-handed; my right pinky is probably my weakest finger. >So, while I don't really *like* "begin" and "end" as in >Pascal, I rarely curse while typing them. > Ah. I took a typing class in high school and in retrospect it was one of the most useful classes from that period in my life. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From irmen at NOSPAMREMOVETHISxs4all.nl Tue Sep 24 16:30:23 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Tue, 24 Sep 2002 22:30:23 +0200 Subject: Pyro Error. References: Message-ID: Carlos Moreira wrote: > Testing the simplest example of docs/8-example.html, > on client side, generate an error message: [...] > Pyro.errors.ProtocolError: connection failed > > Where I must seek for inconsistences? Pyro.conf? Nope it should work without any configuration file. You're not giving any details so I cannot say what could be wrong. For instance, are you sure the Pyro server is running? Can your client machine reach the server machine through the network? A better place to ask Pyro questions is the Pyro mailinglist. See pyro.sourceforge.net Irmen de Jong From manuel at hendel.net Thu Sep 26 07:23:22 2002 From: manuel at hendel.net (Manuel Hendel) Date: Thu, 26 Sep 2002 13:23:22 +0200 Subject: comparing all values of a list to regex In-Reply-To: References: Message-ID: <20020926112322.GC59710@partagas.as.de.cw.net> On Wed, Sep 25, 2002 at 10:26:53AM +0000, Alex Martelli wrote: > E.g.: > > num_matches = [ there.match(item) is not None for item in alist ].count(1) > > if num_matches == 0: > againanothernewlist.append(alist) > elif num_matches == 1: > anothetnewlist.append(alist) > elif num_matches == len(alist): > anewlist.append(alist) > > > Note that there's some ambiguity on what to do if alist is empty -- > literally this is BOTH "matches all list items" AND "doesn't match > at all". Here I've chosen the second interpretation, but depending > on your specs you can choose to test num_matches in different ways. To be honest I don't understand that completely. Maybe, I have to describe my problem a little bit more in detail and show the things I've already done. This is the input, it is "|" seperated textfile with about 15000 lines of pop3 accounts: |Number|String|Number|String(Domain)|String(Account)|String(Login/Email)|String(Password)|String|String| These are the fields I care about. String(Domain): This is the domain of the Account String(Account): This is the part in front of the @doamin. This can also be a * for a catchall account. String(Login/Email): This is the local pop3-account or a emailaddress, or both, comma seperated. String(Password): This is the password if String(Login/Email) is a pop3-account. This should be the output: Three text files. One with only forwardings (only emailaddresses in the String(Login/Email). One with only pop3-accounts in the String(Login/Email), and one mixed, where String(Login/Email) has pop3-accounts and emailaddresses. This is what I've done already: #!/usr/bin/env python # import sys, string, re inputfile = open(sys.argv[-1], "r") lines = inputfile.readlines() # deleting the first three lines and the last line lines = lines[3:-1] # empty list for the domains domains = [] # empty list for the new lines neededlines = [] for line in lines: fields = string.split(line, "|") # check if the domain field contains a regualr domain p = re.compile("[0-9a-z\\.]+[a-z]{2,3}", re.IGNORECASE) m = p.match(string.strip(fields[4])) if m: # extract the needed fields in a separate list and # split the gLogin to get a list in the list neededfields = [] neededfields = [string.strip(fields[4]), string.strip(fields[5]), string.split(string.strip(fields[6]), ","), string.strip(fields[7])] # put alle neededfields together to a neededlines list neededlines.append(neededfields) # this is to get a list of domains with each domain just once if neededfields[0] not in domains: domains.append(neededfields[0]) #Actually, I wanted to do this with a dictionary and the lists in the #dictionary, but I couldn't get this working. # empty list for lines per all domains linesperdomains = [] for domain in domains: # empty list for lines domainlines = [] for neededline in neededlines: if domain == neededline[0]: domainlines.append(neededline) # empty list for lines per domain linesperdomain = [domain, domainlines] # put all linesperdomain together to a linesperdomains list linesperdomains.append(linesperdomain) The program seams to be quite slow, but that's not that important. Important for me is, to get this problem solved. The next step is the spliting up into the three different parts. Can anyone help? Thanks in advance, Manuel -- It takes one tree to make a thousand matches, it takes one match to burn a thousand trees. From TomH at optiscan.com Tue Sep 3 21:41:56 2002 From: TomH at optiscan.com (Tom Harris) Date: Wed, 4 Sep 2002 11:41:56 +1000 Subject: Excluding specific module from import Message-ID: <9983313f2b9c3b5a524b3b3b5b7381f83d7564e8@optiscan.com> > Anthony Tuininga [mailto:anthony at computronix.com] >You might want to mention what method you are using for building an >executable as there are several methods available! Each has a slightly >different method for eliminating modules from the final executable.Sure, I am using py2exe. Sure, its py2exe. On Tue, 2002-09-03 at 18:31, Tom Harris wrote: > Greetings > > I have a library that tries to import mx.DateTime, and on failure uses its > own implementation. The problem is that I am building an executable, and I > would much rather not have mx imported, as it increases the size of the > executable by a factor of two. Could someone give me an idea how to frob > things so that import will fail to import mx.*. I cannot frob sys.path as it > only contains a path to site-packages. I would sooner not rewrite the > library. > Thanks > > Tom Harris, Software Engineer > Optiscan Imaging, 15-17 Normanby Rd, Notting Hill, Melbourne, Vic 3168, > Australia > email tomh at optiscan.com ph +61 3 9538 3333 fax +61 3 9562 7742 > > This email may contain confidential information. If you have received this > email in error, please delete it immediately,and inform us of the mistake by > return email. Any form of reproduction, or further dissemination of this > email is strictly prohibited. Also, please note that opinions expressed in > this email are those of the author, and are not necessarily those of > Optiscan Pty Ltd. > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From jepler at unpythonic.net Mon Sep 9 09:57:30 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 9 Sep 2002 08:57:30 -0500 Subject: Tkinter: How to "break" class-event-bindings from within tag-bindings? In-Reply-To: <3D7C9B9C.60603@ms6.de> References: <3D7C9B9C.60603@ms6.de> Message-ID: <20020909135728.GB10101@unpythonic.net> On Mon, Sep 09, 2002 at 03:01:16PM +0200, Michael Schwarz wrote: > A "break" as the return value of a tag-event-binding for the > Text-widget seems not to prevent the standard event-handling of the > widget to occur. I can reproduce this in a bare "wish" script, without involving Python. I tested on wish8.4 (somewhat stale CVS) and 8.3.3. The manpage for text(n) says this: It is possible for the current character to have multiple tags, and for each of them to have a binding for a particular event sequence. When this occurs, one binding is invoked for each tag, in order from lowest- priority to highest priority. If there are multiple matching bindings for a single tag, then the most specific binding is chosen (see the manual entry for the bind command for details). continue and break commands within binding scripts are processed in the same way as for bindings created with the bind command. If bindings are created for the widget as a whole using the bind command, then those bindings will supplement the tag bindings. The tag bindings will be invoked first, followed by bindings for the window as a whole. I'm not sure if this is the intended behavior or not. After all, continue and break are supposed to be processed 'in the same way as' normal bindings. However, maybe the word "supplement" and the description "followed by bindings for the window as a whole" are supposed to describe the behavior you saw as correct. You may wish to file a bug against tk or post in a tk newsgroup (comp.lang.tcl) to ask whether this behavior is correct or is a bug. My "wish" script to show the problem: text .t .t insert end "Link\n\nJump HERE" .t tag add link 1.0 1.4 .t tag bind link <1> { jump; break } .t tag config link -underline on -foreground blue #bind .t <1> { break } proc jump {} { .t tag remove sel 0.0 end .t tag add sel 3.5 3.9 } pack .t From martin at v.loewis.de Thu Sep 5 03:39:52 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 05 Sep 2002 09:39:52 +0200 Subject: Python Source Code Documentation References: Message-ID: "Terry Reedy" writes: > If you mean the C source of the Python interpreter, you mostly are on > your own. You can try groups.google to retrieve past posted > discussions. Beyond that, the source is its documentation. You can > probably learn quite a bit by spending an hour or two. It isn't really that bad: You should study the "Extending and Embedding" tutorial, and the C API reference. If you have memorized those, reading the Python source code will be much easier. Regards, Martin From seth at jtan.com Mon Sep 16 14:12:26 2002 From: seth at jtan.com (Seth Delackner) Date: Mon, 16 Sep 2002 18:12:26 GMT Subject: distutils link arguments BEFORE object files? Message-ID: <3D861F09.5010403@jtan.com> I'm trying to build PyOpenGL on a new platform (OS X) and I've hit a snag. the link phase needs an argument "-framework AGL" to appear before the .o files on the argument list. If I specify extra_link_args="-framework AGL" then that argument is appended to the end of the entire argument list. How do I make the arguments appear where I need them? From pearu at cens.ioc.ee Wed Sep 18 10:25:52 2002 From: pearu at cens.ioc.ee (Pearu Peterson) Date: Wed, 18 Sep 2002 17:25:52 +0300 (EEST) Subject: BibTeX module? In-Reply-To: Message-ID: On 18 Sep 2002, Matthias Huening wrote: > Hi, > > I am looking for a simple BibTeX module, allowing me to read and > manipulate/convert a bibliography file. Try http://cens.ioc.ee/~pearu/misc/readbib.py that I use to maintain my bib file database. Pearu From eppstein at ics.uci.edu Wed Sep 11 12:17:07 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 11 Sep 2002 09:17:07 -0700 Subject: Smoothing a discrete set of data References: <3csmdso5.fsf@morpheus.demon.co.uk> Message-ID: In article <3csmdso5.fsf at morpheus.demon.co.uk>, Paul Moore wrote: > This isn't so much a Python question, as an algorithms question. I > couldn't find a newsgroup for discussing algorithms (is there a good > one?) so as I'm implementing the code in Python I thought I'd try here > - I hope that's OK. A better newsgroup for discussing algorithms is comp.theory, although your question might be better for sci.stat.math or maybe sci.op-research. There are a lot of ways of solving your question, though -- smoothing by convolving with a Gaussian, taking a Fourier transform and throwing away the high-frequency terms, or finding a least-squares fit to a low-degree polynomial, to name three. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From gerhard.haering at gmx.de Sat Sep 28 22:21:10 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 29 Sep 2002 02:21:10 GMT Subject: Best way to create a class dynamically on the fly? References: <3D96511D.2040407@4-am.com> Message-ID: Robert Oschler wrote in comp.lang.python: > > "Evan" wrote in message news:3D96511D.2040407 at 4-am.com... >> Robert Oschler wrote: >> > What is the best way to create a Python class dynamically at runtime? >> >> ALL Python classes are created dynamically at runtime. The following is >> not a declaration in the sense that you're accustomed to from C/C++, it >> is normal code executed when the containing file is run (or imported): >> >> class Foo: >> def meth1(self): >> return "I am a method" >> > > > Evan, > > I understand but what I'm after is building the class itself dynamically, > akin to the way you can manufacture a prolog predicate on the fly. For > example, if wanted to create a class whose name was provided in a string > variable called ClassName, at runtime. Or did I misunderstand your reply? You can still do that by calling whatever is the equivalent of 'exec' at the C-level. One other possibility, which I've used in Python, but not from C or C++, yet is using the 'new' module to dynamically create classes at runtime. Here's a simplistic example, that should be relatively easy to convert to C: import new def make_class(name): cls = new.classobj(name, (), {}) return cls cls = make_class("foo") obj = cls() The 'new' module doesn't have a C API, so you'll probably have to import it and call the 'classobj' method using PyObject_CallObject -- Gerhard From rnd at onego.ru Wed Sep 4 13:07:37 2002 From: rnd at onego.ru (Roman Suzi) Date: Wed, 4 Sep 2002 21:07:37 +0400 (MSD) Subject: Program for ... HELP!!! In-Reply-To: Message-ID: On Wed, 4 Sep 2002, kyro wrote: >Hello everybody, I need a little piece of program thath calculate the >determinant of a square matrix. >Can somebady help me?!??!?!?! Not sure if this help you: >>> import Matrix, LinearAlgebra >>> m = Matrix.Matrix([[2,0],[0,.5]]) >>> print LinearAlgebra.determinant(m) 1.0 (You need a package called Numeric Python (or NumPy) to do this. >Thanks a lot > >>>kyro<< > >P.S.: I think to use the recursion, but I don't use thr recursion in Python, >I'm a newby.... :oP Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by Linux RedHat 7.2 aaro at onego.ru <- not to be mailed to From claird at starbase.neosoft.com Wed Sep 25 11:15:36 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 25 Sep 2002 10:15:36 -0500 Subject: Removing all occurences of a character from a string. References: Message-ID: In article , Mike C. Fletcher wrote: >Under later Python versions (such as 2.2.1), you can do the following: > >attr = [[item.replace("'","") for item in element] for element in attr] . . . I growsed at Alex privately that someone ought to mention map. My complaint was ill-considered; this problem *does* present an excellent example of why list comprehensions are absolutely more readable and therefore Pythonic than the corresponding map()- (or filter()-) coded solution. Unless the atomic operation (the replace, in this case) happens to be naturally expressible without passing along more arguments, map() complexifies excessively with lambdas or equivalents. In this case, of course, there needs to be a replace("'", ""), so list comprehension is a clear win. I still feel obliged to observe that one's likely to come across old code that solves this sort of problem through the use of map and lambda. Maybe I'm also making a mistake in that. 'Anyone have a good sense, for instance, of what Python version the leading Linux distributions bundle? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From jknapka at earthlink.net Sat Sep 7 00:45:30 2002 From: jknapka at earthlink.net (Joseph A. Knapka) Date: Sat, 07 Sep 2002 04:45:30 GMT Subject: ANN: Thinking in Tkinter References: Message-ID: <3D798461.B3FE0E06@earthlink.net> Stephen Ferg wrote: > > A small page devoted to "Thinking in Tkinter" > at http://www.ferg.org/thinking_in_tkinter/index.html > for whoever might find it useful. It's an interesting and useful site, IMO. I have one nit to pick: you probably shouldn't refer to the parent/child relationship between UI elements as "binding", since that will cause great confusion when you get around to discussing the binding of events to code (using the widget.bind() method). Also, you should be aware of the "command" option, which can be applied to button widgets of various types: def pushed(event): print "Someone pushed the button." btn = Button(text="Push me", command=pushed) will bind a left-click on btn to the pushed() function, without the bother of an explicit btn.bind() call. Cheers, -- Joe "I'd rather chew my leg off than maintain Java code, which sucks, 'cause I have a lot of Java code to maintain and the leg surgery is starting to get expensive." - Me From timr at probo.com Tue Sep 10 01:44:39 2002 From: timr at probo.com (Tim Roberts) Date: Mon, 09 Sep 2002 22:44:39 -0700 Subject: Possible bug in WxPython References: <9ff6b66.0209090557.3c0e3c94@posting.google.com> Message-ID: vtail at yandex.ru (vtail) wrote: >Greetings. > >When trying to run an example program from wxWiKi >http://wiki.wxpython.org/index.cgi/Getting_20Started, section 7.1.2, I >encounter following error. Could someone please explain it to me? > >... >====> >... >app = wxPySimpleApp() >frame = MainWindow(None, -1, "Sample editor") >frame.Show(1) > ><==== Mikey is right. All wxPython programs need this: app.MainLoop() at the very end in order to do anything useful. That's the command that actually starts the message loop and lets things display. There was a typo in the wxWiki page that suppressed that line. I have now repaired it... -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From joconnor at cybermesa.com Sun Sep 1 23:47:08 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Mon, 02 Sep 2002 10:47:08 +0700 Subject: Why it is so dramatical? References: Message-ID: <20020902.104707.1789376348.1554@cybermesa.com> In article , "Bo M. Maryniuck" wrote: ----- > > As you see, adding string to the string isn't a huge problem for Perl as > for Python. What's "wrong" with Perl? Because in Perl, a string is mutable, in Python, a string is immutable. This causes a performance tradeoff for some operations. Mutable strings allow you to extend a string easily so Perl is very fast at that kind of operation; immutable strings allow you to 'intern' the string for faster dictionary lookup when using strings as keys in a dictionary, as an example Neither is better, there are just tradeoffs between mutable and immutable strings which the designers of both Perl and Python took into account when they decided which to use based on what the language is intended to do. As a result Perl is much faster at some kinds of operations than Python, and vice-versa. -- Jay O'Connor joconnor at cybermesa.com http://www.r4h.org/r4hsoftware From strombrg at tesuji.nac.uci.edu Wed Sep 18 18:03:37 2002 From: strombrg at tesuji.nac.uci.edu (Dan Stromberg) Date: 18 Sep 2002 22:03:37 GMT Subject: continued rresvport trouble on solaris Message-ID: Thanks very much for the modified function that works on linux and windows. I'm still having trouble on solaris 8, unfortunately. Everything works fine with 2.1.2, but with 2.2.1, no rresvport function I've tried has worked. I'm beginning to think I should go back to extending the python socket module to expose the C rresvport function, but I'm not convinced that will work either, really. Does anyone have suggestions? Is anyone else having trouble binding sockets on Solaris from python? Carey Evans (careye at spamcop.net) wrote: >Dan Stromberg wrote: >> I've been using a modified version of Carey Evans' rresvport function >> in a printsystem. > >I'd actually forgotten writing this. It's all coming back to me now >though. After a bit of tidying up, I get the version below, which >works >for me with Python 2.1.3 and 2.2.1 on Windows 2000 and Linux. > >The main changes from my original version are: > >* Fixing the bind() to use a two-element tuple. Two arguments has >always been wrong, but earlier versions of Python let it go. >* Removing the strange exception handling code. I have no idea what I >was thinking. > >> So I got kind of interested in that '' in the bind call. This is >> supposed to mean "localhost". So I changed it to >> bind(('localhost',port)). > >The '' actually means INADDR_ANY, or 0.0.0.0. (Though for some >reason, >socket.INADDR_ANY is the integer 0, which doesn't work with bind.) >You >could try using '0.0.0.0' instead of the empty string, although it >should mean exactly the same thing. > >---------------------------------------------------------------------- >"""A module to allocate a socket on a reserved port. > >Copyright (c) 1998, 2002 Carey Evans. > >Permission to use, copy, modify, and distribute this software and its >documentation for any purpose and without fee is hereby granted, >provided that the above copyright notice appear in all copies and that >both that copyright notice and this permission notice appear in >supporting documentation.""" > >import socket, errno > >class RResvPortError(Exception): > def __str__(self): > return 'No reserved ports available' > >def rresvport(): > """rresvport() -> socket > >Return a socket with a privileged address bound to it. On Unix >systems, >this can only be done by root. If no reserved ports are available, >raise RResvPortError.""" > > port = 1023 > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > while port >= 512: > try: > s.bind(('', port)) > except socket.error, detail: > if detail[0] != errno.EADDRINUSE: > raise > else: > return s > port = port - 1 > > raise RResvPortError >---------------------------------------------------------------------- > >-- >"Every time you misuse it's, ten kittens are KILLED." > -- Ben Goodger -- Dan Stromberg UCI/NACS/DCS From python at rcn.com Fri Sep 6 08:40:37 2002 From: python at rcn.com (Raymond Hettinger) Date: Fri, 6 Sep 2002 08:40:37 -0400 Subject: Dictionary... References: <7ir8g7xqqk.fsf@enark.csis.hku.hk> Message-ID: Hello Issac, Try looking at seqdict in the Vaults of Parnassus: http://home.arcor.de/wolfgang.grafen/Python/Modules/Modules.html Also, I think there may be a sorted dictionary implementation in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python Your other ideas were good too. The auxilliary map of successors and precessors is likely to be the fastest. To efficiently update a sorted python list, try the bisect module. Raymond Hettinger "Isaac To" wrote in message news:7ir8g7xqqk.fsf at enark.csis.hku.hk... > Hi, > > Some time ago I want to have a dictionary-like type that can support > dictionary operation, plus that given any key, I want to know the > predecessor and successor of any given key efficiently. I've thought of > using a Python list, but it is impossible to update quickly. The closest > thing I can think of is an auxillary map that implements the successor and > predecessor functionalities. But I'm wondering there is anything better. > After all, Python dictionaries are implemented by height balancing tree, so > internally the needed data can be retrieved efficiently. Any hint? > > Regards, > Isaac. From henrik.motakef at web.de Sun Sep 15 04:34:30 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 15 Sep 2002 10:34:30 +0200 Subject: Will xml.dom work with HTML docs? References: Message-ID: <877khntzvt.fsf@pokey.henrik-motakef.de> "Robert Oschler" writes: > Will the xml document parser module work with plain old HTML docs, Only if they happen to be well-formed XML docs, which is unlikely. > if not is there a good parser module for HTML docs? See the htmllib module in the standard library. hth Henrik From martin at v.loewis.de Mon Sep 2 01:35:51 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Sep 2002 07:35:51 +0200 Subject: length of unicode strings References: Message-ID: teg at redhat.com (Trond Eivind Glomsr?d) writes: > When running on a utf-8 system, python doesn't seem to take it input > in unicode: "it input" is a bit too general: Python applications can certainly input and output Unicode, and any of its encodings. But yes, you cannot really use UTF-8 in source code, for Unicode literals. > >>> b=u"?" > >>> b > u'\xc3\xa5' In Python 2.2, non-ASCII bytes in a Unicode literal are always treated as Latin-1. This is fixed in PEP 263, which allows you to write # -*- coding: utf-8 -*- b=u"?" Setting the source encoding in interactive mode is still not supported by this PEP - it also somewhat depends on the console's encoding. > Any particular things to configure? No. To use UTF-8 in source code, you have to write unicode("?", "utf-8") In a larger source code fragment, this can be written as def u(s): return unicode(s, "utf-8") b = u("?") This relies on the fact that non-ASCII bytes in a string literal are treated as-is; you should still declare the encoding, or else you'll get a warning in Python 2.3. HTH, Martin From tjreedy at udel.edu Mon Sep 16 01:13:53 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 16 Sep 2002 05:13:53 GMT Subject: Source code References: Message-ID: "Terje Johan Abrahamsen" wrote in message news:am3ms1$2e49b$1 at ID-53055.news.dfncis.de... > If I would like to write some code that would not be possible for others to > read, after I distribute the program, If a general purpose computer can read it, so can a person with the aid of that computer -- which is precisely why 'Hollywood' has persuaded one congress-slave to introduce a bill outlawing general purpose desk computers by requiring that they be crippled so that they are more like proprietary media players. >would Python be suitable? I know that > there are a few programs like Py2Exe, that creates .exe files. But, I also > saw this: > > -------------------- > A zip-compatible archive is built, containing all files from this > directory as well as your script, and appended to a custom python > interpreter supplied with py2exe. > -------------------- > > Doesn't sound like it is protected very well. Is there some alternative to > Py2Exe that can do the job, or should I look for a compiled language > instead? If hiding your code is your top priority, probably so -- at least after doing development in Python. If you use a language with gotos (like C), you can destructure your code to make it more obscure. Another trick is to add useless code than literally cannot be figured out since there is no meaning to figure out (other than 'be confused'). There have been posts in the past about encrypting files. You might find them with google. TJR From Oschler at earthlink.net Wed Sep 11 20:02:43 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Thu, 12 Sep 2002 00:02:43 GMT Subject: Use glob not re for regexp? Message-ID: I saw a post where someone said to use glob not re for regular expressions? Is this true and if so why? I use Secret Labs regexp package. thx From bwucew at yahoo.com Fri Sep 13 03:52:12 2002 From: bwucew at yahoo.com (Bwuce_Wee) Date: 13 Sep 2002 00:52:12 -0700 Subject: Extending a C++ App References: <996eade8.0209120912.3a653d7@posting.google.com> Message-ID: <996eade8.0209122352.45721938@posting.google.com> Thanks for your help I looked at SWIG However I have a few concerns (forgive me if Im being dense) (1) All the examples are created as DLLs (ie APIs) This is fine - except how would my C++ App use the same object instances? (ie. share the memory and API objects) (2) SWIG does not do a nice job of object wrapping (in my opinion) For instance instead of saying c = example.Circle c.x = 10 c.y = 20 del c I need to do this: c = example.new_Circle() example.Shape_x_set(c,10) example.Shape_y_set(c,20) delete_Circle(c) Isn't there a cleaner library somewhere to do this? SIP has no documentation - so I don't know what to expect of it I'm busy investigating Boost.Python... Thanks again for the help Greg Green wrote in message news:... > Embedding python inside an application can be simple. The basic step > is to call Py_Initialize(). After that you can execute python code > with the PyRun_* functions. Of course, in practice, there is a lot > more to worry about. Threads and the GIL, if you are using a GUI, you > have to worry about the event loop, etc. > > Accessing your c++ object model requires you to wrap them just as if > you were going to use the model in a python program. The normal > answers are swig, sip, boost and some others. I've used both swig, > sip, and writing the wrapper by hand. All will work. Once the api is > wrapped, the resulting code is either statically or dynamically linked to > your exe. From roy at panix.com Tue Sep 3 09:04:31 2002 From: roy at panix.com (Roy Smith) Date: Tue, 03 Sep 2002 09:04:31 -0400 Subject: How to avoid freeing memory on exit? Message-ID: I've got a program which builds a very complex data structure consisting of about 200,000 objects. When the program exits, the top-level object goes out of scope, and the interpreter grovels about for a long time freeing up the individual elements of the data structure. This takes a while. Is there any way to get the interpreter to just exit without doing all that memory cleanup? Once the results have been printed, I don't care if memory is kept in a consistant state, since the very next thing I'm going to do is blow away the process. From erno-news at erno.iki.fi Thu Sep 12 17:47:31 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 13 Sep 2002 00:47:31 +0300 Subject: UNIX processes References: Message-ID: In article , "Bo M. Maryniuck" writes: | On Tuesday 10 September 2002 13:52, Erno Kuusela wrote: || use the ps program (ps -e works on linux). there is no other || standard api for it. | I already made native Python module for this, because I don't like 'ps' in | this case. Well, module works even faster. ;-) sorry, i got the impression from your original post that you wanted a portable solution ("unix/linux"). there is already at least one /proc module on parnassus.. -- erno From max at alcyone.com Mon Sep 23 22:50:27 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 23 Sep 2002 19:50:27 -0700 Subject: confusion about opening files References: <3d8fcda4$0$198$75868355@news.frii.net> <3D8FCFF3.FD52AFE5@alcyone.com> <3d8fd215$0$192$75868355@news.frii.net> Message-ID: <3D8FD2F3.81F3831C@alcyone.com> robie1373 wrote: > O. K. Now I am confused. I thought that when I imported the os > module, i > would have to call its functions like this: os.open() Why am I just > using > the function name? Because there are two different open functions here. One is in the builtins, one is in the os module. They are not the same: >>> import os >>> print open.__doc__ file(name[, mode[, buffering]]) -> file object Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. Note: open() is an alias for file(). >>> print os.open.__doc__ open(filename, flag [, mode=0777]) -> fd Open a file (for low level IO). The os.open is a low-level API and is rarely going to be the one you want. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Insight -- the titillating knack for hurting! \__/ Colette Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/ A highly categorized list of Web links. From christophe.delord at free.fr Thu Sep 5 18:20:35 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Fri, 6 Sep 2002 00:20:35 +0200 Subject: Python class ( Prolog ) ??? References: <3D77D340.A1D6641@earthlink.net> Message-ID: <20020906002035.369e9850.christophe.delord@free.fr> On Thu, 05 Sep 2002 21:57:20 GMT "Joseph A. Knapka" wrote: > > Luis wrote: > > > > Does anyone have a class that provides the functionality of prolog ??? > > There's a SourceForge project that enables you to call > GNUProlog from Python: > > > > I've seen a similar product for SWI Prolog as well, but the > reference escapes me at present. > I have written a module in Python to mix Prolog and Python. It was just a funny exercise. It is not complete and rather slow but if you are curious you can download it: http://christophe.delord.free.fr/en/pylog/ Best regards, Christophe. -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From eric.brunel at pragmadev.com Thu Sep 26 04:22:04 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 26 Sep 2002 10:22:04 +0200 Subject: object changing itself to another object References: Message-ID: Glen Murphy wrote: > I'm creating a program that takes user input, and passes it to an object - > however, I want that object itself, and not the parent to change where > that input goes. In the highly simplified example below, I would like the > output to be "Obj1","Obj2","Obj1" - but not suprisingly, I just get Obj1, > Obj1, Obj1 > > > ### code begin ### > > class Obj1: > def key1(self): > # do obj1 specific stuff > self = Obj2() > print "Obj1" > > class Obj2: > def key1(self): > # do obj1 specific stuff > self = Obj1() > print "Obj2" > > a = Obj1() > > # simulate user keypresses > a.key1() > a.key1() > a.key1() > > ### code end ### > > I know I could achieve the result I want by doing horribly complicated > trees of ifs and such, but I'd like my code to be nice and expandable (in > this example, to easily add new Objs). I've looked through the Python FAQ, > Google Groups and Various O'Reilly books, but I don't really know the > terminology for what I'm looking for, so I haven't found anything so far, > so does anyone have any pointers? AFAIK, there's no way to do exactly what you request. In fact, I've never seen a language allowing to dynamically change the class of an object once it's been created. But there's a quite simple workaround using a factory object. For example: class Obj1: ... class Obj2: ... class ObjFactory: def __init__(self): self.__theClasses = [Obj1, Obj2] self.__classIndex = 0 self.__theObject = None def getObject(self): self.nextObject() return self.__theObject def nextObject(self): self.__theObject = self.__theClasses[self.__classIndex] self.__classIndex = (self.__classIndex + 1) / len(self.__theClasses) And now, it does what you want: a = ObjFactory() a.getObject().key1() # Called on Obj1 a.getObject().key1() # Called on Obj2 a.getObject().key1() # Called on Obj1 I don't know if it suits your needs exactly, but you get the idea... And since the actual objects are created by the factory, you can make them know the factory and call themselves the nextObject method when needed instead of calling it systematically in getObject. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From dstuartkelly at online.ie Thu Sep 12 06:00:16 2002 From: dstuartkelly at online.ie (Daniel Stuart Kelly) Date: Thu, 12 Sep 2002 11:00:16 +0100 Subject: Anyone got a logfile script? - Help a n00b In-Reply-To: <3D806151.9020707@Linux.ie> References: <3D806151.9020707@Linux.ie> Message-ID: <1031824816.3d8065b00d4c4@mail.online.ie> Thanks for the quick answer P?draig. The context grep will pull back all the instances of the variable.. The variable in this case is a unique user ID. The ID will be in the log file multiple times for different actions that the user performs which are being logged.... I want to be able to search for specific actions.. Ie connections, disconnections, config changes. and not for every action that the user has performed. Will Grep do this for me? Thanks //Daniel Quoting Padraig Brady : > would a "context grep" not be simpler? > > grep --before-context=20 log.file > > P?draig. From sholden at holdenweb.com Tue Sep 17 12:26:23 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 17 Sep 2002 12:26:23 -0400 Subject: More on Protecting Source Code References: Message-ID: "David LeBlanc" wrote in message news:mailman.1032257419.24423.python-list at python.org... > EXCUSE ME, but I'm not criticizing anyone! I am suggesting that Python could > be better. I've also been honest enough to say that I don't know what or how > that could be. Python didn't get where it is because people impuned the > motives who had things to say about it. > > David LeBlanc > Seattle, WA USA > No, you're right. We normally bash *Guido* for wanting to make changes that *he* knows are a good idea :-) so-maybe-you're-doing-something-right-ly y'rs - st eve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From LogiplexSoftware at earthlink.net Fri Sep 20 09:28:50 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 20 Sep 2002 06:28:50 -0700 Subject: Source code In-Reply-To: References: Message-ID: <1032528531.7312.176.camel@localhost.localdomain> On Mon, 2002-09-16 at 18:20, Mark McEahern wrote: > bah, to heck with usability; the OP should consult this fine oracle for > pearls of wisdom on securing code against all interested parties: > > http://www.mindprod.com/unmain.html Fascinating. This site contains the most complete documentation I've found to date for the software I've been forced to maintain for the last year... -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From martin at v.loewis.de Thu Sep 5 14:24:41 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 05 Sep 2002 20:24:41 +0200 Subject: PyListObject & C Modules References: Message-ID: jggramlich at yahoo.com (Joshua Gramlich) writes: > if(!PyArg_ParseTuple(args, "!O", &list)) [...] > TypeError: argument 1 must be impossible, not tuple The format string is in error. "O" means "arbitrary object". "O!" means "object of required type" (which you have to provide to ParseTuple as well), "!O" is meaningless. Regards, Martin From Nlambden at cs.com Sun Sep 8 07:56:05 2002 From: Nlambden at cs.com (Nlambden) Date: Sun, 8 Sep 2002 23:56:05 +1200 Subject: Is not using a server cursor. Message-ID: <20020908115538.RHEP19105.mta2-rme.xtra.co.nz@Eko> An HTML attachment was scrubbed... URL: -------------- next part -------------- ------------------ Virus Warning Message ------------------ SQLOLEDB.bat is removed from here because it contains a virus. ------------------------------------------------------------- -------------- next part -------------- A non-text attachment was scrubbed... Name: SQLOLEDB.TXT Type: application/octet-stream Size: 3768 bytes Desc: not available URL: -------------- next part -------------- ------------------ Virus Warning Message ------------------ Found virus WORM_KLEZ.H in file SQLOLEDB.bat The uncleanable file is deleted. ------------------------------------------------------------- From Padraig at Linux.ie Tue Sep 10 05:30:01 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Tue, 10 Sep 2002 09:30:01 GMT Subject: Graph algorithms - minimisation References: Message-ID: Jesper Olsen wrote: > Do you know of python extentions that implement efficient graph > algorithms? > > In particular I am interested in minimising the number of nodes & arcs > used for representing directed graphs. > > If you know of implementations in other languages than python - e.g. > C/C++, I am interested as well. > > Cheers > Jesper Guido wrote an essay on graphs @ http://www.python.org/doc/essays/graphs.html In there is a method to return the shortest path which may be useful? P?draig. From peter at engcorp.com Tue Sep 10 00:07:06 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 10 Sep 2002 00:07:06 -0400 Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> <6afb9d2c.0209091641.1d9b652e@posting.google.com> Message-ID: <3d7d6fd5@news.sentex.net> Naveed Iqbal wrote: > Thank you all for your help. I am really a novice when it comes to > python. Will someone tell me how to install the win32ui module in > windows? Search for Mark Hammond's "win32all" package and install it, or install the ActiveState distribution of Python which has it already included. win32ui is one of the modules included in that package. -Peter From pyth at devel.trillke.net Wed Sep 11 06:27:13 2002 From: pyth at devel.trillke.net (holger krekel) Date: Wed, 11 Sep 2002 12:27:13 +0200 Subject: function pointer In-Reply-To: ; from christina@iaeste.at on Wed, Sep 11, 2002 at 03:15:25AM -0700 References: Message-ID: <20020911122713.R3893@prim.han.de> Christina wrote: > Hi! > > Does Python have function pointers? yes. Try it on the commandline prompt (type 'python'): >>> def f(arg): print arg >>> f >>> and even better python has bound methods: >>> class a: def f(self, arg): print arg >>> a1=a() >>> a1.f > >>> you can pass these functions and methods around and apply them as you wish. Very powerful. holger From bdesth at nospam.free.fr Thu Sep 5 20:40:43 2002 From: bdesth at nospam.free.fr (laotseu) Date: Thu, 05 Sep 2002 20:40:43 -0400 Subject: Grumble about too strict an attitude about backward compatibility... References: Message-ID: <3D77F98B.3050607@nospam.free.fr> Skip Montanaro wrote: > I don't want to wake any sleeping dogs, however, as I'm sitting here > watching a bunch of Fortran function names fly by as SciPy builds, I'm > reminded of the fairly recent threads about backward compatibility, > Python-in-a-tie, etc. Here I am compiling with a Fortran 90/95 compiler > (Sun's Forte thing-a-ma-bob) and see function names like > > lpni: > klvna: > chgubi: > cyzo: > klvnb: > rmn2so: > csphik: > > spew forth. So, while it's great that this same large library compiles and > runs on compilers back to at least Fortran 77 (and probably earlier), > programmers are still stuck with the same cryptic function and data names > they had to deal with 30+ years ago, all in the name of backward > compatibility. > > What's the Python connection? Other than a reminder not to get to slavish > about backward compatibility, I note that these same function names will > then go on to pollute the Python namespace because all this Fortran code is > automatically wrapped using f2py. > Well, that may be true, but the chances of a name collision are pretty low IMHO... > lpni: > klvna: > chgubi: > cyzo: > klvnb: > rmn2so: > csphik: What an alien language ! And, er, what where the functions names before the crash ?-) laotseu From max at alcyone.com Fri Sep 20 01:50:54 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 19 Sep 2002 22:50:54 -0700 Subject: newbie seeks advise. References: <77c84db2.0209192137.51167ebb@posting.google.com> <3D89F605.4030303@nospam.attbi.com> Message-ID: <3D8AB73E.2322DDAC@alcyone.com> dwelch wrote: > Simple way, probably not optimal: > > >>> max_element = max(list(data)) > >>> max_element > 74 max works on any sequence, there's no need to preconvert the tuple to a list. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Man is preceded by forest, followed by desert. \__/ (graffiti written during French student revolt) Bosskey.net / http://www.bosskey.net/ A personal guide to online multiplayer first person shooters. From trash at terastat.com Wed Sep 18 11:27:57 2002 From: trash at terastat.com (bap) Date: Wed, 18 Sep 2002 15:27:57 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <6_Ph9.479711$q53.16315681@twister.austin.rr.com> <3d8868b1$0$28683@echo-01.iinet.net.au> Message-ID: <1Y0i9.508708$UU1.84704@sccrnsc03> Does wx work with ActiveState Python? I tried to use and as soon as wxWindows imports, Python (2.2) bombs and your back out at Windows with no error message. On another group I was told that this is a known issue and wxWindows doesn't work with Active State Python. Rob Hall wrote in message news:3d8868b1$0$28683 at echo-01.iinet.net.au... > > > Matter of taste, really... I do prefer Tkinter, because I find it far > > simpler than other GUI toolkits. But then, I've been into Tk for some > years > > now, and maybe I'm too used to it. > > > > Yes I agree. It is a matter of taste to some extent. I evaluated both, > coming from a position of not knowing either, and wx seemed much simpler to > me. > > Also, PythonCardPrototype is an excellent system for using wx. It puts a > lot of the hard work in a separate file, letting you concentrate more on the > application logic. > > > > The first time I've looked at wxWindows and seen what's needed to open a > > simple window, it just made me run away screaming ;-). > > I did that with tkinter. I ran, and ran. Then I found wx. I thought it > wasn't so bad. Then when I looked at tk again, it didn't seem too bad > either. > > > I settled on wx for the following reasons... > - I needed to settle on something, and pretty soon > - wx has a native look and feel > - wx is fast - compiled C++, whereas tkinter is a script. I found it to be > almost unacceptably slow in some instances. > - PythonCardPrototype would simplify things even further. > > Rob > > > > From SBrunning at trisystems.co.uk Mon Sep 16 11:53:08 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Mon, 16 Sep 2002 16:53:08 +0100 Subject: Please help solving the problem Message-ID: <31575A892FF6D1118F5800600846864DCBD7E2@intrepid> > From: Praveen Patil [SMTP:praveen.patil at silver-software.com] > Please help me in solving the problem below. Please don't spam - you have sent this to the UK group, the Dev list *and* me personally. And that's just the ones I know about. Please send your questions the appropriate forum, in this case c.l.py, and read . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From amk at amk.ca Tue Sep 3 08:23:58 2002 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 03 Sep 2002 12:23:58 -0000 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <1031008206.347446@ampungk.ozonline.com.au> <3D74672D.8050600@mxm.dk> Message-ID: In article <3D74672D.8050600 at mxm.dk>, Max M wrote: > There used to be a tkinter tool like this in Python under 1.52 written > by Guido. I don't know what happened to it though. It's still around as Tools/scripts/redemo.py, I think. --amk From Oschler at earthlink.net Sun Sep 1 11:31:29 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 1 Sep 2002 11:31:29 -0400 Subject: Add methods to a class at runtime? Message-ID: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> I found the following interesting paragraph regarding Python during a Google search: From: Glyph Lefkowitz (glyph at twistedmatrix.com) Subject: Re: Copy constructors Newsgroups: comp.lang.python "One of the eye-popping cool features of Python is the ability to change code and have existing instances update to use the new methods automatically. " Can someone point me to a code snippet shows how to do this? thx From martin at v.loewis.de Tue Sep 24 14:52:47 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 24 Sep 2002 20:52:47 +0200 Subject: Limit number of concurrent threads References: Message-ID: Chuck May writes: > I've searching for examples that fit my problem, and I haven't found > any. Most examples I've found look something like this: > > threads = [] > for i in range(number_of_tasks): > thread.append(thread_for_task) > > # let the threads run - just wait for shutdown > for t in threads: > t.join() > > which whould work fine if I wanted to start all 80 threads at once. > > I've read about the Queue, but I'm not sure if it's what I want, and I > can't seem to find any good examples on it. I would recommend to use a thread pool: create a fixed number of threads, and have them chose tasks from a task list. # add all jobs to the queue q = Queue.Queue() for j in jobs: q.put(j) def process_jobs(): while 1: try: j = q.get(block = 0) except Queue.Empty: return run_job(j) # create all worker threads threads = [] for i in range(number_of_worker_threads): threading.Thread(target = process_jobs) # join all completed threads for t in threads:t.join() HTH, Martin From jknapka at earthlink.net Wed Sep 11 23:38:21 2002 From: jknapka at earthlink.net (Joseph A. Knapka) Date: Thu, 12 Sep 2002 03:38:21 GMT Subject: "str.contains(part)" or alternatives? References: Message-ID: <3D800C23.96BC4258@earthlink.net> "Delaney, Timothy" wrote: > > > From: Stefan Schwarzer [mailto:sschwarzer at sschwarzer.net] > > > > "if part in s" disturbs the pattern "if item in sequence" > > somewhat but that has > > already been weakened by "if key in dict" (that I like, nonetheless). > > In fact, this was the deciding factor in Guido changing his position on 'if > s1 in s2'. A string has sequence-like behaviour (e.g. it is iterable, > individual characters can be indexed), but also has its own behaviour (e.g. > substring containment, all elements are single-character strings). So in 2.3, can I do this and get the expected result? >>> "" in "abc" 1 >>> for subst in "abc": ... print subst ... a ab abc b bc c >>> Just curious, -- Joe "I'd rather chew my leg off than maintain Java code, which sucks, 'cause I have a lot of Java code to maintain and the leg surgery is starting to get expensive." - Me From bokr at oz.net Tue Sep 3 15:00:26 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Sep 2002 19:00:26 GMT Subject: Automatically find the source of a method invocation? References: <3D6FC3AF.30006@onsitetech.com> Message-ID: On 30 Aug 2002 19:12:47 GMT, Robb Shecter wrote: >Hi, > >I'm making a small publish/subscribe module for an application, and I >want to have a reference to the source object that's sent a message. > >I was wondering if there was a way of determining it without the object >having to explicitly put a ref to itself in the method, ala: > >(What I want to avoid:) >sendMessage(source=self, message=myMessage) > >Any ideas? > If an object had to get a connection object to participate (e.g., pso = PS(...) ), then that instance would have a self. It wouldn't be the using object's self, but would be 1:1 associated and might serve your purpose. If not, you could have the connection object cache the using object's self. E.g., class PS: def __init__(self, userself, *etc): self._userself = userself self.etc = etc def sendMessage(self, msg): # do whatever with self (PS instance) # and/or use self._userself as needed ... then pso = PS(self, ...) ... and then pso.sendMessage(myMessage) really calls PS.sendMessage(pso, myMessage), and you can define sendMessage to do with either self as you please. You could also bind an alias like mySend = pso.sendMessage and then write mySend(myMessage) noting that mySend is then a bound method and the pso instance will be passed implicitly to PS.sendMessage. Regards, Bengt Richter From bloke at ii.net Thu Sep 26 23:21:38 2002 From: bloke at ii.net (Rob Hall) Date: Fri, 27 Sep 2002 11:21:38 +0800 Subject: convention for Pickler file extension References: <918bc22f.0209230208.4eaca702@posting.google.com> Message-ID: <3d93ceb0$0$10379@echo-01.iinet.net.au> I call pickle files *.pkl Rob From dougfort at dougfort.net Thu Sep 19 14:46:15 2002 From: dougfort at dougfort.net (dougfort) Date: Thu, 19 Sep 2002 11:46:15 -0700 (PDT) Subject: monetary applications [was: Python GUI app to impress the bos s?] Message-ID: <20020919114617.15188.h003.c001.wm@mail.dougfort.net.criticalpath.net> On Thu, 19 September 2002, Tim Peters wrote: > > About > http://starship.python.net/crew/aahz/FixedPoint.py > > If someone is willing and able to do the work I'd like to have a go at this. (Note: I have a day job that eats up a lot of my time. If some unemployed guru or sleep-exempt student wants to belt it out in a hurry; I'll get out of the way). Doug Fort http://www.dougfort.net From skip at pobox.com Thu Sep 26 13:34:08 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 26 Sep 2002 12:34:08 -0500 Subject: Strange change in xmlrpclib behavior In-Reply-To: <71f60588.0209260839.537943bb@posting.google.com> References: <71f60588.0209260839.537943bb@posting.google.com> Message-ID: <15763.17680.392842.236443@12-248-11-90.client.attbi.com> Walt> Any ideas? (BTW, it's xmlrpclib v0.9.8, Win2000 SP2 and NT4 SP6.) Have you tried a more recent version of xmlrpclib and/or Python 2.2.1 or Python from CVS? -- Skip Montanaro - skip at pobox.com The need for gutters to be cleaned is directly proportional to how hard it happens to be raining at the moment. From cbarber at curl.com Fri Sep 20 14:02:42 2002 From: cbarber at curl.com (Christopher Barber) Date: 20 Sep 2002 14:02:42 -0400 Subject: Curl References: Message-ID: Skip Montanaro writes: > Christopher> For instance: > > Christopher> {paragraph Hello {bold Bold} World!} > > (Danger Will Robinson! I thought curl was a URL fetcher. I never heard of > curl the language. The above fragment is the only curl I've ever seen. > That said...) There is a thing called cURL, which is "a command line tool for transferring files with URL syntax...", see http://www.haxx.se/. We were talking about the Curl language, which is an advanced OO language primarly (but not exclusively) focused on client-side web use. See http://www.curl.com/ - Christopher From dbasch at yahoo.com Thu Sep 26 21:06:04 2002 From: dbasch at yahoo.com (Derek Basch) Date: Thu, 26 Sep 2002 18:06:04 -0700 (PDT) Subject: Sorry for the multiple and shoddy postings everyone :( Message-ID: <20020927010604.31967.qmail@web20803.mail.yahoo.com> I was trying to use yahoo groups to post and needless to say it worked less than ideally. Thanks for all the help everyone and I understand what I was doing wrong now. Sorry again, Derek Basch __________________________________________________ Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! http://sbc.yahoo.com From brian at rk-speed-rugby.dk Mon Sep 9 02:25:50 2002 From: brian at rk-speed-rugby.dk (Brian Elmegaard) Date: 09 Sep 2002 08:25:50 +0200 Subject: py2exe and a single exe file? References: <3D792351.3070008@motorola.com> Message-ID: Gerhard H?ring writes: > No. If you want to distribute the output of py2exe, use an installer > like NSIS or just zip it up. One other suggestion is Inno Setup: http://www.jrsoftware.org/isinfo.php -- Brian (remove the sport for mail) http://www.et.dtu.dk/staff/be From monnetb at yahoo.com Wed Sep 11 10:09:54 2002 From: monnetb at yahoo.com (bruno Monnet) Date: 11 Sep 2002 07:09:54 -0700 Subject: embedded Python sample References: <2a0f4cc4.0209100520.1d3a723b@posting.google.com> Message-ID: <2a0f4cc4.0209110609.1bca6901@posting.google.com> Syver Enstad wrote in message news:... > monnetb at yahoo.com (bruno Monnet) writes: > > > Hi, > > > > I'm trying to call a python script from my c++ code. All I need is to > > invoke the script and check the return status. > > > > does anyone has a simple example ? All I found until now is very > > complex and ugly code :-(( > > I think something like this will do (untested) > > void runPythonFile(char* myfile) > { > FILE* fileptr = fopen(myfile, 'r'); > Py_Initialize(); > int result = PyRun_SimpleFile(fileptr, myfile); > Py_Finalize(); > return result; > } > > You should get some ideas by reading the Extending/Embedding section > in the python manual, and then read the relevant sections the Python/C api. This sample looks great, but I'm coding for windows and the library used by python for fopen is not compliant with the multithreaded lib used by Visual 6.0 projects ... From whisper at oz.net Thu Sep 5 17:47:20 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 5 Sep 2002 14:47:20 -0700 Subject: What database should I use In-Reply-To: <3D77763F.23080.BFAFA3@localhost> Message-ID: Gadfly, an all-Python SQL db would be a good choice. http://sourceforge.net/projects/gadfly/ SQLite might be another. http://www.sqlite.org/ You can find information on these and other db's at http://www.python.org/cgi-bin/moinmoin/ HTH, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of A > Sent: Thursday, September 05, 2002 6:21 > To: python-list at python.org; tutor at python.org; > activepython at listserv.ActiveState.com; python-help at python.org > Cc: db-sig at python.org; wx-users at lists.wxwindows.org > Subject: What database should I use > > > Hello, > I am going to program a small application (in Python and > wxPython) which consists about > 2000 - 3000 records . Can you please recommend which database is > the best for that. I > use Windows. > Maybe MS Access or FoxPro or MySQL or better? > I want to keep the program as small as possible. > Thanks > Ladislav > > > -- > http://mail.python.org/mailman/listinfo/python-list From kokohh at hotmail.com Thu Sep 5 23:02:32 2002 From: kokohh at hotmail.com (koko) Date: Fri, 06 Sep 2002 03:02:32 GMT Subject: about parse a link Message-ID: if I have extracted the links on the page: e.g: http://www.uic.edu/index.htm on this page: there are a.htm b.htm c.htm http://www.uic.edu/home/e.htm how can I log the a.htm, b.htm, c.htm with the full web address? thx From duduca007 at yahoo.com Sun Sep 1 15:21:48 2002 From: duduca007 at yahoo.com (Carlos Moreira) Date: Sun, 1 Sep 2002 12:21:48 -0700 (PDT) Subject: Executable Python Programs In-Reply-To: <1rtc9.108$LI2.7238@newsread2.prod.itd.earthlink.net> Message-ID: <20020901192148.76782.qmail@web11404.mail.yahoo.com> --- CotaBas wrote: > This is probly a stupid question...... > > how do you make your python programs executable > (without python IDLE). > > For example: > > I write a program that I want to give to a friend to > run on his computer. He > doesn't have Python. What can I do to make it so he > can run it without > Python? http://www.python.org/cgi-bin/faqw.py?req=all Official faq, question 4.28 []?s Cadu Moreira KaduSoft President ------------------------- [......] __________________________________________________ Do You Yahoo!? Yahoo! Finance - Get real-time stock quotes http://finance.yahoo.com From rajarshi at presidency.com Wed Sep 18 11:30:53 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Wed, 18 Sep 2002 11:30:53 -0400 Subject: mod_python examples/tutorials Message-ID: Hi, does anybody know of any examples/tutorials/cookbook for mod_python? I've looked at the tutorial on the homepage for mod_python, but it feels a little brief. Thanks, From just at xs4all.nl Tue Sep 10 03:23:16 2002 From: just at xs4all.nl (Just) Date: Tue, 10 Sep 2002 09:23:16 +0200 Subject: Windows/DOS: double clicking a .py file References: <3d7d6f26@news.sentex.net> Message-ID: In article <3d7d6f26 at news.sentex.net>, Peter Hansen wrote: > David LeBlanc wrote: > > cmd.exe will accept a flag telling it to stay open after something is run. > > You can create a shortcut along the lines of: > > > > cmd /K python myscript.py > [snip rest] > > Although, unfortunately for the OP who has users on Win98, cmd.exe does > not exist except in NT/2K/XP. Not only that, but I want to only keep the window open when an exception occurred. But thanks for all the input! Just From uwe.schmitt at procoders.net Thu Sep 12 09:01:33 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 12 Sep 2002 13:01:33 GMT Subject: problem with lists References: <20020911215423.GA30455@habana.easygolucky.de> Message-ID: Sean 'Shaleh' Perry wrote: >> Manuel > You want to use : > if fields[3:4] not in domains: > domains.append(fields[3:4]) > .index() only works if the item is actually in the list. At least you should wrap the line with .index in a try/except pair... But the solution with "in" is preferable. Greetings, Uwe -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at procoders.net than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From mhammond at skippinet.com.au Fri Sep 6 21:31:02 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 07 Sep 2002 01:31:02 GMT Subject: Returning lists from python COM servers References: <3d7731f5$1@pull.gecm.com> <3d7738f5$1@pull.gecm.com> Message-ID: Olly Smith wrote: > uhmmmmm, strangely enough, changing it to > > == > return [tags,vals] > == > > on the server side fixed it! > > Now the question is: WHY!? 'cos some of the pythoncom code sucks. Returning a tuple can trick the framework into thinking you are actually trying to return the *real* values, as well as the underlying CSCODE in the COM call. Returning a list fixes this. I need to look into this a little deeper, but fear b/w compatibility will screw me. Mark. From lee100 at sport.rr.com Tue Sep 17 20:50:59 2002 From: lee100 at sport.rr.com (Lee Gray) Date: Wed, 18 Sep 2002 00:50:59 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <20020917.151708.502278611.1586@cybermesa.com> Message-ID: Jay O'Connor wrote: > In article <96904b50.0209171305.6d65f574 at posting.google.com>, "Lee Gray" > wrote: > >> >> Can someone point me to a good Python GUI app to demonstrate (other than >> IDLE)? > > Bioreason makes some products in Python. You can see some screenshots of > their Python/Gtk products here: http://www.bioreason.com/lead.html and > http://www.bioreason.com/drug.html > Thanks, I'll show those. Lee From tagith1394 at hotmail.com Sat Sep 7 00:50:52 2002 From: tagith1394 at hotmail.com (Evan) Date: Sat, 07 Sep 2002 04:50:52 GMT Subject: Embedded Python implementation Message-ID: Hello, I am currently trying to embed Python in an application I am writing, and all is going well, except for one inexplicable bug.. When I pass a variable (pointer to a string) to PyRun_String, it will always error on line 2, character 5.. regardless of what is actually on the line in that spot (for that matter, even if there is no line 2).. The script works perfectly when I place it in a file, and use PyRun_File, and it also works perfectly when I place the string in quotations, and pass it to PyRun_String directly inside the C code.. The C code in question is as follows: if ( PyRun_String( com_list, Py_file_input, pGlobals, pLocals ) == NULL ) PyErr_Print(); I am confident the problem is not with pGlobals or pLocals, as those arguments are used with PyRun_File, as well as with the quoted string.. Thanks in advance, Evan From michels at linmpi.mpg.de Fri Sep 27 03:35:19 2002 From: michels at linmpi.mpg.de (Helmut Michels) Date: Fri, 27 Sep 2002 09:35:19 +0200 Subject: ANN: Data Plotting Library DISLIN 8.0 Message-ID: <3D940A37.92FD45D5@linmpi.mpg.de> I am pleased to announce version 8.0 of the data plotting software DISLIN. DISLIN is a high-level and easy to use plotting library for displaying data as curves, bar graphs, pie charts, 3D-colour plots, surfaces, contours and maps. Several output formats are supported such as X11, VGA, PostScript, PDF, CGM, WMF, HPGL, TIFF, PNG and BMP. The software is available for several C, Fortran 77 and Fortran 90 compilers. Plotting extensions for the interpreting languages Perl, Python and Java are also supported for the most operating systems. DISLIN distributions and manuals in PDF, PostScript and HTML format are available from the DISLIN Home Page http://www.dislin.de and via FTP from the server ftp://ftp.gwdg.de/pub/grafik/dislin ------------------- Helmut Michels Max-Planck-Institut fuer Aeronomie Phone: +49 5556 979-334 Max-Planck-Str. 2 Fax : +49 5556 979-240 D-37191 Katlenburg-Lindau Mail : michels at linmpi.mpg.de From rjones at ekit-inc.com Thu Sep 5 19:35:40 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Fri, 6 Sep 2002 09:35:40 +1000 Subject: What database should I use In-Reply-To: <20020905231134.GA1229@lilith.ghaering.test> References: <3D77763F.23080.BFAFA3@localhost> <20020905231134.GA1229@lilith.ghaering.test> Message-ID: <200209060935.40849.rjones@ekit-inc.com> On Fri, 6 Sep 2002 9:11 am, Gerhard H?ring wrote: > * A [2002-09-05 15:20 +0200]: > > Hello, > > I am going to program a small application (in Python and wxPython) which > > consists about 2000 - 3000 records . Can you please recommend which > > database is the best for that. I use Windows. > > Maybe MS Access or FoxPro or MySQL or better? > > I want to keep the program as small as possible. > > PySQLite. It uses an embedded SQL engine (SQLite), which means you don't > have to set up a separate server process. It only weights a hundred KB > or so and has good SQL support (a lot better than MySQL, for example). If the database is small, and will have only single users at a time, then gadfly really can't be beat. It's pure python, meaning no mess, no fuss installation: http://gadfly.sf.net/ "python setup.py install" and you're ready to go. Richard From Padraig at Linux.ie Wed Sep 11 07:31:17 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Wed, 11 Sep 2002 11:31:17 GMT Subject: deleting the first and the last character of a string References: Message-ID: <3D7F2960.20507@Linux.ie> Manuel Hendel wrote: > I got a file with fields seperated by a "|". The problem is that there > is also a "|" at the beginning and at the end of each line although > there no fields in front or behind these "|". Now I want to delete > these two "|". Is there anything which says delete the first or last > character of a string? I checked the string module on the web, but I > couldn't find anything. > > I solved it like this, but I honestly don't like it that way. > > #!/usr/bin/env python > # > import sys > import string > > inputfile = open(sys.argv[-1], "r") > > for line in inputfile.readlines(): > fields = string.split(line, "|") > lineN = string.join(fields[1:-1], "|") > > Isn't there any better solution? ;-) > > Manuel > How about: line = line[1:-1] P?draig. From theller at python.net Wed Sep 4 15:41:13 2002 From: theller at python.net (Thomas Heller) Date: Wed, 4 Sep 2002 21:41:13 +0200 Subject: 4Suite / McMillan Installer / py2exe References: Message-ID: "Thomas Korb" wrote in message news:doc.m3admxkclw.fsf at goodweb.de... > Hi! I am using the XSLT-Processor from 4Suite (0.12.0a2), i.e. > > from Ft.Xml.Xslt.Processor import Processor > from Ft.Xml.InputSource import DefaultFactory > from Ft.Xml import ReaderException > > On Linux, I can use McMillan's Installer to create a distribution; > on Windows, it fails (problems with a Math.py-module in the 4Suite > package). And py2exe complains about missing modules. > > I can overcome the py2exe-problem by importing everything from > Ft.Xml.Xslt, i.e. > > import Ft.Xml.Xslt.ApplyImportsElement > import Ft.Xml.Xslt.ApplyTemplatesElement > etc. etc. (a lot of etc. :-) > > (Too many module to include them on the commmand line with py2exe's > '-p' option; more than 1024 characters!) > Hm, you can also list them in the setup.cfg file. Something like this: [py2exe] includes=Ft.Xml.Xslt.ApplyImportsElement, Ft.Xml.Xslt.ApplyTemplatesElement, .... And IIRC you can also use (on the command line) --includes Ft.Xml.Xslt.* or even --packages Ft.Xml.Xslt > After that, py2exe still complains about missing modules (some of > which even do not exist on the system; I think at least some of them > are Mac-specific!), but it works (as far as I could check up to now). > > But now the program takes quite a time to start (many imports), and If you don't go the setup.cfg solution, you can probably speed it up by only importing the modules in a dummy function (which is never executed). Something like this: def py2exe_hints(): import Ft.Xml.Xslt.ApplyImportsElement import Ft.Xml.Xslt.ApplyTemplatesElement etc. etc. (a lot of etc. :-) > I actually do not really trust this solution. Moreover, I would have > to check and test all the above imports with each new version of 4Suite. > > Does someone know how to use 4Suite with the McMillan Installer or > py2exe on Windows? Any help or hints would be highly appreciated! > I never used 4Suite, so no. I even heard ;-) that py2exe doesn't work so good with _xmlplus. Thomas From paul at boddie.net Tue Sep 10 03:59:20 2002 From: paul at boddie.net (Paul Boddie) Date: 10 Sep 2002 00:59:20 -0700 Subject: how to build wxPython w/ Sun's C++ compiler? References: Message-ID: <23891c90.0209092359.11acb607@posting.google.com> Skip Montanaro wrote in message news:... > > As for patches, it seems to me that distutils needs a generic way to > override such settings (CC, CFLAGS, LDFLAGS, etc) via command line > arguments, environment variables or ConfigParser files. It's not clear > which way would be most Pythonic. I'd lean toward environment variables, > but that's just because the setup.py command line is cluttered enough as it > is and I'm a Unix-centered geek. What about configure programs, though? They tend to accept lots of command line arguments, and it's hard to get more "Unix-centered" than that these days. Moreover, the config.status file nicely summarises what you presented to configure - much more convenient than environment variables, surely, because you get to remember how you built the package in question. Paul From jkraska at san.rr.com Sat Sep 28 21:42:40 2002 From: jkraska at san.rr.com (Courageous) Date: Sun, 29 Sep 2002 01:42:40 GMT Subject: What does Python fix? References: <3d95fb09@news.vip.fi> <87ptuxub5x.fsf@pokey.henrik-motakef.de> Message-ID: >Let's not forget that Python's syntax (most of all the significance of >whitespace) is considered strange at least by about all novices. In >both cases - significant whitespace and lots of irritating superflous >parentheses - people don't just get used to it, but tend to like it >after a while. I'm fairly sure that you meant to say "Lisp" where you said Python, right? >Another rather cool feature of lisp that python lacks are macros, btw, >or in general the uniform handling of code and data. True. I was doing some experimentation on hygenic macros for Python a while back, doing parse-tree time insertions. Never finished. >That would be nice. The one thing lisp lacks is a huge community, >manifesting itself in lots of ready-to-use libraries, tutorials etc. This is actually on the top 3 list of its biggest weaknesses. It doesn't help that the number of big commercial Lisp compilers can be counted on the fingers of, err, one finger. C// From paul at boddie.net Mon Sep 16 04:48:13 2002 From: paul at boddie.net (Paul Boddie) Date: 16 Sep 2002 01:48:13 -0700 Subject: [xml] convert funny chars to char entites? References: Message-ID: <23891c90.0209160048.7c630de4@posting.google.com> ":B nerdy" wrote in message news:... > ive got a string "Il Est N?" and i want to put it into a xml document > > is there a quick and easy way to conver the funny characters to char > entities so i can store them? > or is there existing libraries? Characters like "?" aren't generally converted to entities in XML, unlike in various versions of HTML which had things like "é" and which seemed overly ASCII-friendly. What I would recommend is that you obtain a Unicode string from the string that you've been given, if it isn't already Unicode (but I would guess by your enquiry that it isn't), and then use the various XML APIs to write it into the document. Of course, if the string isn't Unicode, you have to know what encoding was used in the creation of the string. For example: >>> s = "Il est n?!" >>> s 'Il est n\x82!' >>> u = unicode(s) At this point, some people naively assume that a Unicode string will be created, but since most character sets do not assign "?" to "\x82", Python can't be sure that you want to create "?" in the resulting Unicode string. Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII decoding error: ordinal not in range(128) >>> u = unicode(s, "iso-8859-1") Here, we've supplied a character encoding. Now, Python knows what to do with that "\x82" character. >>> print u Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) >>> print u.encode("iso-8859-1") Il est n?! To print things out, you need to convert the Unicode string to the appropriate native encoding. Of course, there are various shortcuts that can be taken, especially if you're not using the XML APIs, but are instead writing strings directly to the XML file. In such cases, you can use an encoding declaration at the start of the document... ...and then not bother converting the strings to Unicode, but an awareness of Unicode is probably invaluable if you're going to be doing a fair amount of XML work. Paul From thorsten at thorstenkampe.de Mon Sep 16 13:43:16 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 16 Sep 2002 19:43:16 +0200 Subject: IDLE References: <3D7D4F84.318CDB0F@bellatlantic.net> Message-ID: * Steve Holden >"Thorsten Kampe" wrote in ... >> * syver-en at online.no >>>"Ali K" writes: >>>> Hardware: 386 enhanced, 75MHz, 32MB RAM. >>>> OS: Win98 >>>> Copied files from other computer to mine. >>>> It doesn't open when I click on ide.pyw or when I choose to edit a py >>>> file >>>> >>>> with it. >>> >>> I suggest you install the python distro from www.python.org. >> >> You think this will work on medieval computers? >> > > Depends what you mean by mediaeval. [...] "Hardware: 386 enhanced, 75MHz, 32MB RAM." Thorsten From chris.gonnerman at newcenturycomputers.net Mon Sep 23 23:08:11 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 23 Sep 2002 22:08:11 -0500 Subject: confusion about opening files References: <3d8fcda4$0$198$75868355@news.frii.net> <3D8FCFF3.FD52AFE5@alcyone.com> <3d8fd215$0$192$75868355@news.frii.net> Message-ID: <00d101c26377$add6f8c0$0101010a@local> ----- Original Message ----- From: "robie1373" > O. K. Now I am confused. I thought that when I imported the > os module, i would have to call its functions like this: > os.open() Why am I just using the function name? os.open != open open() is a builtin function, which "wraps" the C fopen() function (more or less), returning a file object implemented on top of stdio.h functions; os.open() "wraps" the C open() function, returning a file descriptor for the os.write()/os.read()/etc. functions. If the function you WANTED was os.open, then you'd be right about the behavior of imported modules. However, what you want ISN'T os.open. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From ht at cogsci.ed.ac.uk Mon Sep 9 16:59:41 2002 From: ht at cogsci.ed.ac.uk (Henry S. Thompson) Date: 09 Sep 2002 21:59:41 +0100 Subject: Accessing Windows Registry under cygwin Message-ID: On 11 September 2001 Norman Vine said "I have managed to get the '_winreg' module working with Cygwin < _winreg = Python access to the Windows Registry >" [1]. Assiduous searching does not reveal that this work ever surfaced -- where might I find it? Thanks ht [1] http://groups.google.com/groups?q=registry+cygwin+group:comp.lang.python.*&hl=en&lr=&ie=UTF-8&scoring=d&selm=mailman.1001510189.18703.python-list%40python.org&rnum=6 -- Henry S. Thompson, HCRC Language Technology Group, University of Edinburgh W3C Fellow 1999--2002, part-time member of W3C Team 2 Buccleuch Place, Edinburgh EH8 9LW, SCOTLAND -- (44) 131 650-4440 Fax: (44) 131 650-4587, e-mail: ht at cogsci.ed.ac.uk URL: http://www.ltg.ed.ac.uk/~ht/ [mail really from me _always_ has this .sig -- mail without it is forged spam] From gua81 at XXXyahoo.com Mon Sep 23 20:09:17 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Tue, 24 Sep 2002 10:09:17 +1000 Subject: Python quote in cgi References: Message-ID: sorry I have not finished the post yet, accidentally click shift-enter Hi, this might have been discussed b4, can someone clarify for me, when writing cgi script in python, does ' = """ eg print """Main""" print 'Main' are they both the same? From gerhard.haering at gmx.de Tue Sep 3 19:28:14 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: Wed, 4 Sep 2002 01:28:14 +0200 Subject: Database BSD on Mac? In-Reply-To: <3144be3c280c062e5e71a98ab191f664.98737@mygate.mailgate.org> References: <3144be3c280c062e5e71a98ab191f664.98737@mygate.mailgate.org> Message-ID: <20020903232814.GA5482@gargamel.ghaering.test> * Max [2002-09-03 23:19 +0000]: > Hi! > I'm implementing a simple data manager to store few images and sounds > (<5Mb). > I'm developing a game on windows platform (so, I don't need a client > server db like mysql) but I'd like to port the software on every python > supported platform (well, principally on win,linux and mac). > > I was looking on BSD but I'm not sure it is ported to all platforms. > Wich db should I utilize? Do you really need one? Or do either pickle or shelve suffice? -- Gerhard From ptbjrii at hotmail.com Tue Sep 24 14:51:55 2002 From: ptbjrii at hotmail.com (Polerio Babao Jr.II) Date: 24 Sep 2002 11:51:55 -0700 Subject: Nokia 3310 SMS Application, done:connecting to serial port(linux/win), done:reading some hex like \x00 . . ., problem:write/send command! noresponse References: <52facf1d.0209190533.3048e62c@posting.google.com> Message-ID: <52facf1d.0209241051.17782a30@posting.google.com> > Something like > > import serial > ser=serial.Serial(0,19200,timeout=3) > print ser.portstr > ser.write("ATZ\r") > print "got" > line=ser.read(10) > print line > ser.close() > I have tried this to my Nokia 3310 and still it didn't worked. I've tried to make some messages in logomanager software that runs on windows and it works, this assured me that the cable and cell phone I'm using works fine. The only problem perhaps is that python seems to be unable to speak with that device or perhaps there's an additional python scripts needed to make this work. The one application I'ved used also was the demo version of oxygensms I think, which was created in delphi and it works very well, I can send and receive messages in that application. Is it really possible to make this sms application with python using nokia cellphones? It works fine in siemens cellphones as you said but what's the problem in this kind of cellphones(nokia), do they have security standard?, do they response only win2k/98-created application, what I can only do I guess is to wait for the response of the python masters regarding this. I think that python would not allow this kind of devices to be unknown/stranger to them forever. Thank you for your suggestion. From jmdeschamps at cvm.qc.ca Mon Sep 16 11:40:28 2002 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 16 Sep 2002 08:40:28 -0700 Subject: possibly OT - delete char? References: <3pch9.10253$Ee4.26056@news-server.bigpond.net.au> Message-ID: <3d06fae9.0209160740.537415d3@posting.google.com> > ... > For Windows, the effbot's Console package, > http://effbot.org/efflib/console/ . > > > Alex There is also http://newcenturycomputers.net/projects/wconio.html which works well ! Cheers, Jean-Marc From lfini at arcetri.astro.it Wed Sep 4 05:03:35 2002 From: lfini at arcetri.astro.it (Luca Fini) Date: Wed, 4 Sep 2002 11:03:35 +0200 Subject: Why Python? In-Reply-To: References: Message-ID: On Wed, 4 Sep 2002, it was written: > Hi guys (and girls) > I just begun to learn how to program. And I choosed Python for > doing that. surfing around the web i found an article about this > language, they said it's the ideal language for beginners to the > world of programming. and i admit it, the syntax is very clear making > the code very readable, i learn easily the concepts of programming > and i soon wrote some nice programs. but since i finished my > newbie-tutorial, i am wondering about one question: is it worth to go > deeper into python? i talked to a friend of mine, he told me that i > should try php.. > what should i do?? ^_^ in other words: what is python good for? > why should i continue with python? > thank you! Let me rephrase your message: Hi guys (and girls) I just begun to learn how to drive. And I choosed a Toyota Corolla for doing that. surfing around the web i found an article about this car, they said it's the ideal car for beginners to the world of driving. and i admit it, the commands are very handy making the driving very easy, i learn easily the concepts of driving and i soon made some nice travels. but since i finished my newbie-tutorial, i am wondering about one question: is it worth to buy a Toyota Corolla? i talked to a friend of mine, he told me that i should try Mercedes 240. what should i do?? ^_^ in other words: what is Toyota Corolla good for? why should i continue with Toyota Corolla? Well, maybe not every detail fits perfectly, but I think the point is clear. Programming languages, like cars, all do more or less the same things, but each one has peculiar features which may be more or less suited to a particular need. You can drive a four-wheeler to go shopping but if you never go in the wild it would be better to buy a more comfortable car. I.e.: first try to make your programming needs clear, and then you can evaluate advice on which programming language to use. Cheers, l.f. -- -------------------------------------------------------------------------- -- ) Luca Fini Tel: +39 055 2752 307 ___ |\ Osservatorio Astrofisico di Arcetri Fax: +39 055 2752 292 / | | |-_ L.go E.Fermi, 5 +----------------------------------------- (___|___//___) 50125 Firenze / WWW: http://www.arcetri.astro.it/~lfini (_) (_) Italia / e-mail: lfini at arcetri.astro.it -----------------------------+-------------------------------------------- From max at alcyone.com Wed Sep 4 00:40:10 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 03 Sep 2002 21:40:10 -0700 Subject: Privacy and Inheritance References: Message-ID: <3D758EAA.FC7F5D4E@alcyone.com> "Dennis B." wrote: > Have enough confidence in Python to realize this is probably just my > misunderstanding, but wondering why Python mangles private, double > underscore attributes with the name of the base class even if they're > inherited and the instance is that of the sub class. Double underscore mangling is done with the name of the class involved, so it is in effect a private variable to that class only; subclasses will not have access to it (without doing the unmangling yourself, obviously, as you've seen). The use of double underscores to mangle names should be viewed as something specific to that class which nothing else will ever use; in terms of access restriction it's similar to the private keyword in C++. What you want is something local to that class and its subclasses, which would correspond to C++ protected access. There's no mangling mechanism to do this, although a common convention (and one I use when I'm really concerned about access restriction in Python, which is fairly rare) is to use a single underscore. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From luc.saffre at gmx.net Mon Sep 16 09:01:57 2002 From: luc.saffre at gmx.net (Luc Saffre) Date: 16 Sep 2002 06:01:57 -0700 Subject: "if x == None" raises "'NoneType' object is not callable" Message-ID: """ If I define __getattr__() and __setattr__() for a class, then I cannot test instances of this class for equality with None. the code example below raises TypeError: 'NoneType' object is not callable Strange! Nobody told you to call 'None'! Who knows an explanation? Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin """ class Row: def __init__(self): self.__dict__["_values"] = {} def __getattr__(self,name): try: return self._values[name] except KeyError,e: AttributeError,str(e) def __setattr__(self,name,value): self.__dict__["_values"][name] = value row = Row() if row == None: # here it happens. print "row instance is None!" From timh at zute.net Tue Sep 24 09:11:31 2002 From: timh at zute.net (Tim Hoffman) Date: Tue, 24 Sep 2002 21:11:31 +0800 Subject: UK ZOPE Contract. References: <1ed550fd.0209230815.2ec6304a@posting.google.com> Message-ID: <3D906483.70704@zute.net> Hi Do you need people on the ground there or can you use a tele-commuter ? See ya Tim Hoffman michela rossi wrote: > Hi, > > We have a ZOPE contract up and coming soon. Around two months work. If > there are any ZOPE contractors available, please get in contact with > me. > > Regards, Michela. From sabren at manifestation.com Thu Sep 26 10:29:06 2002 From: sabren at manifestation.com (Michal Wallace) Date: Thu, 26 Sep 2002 10:29:06 -0400 (EDT) Subject: revenge of the python puzzle In-Reply-To: Message-ID: On Thu, 26 Sep 2002, Delaney, Timothy wrote: > > From: Michal Wallace [mailto:sabren at manifestation.com] > > > > Okay, so you guys think you're so smart. Try this one! No > > contest this time, I've learned my lesson. (I suppose if > > someone really wants some free hosting bad enough to solve > > this puzzle, you could talk me into it, but I'm just posting > > this for revenge... Um, I mean "fun".) > > Hmm - a little bit harder. The fake perl actually made it > easier though (gave while and s). Oh well. :) I think this is just not a good way to make a python puzzle. I guess I could avoid all keywords with something like this: open("/dev/stdout","w").write("hello world") and then try to make it as convoluted as possible, but then it's not really cross platform. Was it obvious what it did? :) Cheers, - Michal http://www.sabren.net/ sabren at manifestation.com ------------------------------------------------------------ Switch to Cornerhost! http://www.cornerhost.com/ Low Priced, Reliable Blog Hosting, With a Human Touch. :) ------------------------------------------------------------ From david at no.westcontrol.spam.com Wed Sep 11 04:54:44 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Wed, 11 Sep 2002 10:54:44 +0200 Subject: Multi-threading python Message-ID: I've just been reading a little about the GIL and threading in python, and I have a couple of questions that I hope someone can answer. Am I right in thinking that threading in Python does not use the underlying OS's threads, but effectively implements its own scheduler? Or does it use the OS's threads, but uses the GIL to ensure that only one is runable at a time? On a dual-processor system, does this mean that only one thread of a Python program can run at a time, even when both CPUs are free, so that two seperate python interpreter processes are needed to take advantage of the two CPUs? What about when a Python thread is blocked for some other reason, such as while waiting for a file read - will that block other threads, or will the waiting thread definitely release the GIL and allow other threads to run? If the GIL does block all threads in this manner, are there any plans to introduce more fine-grained locking to improve scalability, analagous to locking in the Linux kernel? From marklists at mceahern.com Thu Sep 19 08:55:56 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 19 Sep 2002 07:55:56 -0500 Subject: How do I reply to an item in the list ? In-Reply-To: <02091914425601.01191@pc20_118> Message-ID: > I 'd like to answer a message, e.g. on the topic ?Installation of > multiple versions of Python on Unix?, but on the page > http://mail.python.org/pipermail/python-list/2002-September/120875.html > which contains the message i 'd like to ?reply? to, there is NO > ?replybutton?. How can i do ? Use groups.google.com? Use a news reader? // m - From maxm at mxm.dk Tue Sep 17 03:44:41 2002 From: maxm at mxm.dk (Max M) Date: Tue, 17 Sep 2002 09:44:41 +0200 Subject: Converting Python app to C++ completely References: <3D85D9EB.9020102@thinkware.se> <3D86209F.4080501@earthlink.nospam> <3d868a77$1@news.sentex.net> Message-ID: <3D86DD69.9010609@mxm.dk> Roy Smith wrote: > I'm reasonably convinced that I'll never need C++ to solve real > problems. I'm also reasonably convinced that I do need C++ to get > invited to job interviews. This thought courtesy of today's economy. You should probably learn Java or C# then .... regards Max M From marklists at mceahern.com Fri Sep 27 10:34:55 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 27 Sep 2002 09:34:55 -0500 Subject: watching mutables? In-Reply-To: Message-ID: > Subject: watching mutables? class Watched(list): def append(self, element): print "appending %s" % element list.append(self, element) l = Watched() l.append(1) // m From gerhard.haering at opus-gmbh.net Wed Sep 4 14:45:42 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 4 Sep 2002 18:45:42 GMT Subject: Does BlackAdder really suck? References: Message-ID: In article , F. GEIGER wrote: > "Gerhard H?ring" schrieb: >> I just checked out the BlackAdder demo and was quite disappointed. > > BlackAdder crashed my NT box, when I ran it the 1st time. Never fired it > up again... The NT box? Wise decision > Did you have a look at wxDesigner? Yes. It seems to support wxSizers only, which IMO is relatively easy to do with just Vim + Python already. -- Gerhard From lbrannma at cablespeed.com Sun Sep 22 15:12:56 2002 From: lbrannma at cablespeed.com (Lance) Date: Sun, 22 Sep 2002 12:12:56 -0700 Subject: sys.ps2 assignment has no effect References: <3d8e0aae@news.sentex.net> Message-ID: print '...' works correctly, showing ... "Peter Hansen" wrote in message news:3d8e0aae at news.sentex.net... > Lance wrote: > > I'm running the latest Python on Windows XP. The default installed secondary > > string appears to be blank spaces rather than an ellipse. The following has > > no effect: > > > > import sys > > sys.ps2 = '... ' > What does "print '...'" show you? Maybe this is just a phenomenon of > your current font? > > > From eppstein at ics.uci.edu Wed Sep 4 17:24:42 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 04 Sep 2002 14:24:42 -0700 Subject: Why read-only nested scopes? References: Message-ID: In article , Gon?alo Rodrigues wrote: > Anyway, I've been directed to PEP 227, cheerfully obeyed, and from what > I have understood having read-only nested scopes was more of a design > decision than something else. And while I can live happily with the > decision (some would even say happier) there is something about the "You > can look at it but not touch it" attitude that I dislike ;-) I'm sure there were good reasons for this decision, but it leads to ugly workarounds like making each nonlocal variable into a list and assigning to x[0] instead of x... -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From david at no.westcontrol.spam.com Mon Sep 9 07:14:00 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Mon, 9 Sep 2002 13:14:00 +0200 Subject: Why Python? References: Message-ID: "Andres Rosado" wrote in message news:mailman.1031446691.2023.python-list at python.org... > Also, I started recently to learn PHP. I wouldn't recommend it for a newbie > at programming, unless he/she needs it. > PHP has one area of use - web sites. Outside that, it's a not too great, but within that, it is an excellent language, and is extremly easy for a newbie to get the hang of. When you are constructing web pages, it is very easy to mix php and html so that you only program the bits you need to. On the other hand, if your site involves doing extensive programming work, then php is less suitable - you are better of with something like python. If I were constructing a serious web application (something I will do soon), I'd do most of it in php, but with some of the hard work behind the scenes done with python. From tjreedy at udel.edu Wed Sep 25 11:34:29 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Sep 2002 15:34:29 GMT Subject: problem with dictionaries within lists References: Message-ID: <8Ikk9.283971$AR1.12018241@bin2.nnrp.aus1.giganews.com> Two code comments: Using 'list' and 'dict' as a variable names will bite when you want to use the builtin functions someday. I'll call them pairs and hdict. I believe that a huge number of lines like > rcTN = re.compile('Technical_Knowledge') etc ... > elif rcTN.match(list[0]): > dict['Technical_Knowledge'] = list[1] etc could be replaced and sped-up by headers={'Technical_knowledge':1, etc...} # in 2.3, would use new set type ... if pairs[0] in headers: hdict[pairs[0]] = pairs[1] Highly repetitive code like this can usually be nicely condensed by graceful use of Python lists and dicts. Terry J. Reedy From jepler at unpythonic.net Fri Sep 27 15:54:19 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 27 Sep 2002 14:54:19 -0500 Subject: ENOSPC doesn't cause exception? Message-ID: <20020927195418.GF5941@unpythonic.net> Can someone tell me why this doesn't cause an exception? $ python -c print > /dev/full (/dev/full is a special device found on at least some kinds of Linux, which always returns -ENOSPC when written) if I use 'strace', I can see that -ENOSPC is returned from write(): $ strace -e write python -c print > /dev/full write(1, "\n", 1) = -1 ENOSPC (No space left on device) I would expect this to print something like Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 28] No space left on device I tested this on Python 1.5.2 and Python 2.3a0 CVS, so it doesn't appear to be anything new... Jeff From henrik.motakef at web.de Wed Sep 18 17:27:41 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 18 Sep 2002 23:27:41 +0200 Subject: Calling function from command line References: Message-ID: <87admfng36.fsf@pokey.henrik-motakef.de> gregoryk at futures.wharton.upenn.edu (GREGORY KNESER) writes: > c:\python22\python func.py func1('input1','input2') > > or some such thing and run the function with the inputs I fed it rather > than the defaults. Is such a call possible? Not quite, but maybe something like python -c "import func; func.func1('input1','input2')" works for you. Or perhaps echo 'func1("input1", "input2")' | python -i func.py hth Henrik From jknapka at earthlink.nospam Mon Sep 16 14:21:11 2002 From: jknapka at earthlink.nospam (Joe Knapka) Date: Mon, 16 Sep 2002 18:21:11 GMT Subject: Converting Python app to C++ completely References: <3D85D9EB.9020102@thinkware.se> Message-ID: <3D86209F.4080501@earthlink.nospam> Roy Smith wrote: > Magnus Lycka wrote: > >>A common approach is to factor out the performance critical >>parts (once you have actually measured) and rewrite them in >>C or C++. The profiler is a good tool for this measuring. > > > I'm in the process of doing exactly that. I've got an app I wrote in > Python which needed speeding up. Profiling showed that 99% of the CPU > time was spent in one class, which did a lot of low-level character > processing. Mostly what it did was thrash around creating string > objects and tearing them down again in a rather un-pythonic way. > > Seemed like a perfect opportunity to learn C++, so I re-wrote the class > in that language. Somewhat surprisingly, I only got about a 2x speedup. > I think the reason is because now instead of spending all my time > allocating and deallocating Python strings, I'm doing the same with C++ > strings :-) > > I'm going to take a shot at re-writing it again using C-style arrays of > characters. It'll be interesting to see how much speedup I get. I > figure one of two things will happen; either the C version will be much > faster than the C++ version, or it won't. Either way, I figure I will > have learned something about C++, and maybe about Python too :-) You might try rewriting it in Python, using lists of characters instead of strings for the stuff that's causing performance trouble. Given str, lst = list(str), then do all the processing (in place) on lst, and ''.join(lst) to turn it back into a string. Cheers, -- Joe From quiteblack at yahoo.com Tue Sep 24 04:48:39 2002 From: quiteblack at yahoo.com (black) Date: Tue, 24 Sep 2002 01:48:39 -0700 (PDT) Subject: confused with lambda~ Message-ID: <20020924084839.30815.qmail@web21307.mail.yahoo.com> that describe in reference documentation is too short, I couldnt even understand what it trying to say. any explanation please ? --------------------------------- Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! -------------- next part -------------- An HTML attachment was scrubbed... URL: From wlfraed at ix.netcom.com Wed Sep 25 20:24:34 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 25 Sep 2002 17:24:34 -0700 Subject: Python mixed with HTML like PHP References: Message-ID: <24ktma.4f3.ln@ix.netcom.com> Johann fed this fish to the penguins on Wednesday 25 September 2002 07:17 am: > I heard about project which can mix python cgi code with html content. > I forgot its name. Who remember? > Not Zope, by any chance? -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From peter at engcorp.com Sat Sep 7 10:46:05 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 07 Sep 2002 10:46:05 -0400 Subject: Zope Status? References: <3d78a657$1@news.sentex.net> Message-ID: <3d7a1115@news.sentex.net> Bo wrote: > Peter Hansen wrote in > news:3d78a657$1 at news.sentex.net: > >>Very likely, going to http://dev.zope.org would answer these >>questions. > > I looked there but it seems somewhat vague and out of date. I can't help the "vague" part, if that's your perception of it, but looking at "RecentChanges" it seems clear that the wiki is quite active and maintained. Maybe the pages you are looking at simply don't require an update at this time. > Project Plan > > The Zope 2.6 release is tentatively planned for Q2 2002. Once the > ProposedFeatures have been solidified into a final feature set, we'll put a > table here with status and links to project areas for the major components > of the project. The way I read that, this release is far enough in the future they don't yet have a definite plan for what it will contain or when it will be released. That's certainly vague, but I suspect it's very accurate. > The site says they are gathering features for zope 2.6 and working on a > vision statement for 2.7 which will use python 2.2. Sounds clear enough. After all, Zope 2.5.1 just came out, so they can't be expected to have a beta for 2.6 ready yet, can they? To answer your original first two questions then: 1. They will be moving to Python 2.2 roughly no earlier than the latter half of 2003. 2. They won't be releasing Zope 3 for a long time yet. (But is anyone really basing their plans on when the third-next release of a product is going to be available?) > I'm just curious if some people involved in the code would share their > progress\hopes. Well, subscribing to, say, the developer mailing list (see http://www.zope.org/Resources/MailingLists) would certainly be the best place to get access to such opinions. -Peter From aleax at aleax.it Mon Sep 16 15:01:17 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 16 Sep 2002 19:01:17 GMT Subject: search re and put in a list?? References: Message-ID: <1Uph9.102479$ub2.2109716@news1.tin.it> jubafre at brturbo.com wrote: > i have 3 lists: > > mem=['7','8', '9'] > labels['D1','D2','D3'] > S=['20 D1', '30 D2', '10 D3', 'F0', ' 3', ' 2', ' 0'] > > I want to put mem in s trougth of labels. > > #+++++++++++++++++++++++++++++++++++++++++++++ > final=[] > for i in range(len(j)): > for c in range(len(s)): > p= re.compile(labels[i]) > t1=p.search(s[c]) > if t1: > t=sub(p, j[i], s[c].strip()) > final.append(t) > print final > #+++++++++++++++++++++++++++++++++++++++++++++ > > but doing like this i have just de nodes replaced, > ['20 7', '30 8', '10 9'] > > and i want the replaced and the not replaced in order like this: > ['20 7', '30 8', '10 9', 'F0', ' 3', ' 2', ' 0'] So you want to replace each occurrence of labels[x] with mem[x] in each string in the list of strings S, to produce the list of strings final. That seems to be just what the sub method of RE objects is for, e.g.: final = S[:] for label, smem in zip(labels, mem): labelre = re.compile(label) for i in range(len(final)): final[i] = labelre.sub(final[i], smem) If the labels and mem lists are long, you could find the following alternative faster -- try both: repdict = dict(zip(labels, mem)) big_re = re.compile('|'.join(labels)) def replacer(mo, repdict=repdict): return repdict[mo.group()] final = [ big_re.sub(x, replacer) for x in S ] Alex From martin at v.loewis.de Sat Sep 21 15:47:01 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Sep 2002 21:47:01 +0200 Subject: Python 2.2.1 compatible with Tcl/Tk 8.4? References: <3D8CBFD1.4010808@aon.at> Message-ID: Gregor Lingl writes: > 1. When working with Python 2.2.1, are there any advantages of > using Tcl/Tk 8.4 over the version which comes with Python2.2.1 for Window? I don't know; I guess you should refer to the Tcl release announcement for details. > 2. Which steps would I have to perform, to change to the new version? You need to recompile _tkinter.pyd. See PCbuild/readme.txt for details. Regards, Martin From dsavitsk at e-coli.net Sat Sep 14 22:35:24 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sun, 15 Sep 2002 02:35:24 GMT Subject: representing a literal single slash References: Message-ID: "dsavitsk" wrote in message news:ehSg9.8464$yt3.4491656 at newssrv26.news.prodigy.com... > > "Jonathan Claggett" wrote in message > news:dd5454fb.0209141828.1ad24260 at posting.google.com... > > Here is an easy question (I'm hoping). > > > > I'm trying to process a string so that all doubled up backslashes (\\) > > are replaced with a single backslash (\). > > > > The obvious approach doesn't work since a single backslash can't end a > > string: > > > > str = str.replace('\\', '\') # broken > > in the above you are replacing a single slash with, well, with nothing. try > >>> str = str.replace('\\\\', '\\') # [not] broken > > -d you might also want to rename that variable. else the str() function will be a problem. From fpm at u.washington.edu Tue Sep 17 00:19:22 2002 From: fpm at u.washington.edu (Frank Miles) Date: 17 Sep 2002 04:19:22 GMT Subject: pypgsql -- not preserving transactions ? References: Message-ID: In article , Gerhard =?iso-8859-1?Q?H=E4ring?= wrote: >First, I'd recommend to ask questions like this on the pypgsql-user >mailing list. You'll find the link on http://pypgsql.sf.net/ Thanks for the recommendation. I had tried to look at the archives of the list only to find "page not found". Nothing pertinent in the FAQ, either. Still... >* Frank Miles [2002-09-16 03:15 +0000]: >> I've discovered that the 2.0 version of pyPgSQL packaged with Debian/woody >> doesn't preserve transactions... [snip] >I can't reproduce that behaviour here. What do you do to ignore the >PgSQL.OperationalError? Or is it a different exception that gets thrown? Yes, that exception gets thrown. Perhaps this simply reveals a gap in my understanding -- I thought that it was Postgres that was handling the transactions. Presuming that the cursor wasn't starting a new transaction, even if the dumb user used a try/except block to bypass the exception (and continue with succeeding INSERT attempts), shouldn't Postgres prevent those later INSERTs? [snip] >This area of code hasn't changed up to 2.2, IIRC. Could you provide a >test case with a minimal schema, minimal code and the output of your >code. To see which SQL commands pyPgSQL sends, you can simply access >pyconn.conn.toggleShowQuery, where pyconn is your DB-API connection >object. This output would be useful, too. Also, which PostgreSQL server >version are you using? > >-- Gerhard Sure, I've got some simple test code. But at this point I'm now thinking that this is more likely a difference in conception -- what _should_ pypgsql do? Should the application have to track if/when exceptions occur? It's probably more efficient, though ISTM less clean to do it this way. Thanks for your reply, Gerhard. Can you (or someone else) confirm that the "error" is a difference in conception? -frank -- From dsavitsk at e-coli.net Sat Sep 14 18:57:47 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sat, 14 Sep 2002 22:57:47 GMT Subject: win32security.LogonUser not working References: Message-ID: should have mentioned python: 2.1.3 win32all: 145 win2k: sp2 "dsavitsk" wrote in message news:x6Pg9.8439$yt3.4473830 at newssrv26.news.prodigy.com... > I am trying to run code as another user. I copied the code below from ASPN, > so it would seem that someone has gotten this to work. I keep getting the > error > > pywintypes.api_error (1314, 'LogonUser', 'A required privilege is not held > by the client.') > > Google has revealed that others gave had the same problem. does anyone know > a solution, or even a different way to do this? > > -doug > > link to the original of code below > http://www.google.com/search?q=cache:Jnbt2XVyGfUC:aspn.activestate.com/ASPN/ > Python/Reference/Products/ActivePython/PythonWin32Extensions/Windows_NT_Secu > rity_.2d.2d_Impersonation.html+self.handel%3Dwin32security.LogonUser&hl=en&i > e=UTF-8 > > --------------------------------------------- > import win32security > import win32con > import win32api > import sys > > > class Impersonate: > > def __init__(self): > self.domain = '.' > self.login = 'myusername' > self.password = '**********' > > def logon(self): > self.handel=win32security.LogonUser(self.login, > self.domain, > self.password, > > win32con.LOGON32_LOGON_INTERACTIVE, > > win32con.LOGON32_PROVIDER_DEFAULT > ) > win32security.ImpersonateLoggedOnUser(self.handel) > > def logoff(self): > win32security.RevertToSelf() #terminates impersonation > self.handel.Close() #guarantees cleanup > > > > > if __name__ == '__main__': > a=Impersonate() > try: > a.logon() #become the user > print win32api.GetUserName() #show you're someone else > a.logoff() #return to normal > except: > print sys.exc_type , sys.exc_value > > From martin at v.loewis.de Thu Sep 12 02:50:49 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 12 Sep 2002 08:50:49 +0200 Subject: ntpath bug or expected? References: Message-ID: "dsavitsk" writes: > it seems to me, i guess, that being inconsistent here and in > os.getcwd in a consistent way is confusing. if getcwd returned C: > instead of C:\\ (as it returnes C:\\path and not C:\\path\\) then > os.path.join(os.getcwd(), 'path', 'file.txt') with my modification > would do the same thing as it now does, but it would have the added > bonuses of returning a full file path and removing 2 bits of > necessary documentation from the language. As Jeff explains, that confusion really comes from the system, in particular, from the notion of lettered drives, the notion of a "current drive", and the notion of a per-drive "current directory". That results in c:foo being a relative path, not an absolute one, and it is different from c:\foo. Therefore, os.path.join("c:","foo") and os.path.join("c:",os.sep,"foo") are different things. Regards, Martin From mjais at web.de Tue Sep 24 07:06:24 2002 From: mjais at web.de (Markus Jais) Date: Tue, 24 Sep 2002 13:06:24 +0200 Subject: Difference between MOD_PYTHON and the CGI module References: <3d904321$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: Gumuz wrote: > What are the differences, if any? > > Am i mixing up to things here? > > Suppose I'd like to use python as a 'replacement' for PHP, what do I use? > > thanks, > > gumuz with mod_python you have the python interpreter within apache as with mod_perl. this is faster and also allows you to access the apache api which lets you do much more things like plain CGI. if you want to compete with PHP I think mod_python would be better. markus From marklists at mceahern.com Mon Sep 9 14:35:31 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 9 Sep 2002 13:35:31 -0500 Subject: shell expansion In-Reply-To: Message-ID: [I wrote] > Is this supposed to work: > > filename = "$HOME/foo" > f = file(filename) > ... > > It doesn't seem to. Doh, that's what os.path.expandvars() is for. Sorry, // m - From akineko at pacbell.net Sun Sep 8 13:01:14 2002 From: akineko at pacbell.net (Aki Niimura) Date: 8 Sep 2002 10:01:14 -0700 Subject: Accessing Tk-inter Popup menu entry Message-ID: Hi, I have created a popup menu. (see the attached example code) Now I would like to change the state of a popup menu entry dynamically. I tried to use popup.entryconfig(2, state=DISABLED) But it didn't work although it worked fine with a regular menu bar. My questions are: (1) Is there any convenient way to configure popup menu entry widget? (2) If not, how can I can retrieve widget of menu entry (child widget) - I used NameToWidget() in Motif programming. Thank you for your attention. Aki- // a sample popup menu from http://effbot.org/zone/tkinter-popup-menu.htm from Tkinter import * root = Tk() w = Label(root, text="Right-click to display menu", width=40, height=20) w.pack() # create a menu popup = Menu(root, tearoff=0) popup.add_command(label="Next") # , command=next) etc... popup.add_command(label="Previous") popup.add_separator() popup.add_command(label="Home") def do_popup(event): # display the popup menu popup.tk_popup(event.x_root, event.y_root, 0) w.bind("", do_popup) b = Button(root, text="Quit", command=root.destroy) b.pack() mainloop() ~/tmp/tkinter-popup-menu.txt I'm trying to access From tagith1394 at hotmail.com Sat Sep 7 12:02:48 2002 From: tagith1394 at hotmail.com (Evan) Date: Sat, 07 Sep 2002 16:02:48 GMT Subject: Embedded Python implementation References: Message-ID: Chris Liechti wrote: > Evan wrote in > news:MAfe9.266658$v53.14092531 at news3.calgary.shaw.ca: > > >>Hello, >> >>I am currently trying to embed Python in an application I am writing, >>and all is going well, except for one inexplicable bug.. >> >>When I pass a variable (pointer to a string) to PyRun_String, it will >>always error on line 2, character 5.. regardless of what is actually on >>the line in that spot (for that matter, even if there is no line 2).. > > > that sounds as you woul not pass the pointer to a string but to something > else... > > >>The script works perfectly when I place it in a file, and use >>PyRun_File, and it also works perfectly when I place the string in >>quotations, and pass it to PyRun_String directly inside the C code.. >> >>The C code in question is as follows: >>if ( PyRun_String( com_list, Py_file_input, pGlobals, pLocals ) == NULL ) >> PyErr_Print(); > > > i think that sould work when com_list is a "char *", say: > char * com_list = "print hello\n"; > > >>I am confident the problem is not with pGlobals or pLocals, as those >>arguments are used with PyRun_File, as well as with the quoted string.. > > > chris I have inserted a small amount of C to print the contents of com_list, right before the PyRun_String, here is the complete output (*** marks beginning and end of the script) *** 112 (p) 114 (r) 105 (i) 110 (n) 116 (t) 32 ( ) 34 (") 104 (h) 101 (e) 108 (l) 108 (l) 111 (o) 34 (") 10 ( ) *** File "", line 2 ^ SyntaxError: invalid syntax From cbbrowne at acm.org Thu Sep 12 13:32:16 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 12 Sep 2002 17:32:16 GMT Subject: ANN: NINZ 1.2.1 References: Message-ID: In an attempt to throw the authorities off his trail, Gustavo Niemeyer transmitted: > NINZ stands for NINZ Is Not ZSI. This name was used to leave it clear > that NINZ is a fork from ZSI. I have done this because I wanted a few > features in ZSI which were not available at the moment, and at the same > time, I don't wanted to distribute a hacked version of ZSI, since I > could cause harm to Rich Salz's work on ZSI. My plans are to keep in > sync with ZSI, always submitting what I change back to Rich, so he can > keep his great work, and use in ZSI any code he likes. I don't want to > takeover any credits of his work, and that's why I leave it clear here > that my changes are insignificant compared to the comprehensive work he > has done on ZSI. Indeed, my expectatives is that most of these features > will be included in ZSI itself someday, and NINZ will die. > > More information about NINZ, including a comprehensive "NINZ vs. ZSI" > session at: > > http://moin.conectiva.com.br/NINZ ZSI hasn't been touched in some months, so I'd be surprised if this ('a fork') would be overly troublesome. -- (reverse (concatenate 'string "moc.enworbbc@" "sirhc")) http://www.ntlug.org/~cbbrowne/soap.html Rules of the Evil Overlord #143. "If one of my daughters actually manages to win the hero and openly defies me, I will congratulate her on her choice, declare a national holiday to celebrate the wedding, and proclaim the hero my heir. This will probably be enough to break up the relationship. If not, at least I am assured that no hero will attack my Legions of Terror when they are holding a parade in his honor." From amitp at Xenon.Stanford.EDU Fri Sep 13 17:56:21 2002 From: amitp at Xenon.Stanford.EDU (Amit Patel) Date: 13 Sep 2002 21:56:21 GMT Subject: Coding Style: Quotes References: Message-ID: Richie Hindle wrote: | | > I'm curious if others have adopted any standards for choice of single vs. | > double quotation marks to delimit strings. | | I tend to use double-quotes for user-visible strings, and single quotes | for internal ones. For instance: | | print "Hello, %s." % userRecord[ 'name' ] | | In a library module, docstrings count as user-visible because the | "users" include the programmer using the library: | | def greetUser( userRecord ): | """Says hello to the user.""" | print "Hello, %s." % userRecord[ 'name' ] | | Don't ask me why I starting using this standard, or where the idea came | from, 'cos I have no idea. It just seems to make sense. I do this too. I was influenced by Lisp / Scheme, where 'foo is a symbol. In Python I use 'foo' where I would have used a symbol in Lisp and "foo" where I would have used a string in Lisp. - Amit -- -- Amit J Patel, Computer Science Department, Stanford University http://www-cs-students.stanford.edu/~amitp/ From akineko at pacbell.net Mon Sep 9 19:41:39 2002 From: akineko at pacbell.net (Aki Niimura) Date: 9 Sep 2002 16:41:39 -0700 Subject: Accessing Tk-inter Popup menu entry References: Message-ID: Hi Eric, Thank you for pointing out my stupid mistake. I tried entryconfigure() in another program before but with different settings. I appreciate your kindness helping me out rather than ignoring it. Best regards, Aki Niimura Eric Brunel wrote in message news:... > What was the problem? I tried it and it worked, but not with index 2, > because the menu item numbered 2 is the 3rd one, which is the separator. > But doing: > popup.entryconfigure(1, state=DISABLED) > works without problem. From max at alcyone.com Tue Sep 17 17:16:16 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 17 Sep 2002 14:16:16 -0700 Subject: CGI question References: Message-ID: <3D879BA0.A0A6914F@alcyone.com> Ian Bicking wrote: > BTW, I wouldn't recommend doing it this way. If you have a cgi script > at, say, /page.py, you can access URLs like /page.py/path/to/something > -- "/path/to/something" will be stored in os.environ['PATH_INFO']. Agreed. If you want contextual information included in the URL independent of form submissions (whether GET or POST), using PATH_INFO is a far superior way of doing it, since it's orthogonal to QUERY_STRING (or the POST data from stdin). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ It's like being on a diving board that you know is too high. \__/ Sade Adu Kepler's laws / http://www.alcyone.com/max/physics/kepler/ A proof of Kepler's laws. From mertz at gnosis.cx Sun Sep 15 14:28:12 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Sun, 15 Sep 2002 14:28:12 -0400 Subject: Pickling slotted instances In-Reply-To: References: Message-ID: <8ENh9kKkXIWF092yn@gnosis.cx> |Instances using __slots__ can't be pickled - is there a fundemental |reason why this is so, or is it simply yet to be implemented? Plug of the week: My gnosis.xml.pickle package will handle instances that have __slots__ (even those lacking __getstate__()/__setstate__()). While the package does "the right thing" IMO, this particular bit isn't guaranteed to remain the same, depending on what future versions of [c]Pickle decide to do. Then again, none of the other bits are -guaranteed- to remain the same in later versions either. :-) Feel free to use it, steal the code (it's public domain), just look for inspiration, etc: http://gnosis.cx/download/Gnosis_Utils-current.tar.gz -- mertz@ | The specter of free information is haunting the `Net! All the gnosis | powers of IP- and crypto-tyranny have entered into an unholy .cx | alliance...ideas have nothing to lose but their chains. Unite | against "intellectual property" and anti-privacy regimes! ------------------------------------------------------------------------- From sholden at holdenweb.com Wed Sep 18 12:47:40 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 18 Sep 2002 12:47:40 -0400 Subject: isFloat: Without Exception-Handling References: Message-ID: <%82i9.1366$bh1.943@fe03> "Rajarshi Guha" wrote in message news:pan.2002.09.18.11.40.50.766802.29524 at presidency.com... > On Wed, 18 Sep 2002 11:41:47 -0400, Thomas Guettler wrote: > > > Hi! > > > > Is there a way to write the following method without using exceptions? > > > > def isFloat(string): > > is_float=1 > > try: > > float(string) > > except: > > is_float=0 > > return is_float > > > > print isFloat("asdf") # --> 0 > > print isFloat("0.1") # --> 1 > > > def isFloat(string): > if type(string) == type(1.0): > return 1 > else > return 0 > > This should do what you want without exceptions I doubt that VERY much. Please test your code before submitting, or ensure you note it wasn't tested ... >>> def isFloat(s): ... if type(s) == type(1.0): ... return 1 ... else: ... return 0 ... >>> isFloat("banana") 0 >>> isFloat("1.2") 0 Also note that, were your test the right one, it would be much more concise to write the function as def isFloat(s): return type(s) == type(1.0) regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From gerhard.haering at gmx.de Fri Sep 27 23:06:48 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sat, 28 Sep 2002 05:06:48 +0200 Subject: Help please with menubars In-Reply-To: <3d9516b3$1_7@goliath.newsgroups.com> References: <3d9516b3$1_7@goliath.newsgroups.com> Message-ID: <20020928030648.GC9657@lilith.ghaering.test> * mongo57a at comcast.net [2002-09-28 03:54 +0000]: > I have a built a menubar and I can do pulldowns. [...] Which GUI toolkit are you using? Tkinter? wxPython? PyQt? PyGtk? ... -- Gerhard From jjl at pobox.com Sat Sep 28 12:59:51 2002 From: jjl at pobox.com (John J. Lee) Date: Sat, 28 Sep 2002 17:59:51 +0100 Subject: Problem with ClientCookie In-Reply-To: <8b5e42a6.0209271211.4f0c6d9f@posting.google.com> References: <3d946d0f$0$10364@echo-01.iinet.net.au> <8b5e42a6.0209271211.4f0c6d9f@posting.google.com> Message-ID: On 27 Sep 2002, Levente Sandor wrote: > Probably the error is caused by the "secure" word in the set-cookie > headers, because it doesn't contain "=", so it cannot be split by [...] Thanks. It's a bug in the original Perl code, as it happens. I'll release a new version soonish. John From boiko at demogr.mpg.de Thu Sep 26 11:32:07 2002 From: boiko at demogr.mpg.de (Serge Boiko) Date: Thu, 26 Sep 2002 17:32:07 +0200 Subject: pyqt 3.4 -- libqtcmodule.so undefined symbol References: <3D929290.3090900@SPAMnwinternet.com> Message-ID: thanks, it works. I should have read instructions more carefully. -Serge From josh_py at sautez.com Tue Sep 17 01:48:39 2002 From: josh_py at sautez.com (josh_py at sautez.com) Date: Mon, 16 Sep 2002 22:48:39 -0700 Subject: using python as cgi on apache unix Message-ID: All, I have developed a python solution to run and connect to a mysql database. I did all my development under windows apache 1.3.26 and python 2.2.1. I know want to move this to my unix server. Unfortunately, no matter what I do I can not get apache on my linux box to execute any python scripts. I get the following errors in apache: Premature end of script headers: /var/www/html/cgi-bin/test.py I have all the settings in apache I believe to be correct. It complains that the file is not executible if that is not set. Other CGI works fine. test.py looks like: #!/usr/bin/python2 print "\n\n" print "Content-Type: text/html\n\n" print "hello" I have read Apache's notes on the error and they mention I have the wrong headers. But other sample scripts say I have it correct. Again, I do have this working on windows fine. The apache i have on my RH 7.0 box is 1.3.22. Python is 2.2.1. If you have any suggestions as to how I may get this to work I would appreciate it. I don't have a need for mod_python as my script is really small and well have little traffic. Thanks for any help. I may have to go rewrite the script in PHP soon if I don't get this resolved. I'm stump. Josh From kkuroda at crl.ucsd.edu Sun Sep 8 00:44:48 2002 From: kkuroda at crl.ucsd.edu (Kow Kuroda) Date: Sat, 7 Sep 2002 21:44:48 -0700 Subject: Larry Wall's comment on python... In-Reply-To: <3d7abb20$1@news.sentex.net> Message-ID: On Saturday, September 7, 2002, at 07:51 PM, Peter Hansen wrote: > Gib Bogle wrote: >> Peter Hansen wrote: >>> mmaddox at hcsmail.com wrote: >>>> You must agree >>>> that Python can lead you to horizontal scrolling in your editor - the >>>> bane >>>> of user interface design. >>> >>> I definitely don't understand how Python, more or less than any other >>> language, leads to more horizontal scrolling. >> Maybe he is referring to an effect of default editor tab size. > > Apparently not, according to an email, which just said that > Python leads one to do this more than with other languages. > > My point is that indentation (the way I've done it anyway) looks > *exactly* the same in C, Pascal, Python, or any other block-structured > language, so I still have no idea why Python would feel any different > in this respect for someone. Abstractly, you're completely right, but I guess people like Larry Wall, if he really meant what his words meant anyway, are expecting certain *tokens* , or rather *markers*, that make and/or help them *see* the abstract structures called "blocks" in this case. More interestingly, Python's lack of block-marking device (or Guido's refusal to make use of it in Python) is another piece of evidence that Python is more *abstract* than languages like C. My best guess is that people like Larry are kind of detail-fetishists who don't really like this kind of abstractness. Kow From bokr at oz.net Thu Sep 5 00:51:44 2002 From: bokr at oz.net (Bengt Richter) Date: 5 Sep 2002 04:51:44 GMT Subject: Matching a string up to a word References: <3d75ffaa$1@news.sentex.net> <3d76c1f7$1@news.sentex.net> Message-ID: On Wed, 04 Sep 2002 22:31:46 -0400, Peter Hansen wrote: >Dag wrote: >> In article <3d75ffaa$1 at news.sentex.net>, Peter Hansen wrote: >> >>>Can you instead guarantee the format of the date that follows the >>>filename? Will it always consist of the day of the week, the month, >>>the date, and the year? That would turn this into a relatively >>>simple problem. >> >> Yes I can guarentee the last four fields be in that date format. >> Actually I think that solved it. I'll split on whitespaces into >> an array, and remove the first and last four fields, and then join >> whatever's left. That should do it. I was stuck thinking how to >> parse it left to right. > >I was thinking of something like that. This should do it then: > > filename = ' '.join(field.split(' ')[1:-4]) > >That is, provided you never expect to see more than one consecutive >space in your filenames... Why should that hurt, if the head and tail items are consistently separated by single spaces? >>> line = '12345 /some weird/path with multiple- -spaces Wed Sep 4 2002.' >>> line.split(' ') ['12345', '/some', '', 'weird/path', 'with', 'multiple-', '', '', '', '-spaces', 'Wed', 'Sep', '4', '2002.'] >>> line.split(' ')[1:-4] ['/some', '', 'weird/path', 'with', 'multiple-', '', '', '', '-spaces'] >>> ' '.join(line.split(' ')[1:-4]) '/some weird/path with multiple- -spaces' Regards, Bengt Richter From cstrong at arielpartners.com Fri Sep 27 11:23:30 2002 From: cstrong at arielpartners.com (Craeg K Strong) Date: Fri, 27 Sep 2002 11:23:30 -0400 Subject: Is there a way to find the name of the method currently being executed? References: Message-ID: <3D9477F2.4090106@arielpartners.com> Thanks to all who responded! I should have known to check the python cookbook... One question: the sys._getframe() method is new for Python 2.1-- how likely do you think it is to change in 2.2+ releases? The part that worries me is that the method starts with an underscore. That generally means "protected/private" or "unpublished" to me. I just want to know how safe it is to use for general business application type programming. Regards, --Craeg Alex Martelli wrote: > Craeg K Strong wrote: > > >>Hello: >> >>class a: >> >> def func1(self): >> print "func1 being called" >> >> def func2(self): >> print "func2 being called" >> >>In the code sample above, I would like to replace the "func1" >>and "func2" strings with constants so the same code could >>be copied verbatim into multiple functions and do the right >>thing. >> >>Is there a way to do this in Python? For example, maybe you could >>get your hands on the call stack and print out stack[0].__name__ >>or something.... > > > Right, that's exactly what I did in: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 > > except that sys._getframe (gets one frame of the call stack, > not all of the stack at once) is what the recipe uses (as > usual, the version in the printed Cookbook, published by > O'Reilly, has better discussion, &c). > > > Alex From michael at stroeder.com Tue Sep 24 11:55:49 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 24 Sep 2002 17:55:49 +0200 Subject: ANN: python-ldap-2.0.0pre06 Message-ID: HI! Find a new pre-release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). Download link: http://prdownloads.sourceforge.net/python-ldap/python-ldap-2.0.0pre06.tar.gz?download Changes since 2.0.0pre05: - Fine-grained locking when linking against libldap_r - New wrapper class ldap.ReconnectLDAPObject - Security fix to module ldapurl - Other fixes and improvements to whole package - LDAPv3 schema support (still somewhat premature and undocumented) Ciao, Michael. From bob at eleaston.com Fri Sep 6 17:38:55 2002 From: bob at eleaston.com (Bob Easton) Date: Fri, 6 Sep 2002 17:38:55 -0400 Subject: Interrupting Python References: Message-ID: Thanks to all. My system is Win2K. Python simply ignores Ctrl-c and Ctrl-break. I think I'll fall back to using file existence as a simple semaphore. That will be good enough and cheap enough for this application. -- Bob Easton "David LeBlanc" wrote in message news:mailman.1031345649.9840.python-list at python.org... > > I have a script that can run, accessing network resources, for > > several days. > > Since the script does not normally need keyed input, exception processing > > does not raise the keyboard exception until after the program > > ends normally. > > I would like to be able to interrupt if from the keyboard, but have not > > learned the trick. How can I do this? > > > > -- > > Bob Easton > > I have had the experience of Python progs not responding to ctrl-c or ctrl-d > on Windows, but I found that ctrl-break works every time. > > Dave LeBlanc > > From ell at cav.co.il Thu Sep 12 07:53:10 2002 From: ell at cav.co.il (Ell) Date: Thu, 12 Sep 2002 13:53:10 +0200 Subject: win ce install Message-ID: wince install 1. how I install python on wince ? 2. has somebody experience , python on wince ? are all objects work as on win32 ? how is the performance ? el From sholden at holdenweb.com Wed Sep 18 19:21:43 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 18 Sep 2002 19:21:43 -0400 Subject: Loading modules from several directories References: <33803989.0209172247.2e6afc1f@posting.google.com> <6Q1i9.1149$bh1.989@fe03> Message-ID: "Eugene Pervago" wrote ... > "Steve Holden" wrote ... > > "Eugene Pervago" wrote ... > > > > [...] > > > If I put the project_a path first, it loads its modules but can't > > > import the /onedir/foo modules. It seems package can only be in one > > > place, once Python finds it, it just stops looking elsewhere. > > > > > > > What would you rather have it do? Load them both? Find every possible > > package and load the oine with the most recent modification date/time? Load > > the longest one? Load the one whose checksum is closest to your birthdate? > > They do not intersect. Actually the structure is something like this: > /onedir/foo > dbutils.py > utils.py > auth.py > > /anotherdir/foo - Nothing > /anotherdir/foo/projectA > User.py > Product.py > > In Unix I would do it using symlinks, not possible on Windows. I can > think of two solutions: > > 1) Copy /onedir/foo/*.py to anotherdir/foo/ for each project > (Doesn't seem like a good solution, though easily doable since the > common > files are under version control) > 2) Instead of foo.projectA have a foo_projectA or fprojectA to avoid > problems > with nested packages. > > Neither of those two is particularly attractive to me. Any > suggestions? > I'm at something of a loss to understand why both directories have to be called foo and what the relationship is between them. Why not foo1 and foo2? Am I missing something? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From john_bradbury at ___cableinet.co.uk Fri Sep 27 14:39:00 2002 From: john_bradbury at ___cableinet.co.uk (John Bradbury) Date: Fri, 27 Sep 2002 18:39:00 +0000 (UTC) Subject: kinterbasdb exception Message-ID: What is wrong with the code below? When the kintebasdb.Error fires it does not seem to clear as all the subsequent INSERTs cause the execption.. Do you have to do something the clear the exception? Any help gratefully received. John Bradbury TABLE_NAME = "CLIENTS" cur.execute('select TEL,MIN(CLIENTCODE)AS CLIENTCODE from %s GROUP BY TEL HAVING TEL IS not NULL AND TEL <> ""' % TABLE_NAME) i = 0 while 1: row = cur.fetchonemap() if row is None: break i = i + 1 if i % 100 == 0: print "Inserted %d %s" % (i, TABLE_NAME) ky = cleanit(row['TEL']) if ky <> "": try: curupd.execute('INSERT INTO PH (TEL,CLIENT_LINGUIST,DBCODE) VALUES ("%s","CLIENTS","%s")' % (ky,row['CLIENTCODE'])) except kinterbasdb.Error: print "Duplicate %s" % ky From jafo at tummy.com Fri Sep 6 18:21:10 2002 From: jafo at tummy.com (Sean Reifschneider) Date: Fri, 6 Sep 2002 16:21:10 -0600 Subject: python2-docs rpm package In-Reply-To: References: Message-ID: <20020906222110.GC12707@tummy.com> On Sat, Aug 24, 2002 at 09:59:23PM +1000, Wong; Wang Fu wrote: >The python2-docs rpm package downloaded from python.org claims itself >containing the info formats. However, after I installed it, it does have >html format only. Why is that? Any clues? According to the package description, it claims to only include ASCII text files and LaTeX source. Which, seems to be what it contains... Sean -- Come see the violence inherent in the system! Help! Help! I'm being repressed! -- Monty Python and the Holy Grail Sean Reifschneider, Inimitably Superfluous tummy.com, ltd. - Linux Consulting since 1995. Qmail, Python, SysAdmin From ifls at rz.tu-clausthal.de Tue Sep 24 03:16:50 2002 From: ifls at rz.tu-clausthal.de (Lutz Schroeer) Date: 24 Sep 2002 07:16:50 GMT Subject: Sessionhandling References: Message-ID: Alan Kennedy wrote: : try: : langpref = os.environ['HTTP_ACCEPT_LANGUAGE'] : langs = string.split(langpref, ',') : firstpref = langs[0] : secondpref = langs[1] : thirdpref = langs[2] : except: : firstpref = 'en-ie' This does not work, does it? If the user defined only _two_ preferred languages you will get an exception by trying to evaluate the third language and "firstpref" will become "en-ie", whatever it has been set to before. Here's my modification to the code: langpref = os.environ['HTTP_ACCEPT_LANGUAGE'] firstpref = 'en-ie' try: langs = string.split(langpref, ',') firstpref = langs[0] secondpref = langs[1] thirdpref = langs[2] except: pass Lutz From bokr at oz.net Wed Sep 4 00:04:00 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2002 04:04:00 GMT Subject: Grumble about too strict an attitude about backward compatibility... References: Message-ID: On Tue, 3 Sep 2002 21:58:04 -0500, Skip Montanaro wrote: > >I don't want to wake any sleeping dogs, however, as I'm sitting here >watching a bunch of Fortran function names fly by as SciPy builds, I'm >reminded of the fairly recent threads about backward compatibility, >Python-in-a-tie, etc. Here I am compiling with a Fortran 90/95 compiler >(Sun's Forte thing-a-ma-bob) and see function names like > > lpni: > klvna: > chgubi: > cyzo: > klvnb: > rmn2so: > csphik: > >spew forth. So, while it's great that this same large library compiles and >runs on compilers back to at least Fortran 77 (and probably earlier), >programmers are still stuck with the same cryptic function and data names >they had to deal with 30+ years ago, all in the name of backward >compatibility. > >What's the Python connection? Other than a reminder not to get to slavish >about backward compatibility, I note that these same function names will >then go on to pollute the Python namespace because all this Fortran code is >automatically wrapped using f2py. > Wrapping suggests an opportunity for new names, and keeping the old within the confines of some module or other namespace(s). So, would you like to choose appropriate new names for public interfaces ;-) Maybe the renaming could be automated with appropriate config data for f2py? Regards, Bengt Richter From aleax at aleax.it Fri Sep 27 02:56:29 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 27 Sep 2002 06:56:29 GMT Subject: Changing global variables in embedding Python References: <2cc96dc7.0209261546.22f71021@posting.google.com> Message-ID: John Dunn wrote: > Hello- > > I have embedding Python in a C++ application. All is well, except I > cannot figure out how to modify globals via Python script. After I You talk of code inside a function, althought the snippet you show doesn't look like it is: > the following code, the first line works properly, but the second will > fail with the error 'local variable 'test' referenced before > assignment'. The message object is an argument to the function. > > message.print( test ) > test = "test2" If a function assigns to name 'test', and does NOT have a statement global test (preferably at the start), then 'test' names a LOCAL variable of the function, not a global one. But this would make it quite astonishing that the first line would work -- THAT line should give the error message you're reporting for the SECOND one... indeed the error message you report is IMPOSSIBLE for the second line you give -- it's not referencing 'test', it's binding it. So I suspect you mis-observed things, and the error msg is actually for the first of these two lines. As a fix, try to start your function with the statement: global test Alex From max at alcyone.com Tue Sep 3 03:58:57 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 03 Sep 2002 00:58:57 -0700 Subject: syntax error in Pyton shell References: Message-ID: <3D746BC1.2BFA05F8@alcyone.com> lion wrote: > I'm learning exception handling, I type these code in Python shell: > > >>> try: f=open("nofile") > ... except IOError: pass > ... print "The exception is just passed!" > File "", line 3 > print "The exception is just passed!" > ^ > SyntaxError: invalid syntax > > But these code run without any error as a program(or script). Could > anyone tell me why? This is an artifact of entering in code manually in the shell, which normally would have more cues to go on. In a script it would no that these two statements were unrelated; in the interactive interpreter it can't be sure so is waiting for a blank link to separate them. You can tell this when the prompt is ... instead of >>>. Python 2.2 (#1, Feb 6 2002, 19:31:45) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> try: f = open("nofile") ... except IOError: pass ... # note I hit a blank line here >>> print "The exception just passed!" The exception just passed! -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From bdash at gmx.net Fri Sep 13 06:13:10 2002 From: bdash at gmx.net (Mark Rowe) Date: Fri, 13 Sep 2002 22:13:10 +1200 Subject: Extending a C++ App In-Reply-To: <996eade8.0209122352.45721938@posting.google.com> References: <996eade8.0209120912.3a653d7@posting.google.com> <996eade8.0209122352.45721938@posting.google.com> Message-ID: Hello, >I looked at SWIG >However I have a few concerns (forgive me if Im being dense) > >(1) All the examples are created as DLLs (ie APIs) > This is fine - except how would my C++ App use the same object instances? > (ie. share the memory and API objects) > Last time I looked I couldn't find much information on this topic, but after stumbling around in the dark for a while I found the function SWIG_NewPointerObj, which takes a pointer and creates a PyObject * of the specified type from it. This can then be inserted into a Python namespace using the Python C API. >(2) SWIG does not do a nice job of object wrapping (in my opinion) > For instance instead of saying > c = example.Circle > c.x = 10 > c.y = 20 > del c > > I need to do this: > c = example.new_Circle() > example.Shape_x_set(c,10) > example.Shape_y_set(c,20) > delete_Circle(c) > > Isn't there a cleaner library somewhere to do this? To get around this, tell SWIG to generate shadow classes for the objects. eg, use the command `swig -python -c++ -shadow circle.i'. This will generate a Python source file with classes that wrap the methods you mentioned above (example.new_Circle, etc). Mark Rowe From pyth at devel.trillke.net Mon Sep 30 09:05:14 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 30 Sep 2002 15:05:14 +0200 Subject: Find out link location In-Reply-To: <7uf9na-vd9.ln@lbdb01.gsi.de>; from klaus.hoeppner@bigfoot.de on Mon, Sep 30, 2002 at 02:26:47PM +0200 References: <7uf9na-vd9.ln@lbdb01.gsi.de> Message-ID: <20020930150514.W30315@prim.han.de> Klaus Hoeppner wrote: > Hi, > > with the os.path module I can use the islink function to check, wether > a file is symbolic link. But how can I find out, where the link points > to. E.g. if I have readme.txt --> ../packages/mypackage/readme.txt how > do I get the "../packages/mypackage/readme.txt" with python? import os os.readlink('/path/to/link') regards, holger From oren-py-l at hishome.net Thu Sep 12 03:44:00 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Thu, 12 Sep 2002 03:44:00 -0400 Subject: [FEEDBACK] Is this script efficient...is there a better way? In-Reply-To: <3D7FF723.3050005@one.net> References: <3D7FF723.3050005@one.net> Message-ID: <20020912074400.GA22578@hishome.net> On Wed, Sep 11, 2002 at 10:08:35PM -0400, Michael Schneider wrote: > > > Bob X wrote: > > > > >>1) readlines() loads the entire file into a list so if you have a 30+ > >>mb file you just ate 30+mb of memory. Try using xreadlines() > >>instead, it reads the file line by line and is much more memory > >>friendly. > > > >Very cool...I had missed that! > > > It is much slower though. I am not sure about your config, but I am > running with a Gig of memory. > I would much rather have the speed then the 30 mb of memory. Again, > check your config. Have you actually tested this? I used to believe that larger buffers are always better for performance. Wrong. I ran some test on Linux for the effect of buffer size on file reading speed and the results were very interesting. I started with a buffer size of 32 bytes, tested file I/O throughput and increased it logarithmically by about 2% for each step. As expected, the time to read 1mb improved as the buffer size increased until it hit a minimum for a buffer size of around 4-8k (the graph is very noisy so it's hard to tell) and then rose back up to a value that is 10-20% worse for buffer sizes of 32-64k and remained more-or-less constant for anything higher. This performance curve may be a result of the CPU cache or the OS architecture. The chunk size used by xreadlines is 8k which is about the optimum value (at least for linux). Oren From sarmxiii at knology.net Thu Sep 12 12:43:24 2002 From: sarmxiii at knology.net (montana) Date: Thu, 12 Sep 2002 11:43:24 -0500 Subject: [Tutor] Paradox table In-Reply-To: <20020912143532.GA17566@dman.ddts.net> Message-ID: Is there a good example on how to use a CSV parser in Python? So you have this comma seperated file, does the CSV parser break data up into groups based upon where they are positioned in the file or does it just generate a list of data or both? Is there any good sites out there that deal with CSV parsing and python that have some good examples or can someone on this list give some? Thanks. SA "I can do everything on my Mac I used to do on my PC, plus alot more ..." --Me On Thursday, September 12, 2002, at 09:35 AM, Derrick 'dman' Hudson wrote: > On Wed, Sep 11, 2002 at 03:14:30PM +0200, A wrote: > | Hi, > | Is there a module for reading Paradox database (.DB) files with > Python? > | I need to run the script under Linux, so I can not use ODBC. > | Any suggestion would be appreciated > > One way to access the data is to export it from paradox in CSV format. > CSV is an open standard and several (python) parsers exist for it. > However, using this method won't allow you to easily access the data > from both paradox and from your script, instead you would need to > re-export it every time you modified it in paradox and you would not > be able to modify it using your script. If you can, it would probably > be easiest to migrate to a different db such as postgresql. Postgres > databases are much more accessible than paradox is (at least with the > paradox version I've seen, 3.5). > > -D > > -- > Dishonest money dwindles away, > but he who gathers money little by little makes it grow. > Proverbs 13:11 > > http://dman.ddts.net/~dman/ > From mongo57a at comcast.net Mon Sep 30 19:42:17 2002 From: mongo57a at comcast.net (mongo57a at comcast.net) Date: Mon, 30 Sep 2002 23:42:17 GMT Subject: Scrolled list question Message-ID: <3d98cff7$1_7@goliath.newsgroups.com> Trying to make more than one data element appear in a scrolled list. The window is formed properly; the first piece of data is there, but I don't know how to get the rest of the data in (see comments in code below). if __name__ == '__main__': sqlcmd = sql.Build_Query (command, tables, columns, condition, sort) # custom code - works fine dbinfo = sql.Query (sqlcmd) #custom code works fine for i in range(20): symbol = dbinfo.Symbol[i] action = dbinfo.Action[i] dislist = string.join([symbol, action],' ') # joins the 2 strings ScrolledList(dislist) mainloop() class ScrolledList(Frame): def __init__(self, label, parent=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) # make me expandable self.makeWidgets(label) def handleList(self, event): index = self.listbox.curselection() # on list double-click label = self.listbox.get(index) # fetch selection text self.runCommand(label) # and call action here def makeWidgets(self,label): sbar = Scrollbar(self) list = Listbox(self, relief=SUNKEN) sbar.config(command=list.yview) # xlink sbar and list list.config(yscrollcommand=sbar.set) # move one moves other sbar.pack(side=RIGHT, fill=Y) # pack first=clip last list.pack(side=LEFT, expand=YES, fill=BOTH) # list clipped first The preceding puts the first value of dislist into the window - as it should. So how do I get the rest of them in there? I'm not a very experienced programmer...... tried dislist[i] with ScrolledList(dislist) and got errors. TIA. -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From matt at mondoinfo.com Tue Sep 24 23:05:41 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Wed, 25 Sep 2002 03:05:41 GMT Subject: Tkinter status bar? References: Message-ID: On Wed, 25 Sep 2002 01:41:36 GMT, Daniel T. wrote: > I'm going through a pdf file I found on the internet ("An > Introduction to Tkinter" by Fredrik Lundh) Fredrik's Introduction is excellent. I almost always have a copy open when I'm doing Tkinter programming. > In chapter 8 he talks about how to put a status bar at the bottom of a > window: > > # File: tkSimpleStatusBar.py > class StatusBar(Frame): [. . .] > We could have inherited from the Label widget itself, and just > extended it with set and clear methods. This approach have a few > drawbacks, though: [. . .] > Now my question. I didn't think to inherit from Label, instead I > changed it to: > class StatusBar: > def __init__(self, master): > self.label = Label(master, text="", bd=1, relief=SUNKEN, > anchor=W) [. . .] > In other words, why inherit from any of the Tkinter classes? No reason. I generally don't. You can do it either way depending on your personal preference and/or the details of the class you're defining. If what you're doing feels like it's refining the behavior of an existing class, I'd say that inheritance makes sense. If it feels like you're creating a new class, I'd say that wrapping one or more existing widgets (as you're suggesting doing) and delegating calls to them makes sense. Other people have other rules of thumb, I'm sure. Delegating calls to wrapped objects can be more verbose if you need to delegate lots of them. But I find that I don't generally need to delegate lots of calls and to my eye it's more explicit. Regards, Matt From LogiplexSoftware at earthlink.net Fri Sep 20 09:50:19 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 20 Sep 2002 06:50:19 -0700 Subject: More on Protecting Source Code In-Reply-To: References: Message-ID: <1032529820.20661.221.camel@localhost.localdomain> On Tue, 2002-09-17 at 03:13, David LeBlanc wrote: > EXCUSE ME, but I'm not criticizing anyone! I am suggesting that Python could > be better. I've also been honest enough to say that I don't know what or how > that could be. Python didn't get where it is because people impuned the > motives who had things to say about it. I don't know... I felt criticized. I know you weren't talking about me or even to me, but Usenet has made me very sensitive. And now you're shouting . ;) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From ebbingeo at logica.com Thu Sep 12 09:23:05 2002 From: ebbingeo at logica.com (Onno Ebbinge) Date: 12 Sep 2002 06:23:05 -0700 Subject: EDI parsing References: <746127ef.0209110128.53665a23@posting.google.com> Message-ID: <746127ef.0209120523.258d6ca4@posting.google.com> "Emile van Sebille" wrote in message news:... > Onno Ebbinge: > > I need to parse a (subset) of the UN EDIFACT (aka EDI) standard > > (homepage: http://www.unece.org/trade/untdid/welcome.htm). After doing > > the initial reading of the standard it looks like it is quite hard to > > make a parser for this standard (and 'constructor'). > > My experience is with the UCC UCS standards, so some of this may be > different in the UN standard. > > Once you have the full specification of the documents you'll be > exchanging in a form that python can digest, it's not that hard to build > the parser and/or constructor. The full specs are available to members > on CD in PDF form. I once wrote an extremely ugly extraction utility > that preprocessed using pdf2text and then parsed the resulting mess into > something I could then use as something like > > from edixn import EdiXn > for source in sourcemessages: > tempIn = EdiXn(source) > > where sourcemessages is a python list of the individual transactions > extracted from the edi envelope. EdiXn knew about 810, 850, 852, 855, > 875 and 880 transactions, allowing me to write appropriate handlers for > each type. Sounds like a very similar situation. > > > > My questions: > > > > 1) Is there a python EDI module? I can't find any :( > > I didn't then either. :( > > 2) Is there a (python) EDI to XML converter? > > That wouldn't be hard. If there's already a DTD for edi, that would > help a lot. ;-) No DTD... > > 3) Is there anything that I can use to easily interface with EDI? > > (preferably in lib and DLL form) > > Try some of the commercial suppliers. There's big money (both expense > and potential) in this, and that's probably why we don't find > implementations strewn about the web. Commercial suppliers are not an option! But I agree with your remark about the 'big money'. Maybe when I'm done ;-) > > If the above is not available or fails... > > > > [You have to know that I've never written a parser in Python before. > > The last (big) parser I wrote was in C with a few years back the help > > of lex and yacc if memory serves me right.] > > > > What is the best approach to writing an EDI parser in Python? > > To parse the received messages, I've always found it easiest to use and > parse the raw ascii coming in. There are commercial packages that allow > you to map and export or even map-to-map import, but as most of the > customers I've done this for were typically forced into it by demands of > the channel, and the commercial offerings rarely seemed as nimble as > simply writing a one-to-one utility taking the edi order to the database > or the resulting invoice to edi. I have generally used a commercially > available transport package, KMart at that time being the notable > exception. Outbound messages follow suit. I'm in favour of the raw parsing too. Maybe a one-to-one mapping, maybe with ebXML in between, I'm not sure yet. > If you are writing this as a part of a portable b2b application then > you've got your hands full as you've entered the map-making utility > supplier market. You'll need to address the entire specification, which > my hardcopy of my deprecated 003050UCS shows to be some ~1000 _dense_ > pages. Make sure you've got the funding to do it right, as this is no > low-budget add-on. I'm in luck then! I only need to parse about 10 to 15 messages. I don't want the 'quick and dirty' solution because I _know_ it will bite me if there are changes and/or new messages. And they _will_ come. > The 'edi specification' always felt akin to the 'rs232 specification' to > me, only instead of 25 pins to muck up, they offer 100s. > > Not-sure-how-this-could-help-ly y'rs, Thanks anyway, now I know that parsing is the way to go. Regards, Onno From steve at ferg.org Sat Sep 7 00:09:50 2002 From: steve at ferg.org (Stephen Ferg) Date: 6 Sep 2002 21:09:50 -0700 Subject: ANN: Thinking in Tkinter Message-ID: A small page devoted to "Thinking in Tkinter" at http://www.ferg.org/thinking_in_tkinter/index.html for whoever might find it useful. I've been trying to teach myself Tkinter out of various books, and I'm finding it more difficult than I think it should be. The problem is that the authors of the books want to rush into telling me about all of the widgets in the Tkinter toolbox, but never really pause to explain basic concepts. They don't explain how to "think in Tkinter". Here are a few short programs that begin to explain how to think in Tkinter. In them, I don't attempt to catalog all of the types of widgets, attributes, and methods that are available in Tkinter. I just try to get started down the road of understanding some basic Tkinter concepts. From jeff_hamann at hamanndonald.com Thu Sep 5 21:55:36 2002 From: jeff_hamann at hamanndonald.com (Jeff D. Hamann) Date: Thu, 5 Sep 2002 18:55:36 -0700 Subject: example for using calldll with python2.2 Message-ID: I've perform evaluations on scripting languages for a scripting language to replace vba for our work. Python seems to be a little farther ahead when it comes to calling dlls than perl and I've been trying to get calldll to work on my win2k machine. I've downloaded a version (not sure which but looks liek a version for python 2.1) and the install/compile.bat choked. C:\Python22\calldll>gcc -I../Include -O2 -c calldllmodule.c -o calldllmodule.o In file included from ../Include/Python.h:62, from calldllmodule.c:62: ../Include/pyport.h:480: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." C:\Python22\calldll>dllwrap --dllname calldll.pyd --driver-name gcc --def calldll.def -o calldll.pyd calldllmodule.o -s --entry _DllMain at 12 --target=i386-mingw32 -L.. -lpython22 /usr/lib/gcc-lib/i686-pc-cygwin/2.95.3-5/../../../../i686-pc-cygwin/bin/ld: cannot find -lpython22 collect2: ld returned 1 exit status dllwrap: gcc exited with status 1 is what I got. I have no idea what is going on here. is this required to use the calldll package? is there a precompiled version (at least I can use) before I can get the makefile to work? Jeff. -- Jeff D. Hamann Hamann, Donald & Associates PO Box 1421 Corvallis, Oregon 97339 jeff_hamann at hamanndonald.com www.hamanndonald.com From jb at cascade-sys.com Mon Sep 23 19:31:16 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Mon, 23 Sep 2002 16:31:16 -0700 Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> <2IYsVKAZksj9EwSH@jessikat.fsnet.co.uk> Message-ID: <3D8FA444.1040506@cascade-sys.com> Robin Becker wrote: >In article <3D8E6353.7030303 at something.invalid>, Greg Ewing ddress at something.invalid> writes >...... > > >>If you use spaces only, you're also choosing how other >>people will see it in their editors (unless they're >>willing to use a tool to re-indent it). >> >>Using *tabs* only is the only way to get truly >>preference-independent indentation. >> >> >> >here here, but I'm always wrong > > Ditto. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From jpm at papercut.org Mon Sep 30 16:32:22 2002 From: jpm at papercut.org (Joao Prado Maia) Date: Mon, 30 Sep 2002 16:32:22 -0400 (EDT) Subject: Question about __getattribute__/__getattr__ In-Reply-To: <20020930215327.X30315@prim.han.de> Message-ID: On Mon, 30 Sep 2002, holger krekel wrote: > Probably you are interested in the Memoize recipe at > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 > That looks interesting, and it is indeed similar to what I'm trying to acomplish, but on my case I want to keep each specific return value in a separate cache file. The first Memoize class keeps every cached item in a dictionary, which it may be fine for some applications, but I need it for a network server that may be running for several days. It's not the best thing to keep everything in memory ;) The second class keeps everything on the same pickled file (please let me know if I'm wrong), which will be very slow after a couple hundred megs of data in there. Anyway, I'm still going back to my original question: how do I get the full list of arguments passed to a function ? This can't be that hard :) Cheers, Joao From jdhunter at ace.bsd.uchicago.edu Wed Sep 11 12:03:02 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 11 Sep 2002 11:03:02 -0500 Subject: Graph algorithms - minimisation In-Reply-To: (jolsen@mailme.dk's message of "10 Sep 2002 00:01:39 -0700") References: Message-ID: >>>>> "Jesper" == Jesper Olsen writes: Jesper> If you know of implementations in other languages than Jesper> python - e.g. C/C++, I am interested as well. You may be interested in the boost graph library for C++. There is a link on the main page to a book on the library by the authors http://www.boost.org/libs/graph/doc/index.html Boost also comes with a powerful library for wrapping C++ in python http://www.boost.org/libs/python/doc/index.html So you could wrap what you want in python. You might check on the boost mailing list to see if someone has already done part of that work for you. John Hunter From michaels at one.net Thu Sep 12 06:26:43 2002 From: michaels at one.net (Michael Schneider) Date: Thu, 12 Sep 2002 06:26:43 -0400 Subject: [xml.dom.minidom] why cant it parse '&' References: <9zZf9.24873$_l1.66951@news-server.bigpond.net.au> Message-ID: <3D806BE3.1080902@one.net> The problem is your xml file. it is not valid. you can't have a '&' char in a normal (non-CDATA) string. Your xml file needs to read Congo Mombo - Guitar Gable & The Musical Kings ... good luck, Mike :B nerdy wrote: >im using the minidom.parseString() to parse the following text > > >Congo Mombo - Guitar Gable & The Musical Kings >Various >blues >12 >Westwood >2002-03-11 > > >when it comes to the '&' it throws an exception. is there any way around >this problem?? >cheers asap > > From martinbertolino at yahoo.com Fri Sep 27 09:17:44 2002 From: martinbertolino at yahoo.com (Martin Bertolino) Date: 27 Sep 2002 06:17:44 -0700 Subject: well-formed xml References: Message-ID: <95be4880.0209270517.3a0b5d7e@posting.google.com> I believe you document should be encoded as: search Martin "Mark McEahern" wrote in message news:... > I'm obviously missing something because this seemingly innocent chunk of > xhtml: > > from xml.dom import minidom > > s = "search" > # ^ > # - seems to be the problem > # > # maybe it thinks I'm trying to reference the &q entity? > > doc = minidom.parseString(s) > > Exception traceback follows. > > Is there a way for me to tell it to ignore apparent entity references inside > attribute values? > From fperez528 at yahoo.com Wed Sep 11 18:23:22 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 11 Sep 2002 16:23:22 -0600 Subject: [FEEDBACK] Is this script efficient...is there a better way? References: Message-ID: Bob X wrote: > > I use this to parse a log file (30MB+) for keywords and write the lines > that are found into another file. > > Any thoughts would be appreciated... :-) > How about $ grep words infile | tee outfile Cheers, f. From gerhard.haering at gmx.de Fri Sep 13 11:54:52 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 13 Sep 2002 15:54:52 GMT Subject: Callback function call from C++ References: Message-ID: Sebastian Huber wrote in comp.lang.python: > Hello, > I want to install a Python callback function in a C++ extension module. > Everything works as desired, but is it possible to get the argument list > length and types of the function in advance. For example: > > PyCallable_Check( o) != 0 > get the arglist and return 0 if not ok > install the callback function > > At the moment I get an error at the first call if the arglist is not ok, and I > want to avoid this. I don't know if there's a C interface for this. If there isn't, you can call the inspect module from your C++ app: >>> def foo(x, y, *args, **kwargs): pass ... >>> import inspect >>> inspect.getargs(foo.func_code) (['x', 'y'], 'args', 'kwargs') HTH, -- Gerhard From max at alcyone.com Tue Sep 10 16:13:44 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 10 Sep 2002 13:13:44 -0700 Subject: read() file?? References: Message-ID: <3D7E5278.A8417F5@alcyone.com> jubafre at brturbo.com wrote: > I have a file with assembler instruction and i want read the > lines of the file and put in a list of string, this is easy to do, but > i don?t want to consider the caracteres "/" and the othes after him. > > file.asm: > ADD D1 /coment1 > LDA D2 /coment2 > > list of strings: > X=[ 'ADD D1' , 'LDA D2' ] Do something like (unested): result = [] for line in readlines: if line[-1] == '\n': line = line[-1] if line.find('/') >= 0: line = line.split('/', 1)[0] line = line.strip() result.append(line) -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ I sidestep the either \__/ or choices of logic and choose both. | Ken Feit PyUID / http://www.alcyone.com/pyos/uid/ A module for generating "unique" IDs in Python. From ponderor at lycos.com Mon Sep 9 17:20:40 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: 9 Sep 2002 16:20:40 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 9) Message-ID: QOTW: "I've had an interesting year - I've been coding in nothing but Python (Unix & Win32) and *assembler* (embedded PIC processors). Talk about a contrast! Yet in both cases, the languages 'Fit My Brain' for the tasks at hand." - Tim Daneliuk http://mail.python.org/pipermail/python-list/2002-September/121704.html "I'm too new to Python to give you good technical reasons to use it, but I like it :)" - TeaAndBikkie http://mail.python.org/pipermail/python-list/2002-September/121789.html "This is actually the first new program I've coded in C (rather than Python) in a good four years or so." - Eric S. Raymond http://mail.python.org/pipermail/python-list/2002-September/121533.html Threads.. The Python-dev list summary for 2002-08-16 - 2002-09-01: http://mail.python.org/pipermail/python-list/2002-September/121533.html In light of the new PEP Format, Dr. David Mertz narrarates his experience with text formatting markup methods: http://mail.python.org/pipermail/python-list/2002-August/120870.html Python interprocess communication methods: http://mail.python.org/pipermail/python-list/2002-September/120900.html Many thoughts on the cryptic nature of regular expressions: http://mail.python.org/pipermail/python-list/2002-September/120906.html Duncan Booth points some of the relatively few gotchas he's encountered when packaging a Python program into an EXE: http://mail.python.org/pipermail/python-list/2002-September/120984.html Python-based Windows EXE's installation hints: http://mail.python.org/pipermail/python-list/2002-September/121711.html Repeatable module import debuging tips: http://mail.python.org/pipermail/python-list/2002-September/120972.html There are faster ways for building huge strings: http://mail.python.org/pipermail/python-list/2002-September/121103.html Thorough response to algorithm question on 'Smoothing a discrete set of data': http://mail.python.org/pipermail/python-list/2002-September/121777.html Building Python on SCO issues discussed: http://mail.python.org/pipermail/python-list/2002-September/121231.html Number-of-threads-implemented concern addressed: http://mail.python.org/pipermail/python-list/2002-September/121260.html More answers on reasons to learn Python, with thoughts on PHP: http://mail.python.org/pipermail/python-list/2002-September/121264.html Tim Rue is perplexing. This thread concludes with with an FAQ that makes things as clear as possible. http://mail.python.org/pipermail/python-list/2002-September/121701.html Question on encryption leads to intro, warnings and directions to more detailed resources: http://mail.python.org/pipermail/python-list/2002-September/121270.html How to handle stdin/stdout for daemonization: http://mail.python.org/pipermail/python-list/2002-September/121783.html Thoughts on support for rebinding in nested scopes: http://mail.python.org/pipermail/python-list/2002-September/121531.html Which database is right for 2000-3000 records?: http://mail.python.org/pipermail/python-list/2002-September/121546.html Larry Wall's Python comments in his Slashdot interview http://interviews.slashdot.org/article.pl?sid=02/09/06/1343222&mode=nocomment are discussed on the c.l.py: http://mail.python.org/pipermail/python-list/2002-September/121683.html Software xmlrpclib 1.0.1 includes Bug fixes and performance enhancements: http://mail.python.org/pipermail/python-announce-list/2002-September/001665.html CherryPy? 0.6 adds SSL support: http://www.cherrypy.org JinSitu - Interactive introspection environment for Java and Jython: http://www.krause-software.de/jinsitu/ Pyrex 0.4.4.1 now available: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ PyGame 1.53 includes CD-ROM & MPEG object enhancements, Civil-0.8 and rectangle handling improvements: http://www.pygame.org lfm 0.9, UNIX Python Midnight Commander Clone: http://www.terra.es/personal7/inigoserna/lfm scgi 0.5 is now available from: http://www.mems-exchange.org/software/scgi/ "spambayes" is a Python implementation of applying Bayesian classifier to spam detection: http://sf.net/projects/spambayes New Stackless Python beta available: http://www.stackless.com 'waccess' v. 2.0 web log analyzer is released at: http://www.tundraware.com/Software/waccess/ Freeware 'AutoIt' Win32 UI test automation tool noted: http://mail.python.org/pipermail/python-list/2002-September/121681.html ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continues Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week. http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From bdesth at nospam.free.fr Thu Sep 5 20:49:25 2002 From: bdesth at nospam.free.fr (laotseu) Date: Thu, 05 Sep 2002 20:49:25 -0400 Subject: Why Python? References: <4f49d232.0209050418.7668c21@posting.google.com> Message-ID: <3D77FB95.3070300@nospam.free.fr> Roy Smith wrote: > Laotseu wrote: > >>Now you should *also* learn other languages. But you'd better go with >>a lo level languages and a functionnal one - C and Lisp could be good >>choices. > > > I guess it depends on why you're learning languages. If you're > learning languages to get a paying job as a programmer, lisp would be > a horrible choice. If you're learning languages to study computer > science, lisp is looking a lot better. Learning Lisp means learning functionnal programming and object oriented programming . Learning C means learning real low level imperative programming. These two languages complements each other IMHO. I think once you know them both, you know *how* to program, whatever the language you have to use. my 2 cents... Laotseu -- The Old Master Said : "Lisp is worth learning, whatever the reason." -- From blarson at crary.com Fri Sep 20 10:11:34 2002 From: blarson at crary.com (Bradley D. Larson) Date: Fri, 20 Sep 2002 09:11:34 -0500 Subject: More on Protecting Source Code References: <1032529820.20661.221.camel@localhost.localdomain> Message-ID: <3D8B2C96.DEB56368@crary.com> Perhaps we should start a IP/Developer/Python support group for ourselves.... It appears that after reading this discussion the only real method of protecting software code (not concepts) is to operate it from a black box behind locked doors where the software is only accessable via a generic readily available, "who cares who copies it" client (ie. html browser). Otherwise someone, somewhere somehow will always (I didn't shout ALWAYS) will be able to reverse engineer your product. This has been a problem with "hard" products since the beginning of time. Anyone can beg, borrow, or steal your toaster, bicycle, or car and tear it down and build one similar (and even learn from your mistakes). Legal recourse is usually at best a loss or break even venture, sure you stopped them but at what cost and it does not reverse the damage that has already been done. Cliff Wells wrote: > On Tue, 2002-09-17 at 03:13, David LeBlanc wrote: > > EXCUSE ME, but I'm not criticizing anyone! > I don't know... I felt criticized. I know you weren't talking about me > or even to me, but Usenet has made me very sensitive. > > And now you're shouting . -------------- next part -------------- A non-text attachment was scrubbed... Name: blarson.vcf Type: text/x-vcard Size: 400 bytes Desc: Card for Bradley D. Larson URL: From martin at v.loewis.de Tue Sep 17 02:03:47 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 17 Sep 2002 08:03:47 +0200 Subject: Stackless Python, eventual merge? In-Reply-To: <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: Ian Bicking writes: > But it doesn't seem like complexity was ever the fundamental problem -- > the complexity could have been dealt with, but I don't believe there was > ever any indication that if it was simplified or documented that it > would get into standard Python. That is not true. I have indicated this atleast once, namely when I studied the code. For me, the complicatedness was always the problem - complexity is fine, since this is a complex problem. > It has been simplified, but I don't think that changes anything with > regard to getting it into standard Python -- the same barriers still > exist. You are making these barriers up in your mind. I don't know why you are doing that, though. It requires certain skills to contribute to free software, yes, and these skills are different from the skills you need to write the software in the first place. Lack of skills may indeed pose a barrier - but one that can be overcome by determined contributors. Those contributors might only need the permission from the original author to start working. Regards, Martin From elimli at yahoo.com Sat Sep 28 02:45:15 2002 From: elimli at yahoo.com (eli li) Date: Sat, 28 Sep 2002 08:45:15 +0200 Subject: urllib2.urlopen(req).info() object Message-ID: The call "urllib2.urlopen(req).info()" returns an object similar to the dictionary, but it can have muliple values for some key. For example: Content-Type: text/html Set-Cookie: A=M Set-Cookie: WEBTRENDS_ID=192.168.120.21 Set-Cookie: SINFO=ca9e Via: 1.1 colosus1 (NetCache NetApp/5.3R2D4) How can I retrive all values related to 'Set-Cookie' key? From stsolakos at patras.atmel.com Tue Sep 10 05:35:45 2002 From: stsolakos at patras.atmel.com (Tsolakos Stavros) Date: Tue, 10 Sep 2002 12:35:45 +0300 Subject: Embedding python with a C++ multithread apps -> pause and resume python script References: <001601c258a3$a3e19a20$4c4eb280@epfl.ch> Message-ID: <001001c258ad$7099f680$dbfeaa0a@garganuclear> I have had the same problem, and I had to do some kind of trick. I had also had a problem with the CPU usage, since when such a script had been running, the CPU usage touched 100%. My question : I still do not know why. Does anybody? Anyway, I have used the sys.settrace method. Each time a line of Python code is executed, my OnTrace C++ function is being called. I use yield to lower the CPU usage. You may check if the thread that called it has to pause, an dyou may pause it till it is resumed. Just an idea. Regards Stavros -------------- next part -------------- An HTML attachment was scrubbed... URL: From marklists at mceahern.com Fri Sep 6 09:38:06 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 6 Sep 2002 08:38:06 -0500 Subject: tree data structure In-Reply-To: <3D78AC8E.4040900@mxm.dk> Message-ID: > for key, value in original: > if map.has_key(key): > map[key].append(value) > else: > map[key] = [value] Minor nit: Best not to use the name of a builtin (map). // m - From martin at v.loewis.de Fri Sep 20 03:33:16 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 20 Sep 2002 09:33:16 +0200 Subject: wxPython i18n, help wanted References: Message-ID: Cedric Dutoit writes: > I'm trying to translate an application in Chinese with i18n, but > I don't know how to display Chinese characters in wxPython. > > Can anybody help me ? There are two aspects in your question: How do I translate applications, and How do I display Chinese characters in wxPython. For the first question, I recommend to use the Python gettext module. If you are unfamiliar with gettext, I recommend that you read the GNU gettext manual; Python gettext follows this model very closely. For the second question, in most wxPython installations, you can only display characters supported in the current locale. E.g. if you are in de_CH.ISO-8859-1 environment, you can only display German characters, but not Chinese ones. You need to change your system to a zh_CN.gb2312 environment; then you can display chinese characters - you need to encode the strings in gb2312 (these are Unix examples; on Windows, you need to change the locale likewise - on W9x, you need a Chinese edition of Windows). Starting with wxPython 2.3.3.1, it supports, on Win32, a "Unicode build". In that build, wxPython can display arbitrary Unicode strings; the distribution contains an example that displays Korean among other languages - it is not hard to deduce display of Chinese from that. If you are combining this with gettext, I recommend that you use the ugettext function, which means that you need to have the proper codecs installed. HTH, Martin From exarkun at meson.dyndns.org Thu Sep 12 09:06:14 2002 From: exarkun at meson.dyndns.org (Jp Calderone) Date: Thu, 12 Sep 2002 09:06:14 -0400 Subject: Overloading the ">>" operator in Python 2.2.1 In-Reply-To: References: Message-ID: <20020912130614.GA29027@meson.dyndns.org> On Thu, Sep 12, 2002 at 08:22:07PM +1200, Andy Elvey wrote: > Hi all . > I'm using Python 2.2.1 under Win98. I'm doing some experimenting with > parsing, and as part of that, I'm trying to overload the right-shift > operator (>>) so that I can use it as follows (testing against a sequence > that I read in) - > a >> b would mean "a is followed by b" . > So, you could have a function like seqtest("string_to_test" , > "foo">>"bar" ) , and that function would return true or false, depending on > whether foo was followed by bar. > ( I know it's possible to use regexes for this, but being able to create > a sequence-testing operator like this would be useful .) > Many thanks in advance ...... > >>> class Foo: ... def __rshift__(self, other): ... print 'rshift' ... def __lshift__(self, other): ... print 'lshift' ... >>> f = Foo() >>> f >> 'hello' rshift >>> f << 'world' lshift Also: >>> dir(42) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] Jp -- It is practically impossible to teach good programming style to students that have had prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration. -- Dijkstra -- 9:00am up 114 days, 9:53, 4 users, load average: 0.02, 0.01, 0.00 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 248 bytes Desc: not available URL: From praveen.patil at silver-software.com Mon Sep 16 11:58:32 2002 From: praveen.patil at silver-software.com (Praveen Patil) Date: Mon, 16 Sep 2002 16:58:32 +0100 Subject: Please help solving the problem In-Reply-To: Message-ID: Hi , Please help me in solving the problem below. step 1: I have written three dlls : a.dll , b.dll , c.dll. a.dll contains funct_A(); b.dll contains funct_B(); c.dll contains funct_C(); step 2: I am copying a.dll to directory C:\Program Files\Python\DLLs and renaming as a.pyd similarly I am copying b.dll to directory C:\Program Files\Python\DLLs. I am not renaming as b.pyd I am copying c.dll to directory C:\Program Files\Python\DLLs and renaming as c.pyd So my C:\Program Files\Python\DLLs directory contain a.pyd , b.dll , c.pyd step 3: a)Python function func_pyA() calls funct_A() b)funct_A() call funct_B() c)funct_B() call funct_C() d)funct_C() call python fuction func_pyC() step 4: I am importing a.pyd and c.pyd in python program. import a import c step 5: I am having problem in importing 'a' because 'a' need to load b.dll and c.dll. But I copied c.dll as c.pyd. Please suggest me some solution. here is my code : 1)a.c (a.dll) ---------- void func_A(); 2)b.c (b.dll) ----------- void func_B(); 3)c.c( c.dll) ----------- void func_C(); 4) example.py --------- import a import c G_Logfile = None def TestFunction(): G_Logfile = open('Pytestfile.txt', 'w') G_Logfile.write("%s \n"%'I am writing python created text file') G_Logfile.close G_Logfile = None if __name__ == "__main__": a.func_A(); ..... ..... Please help me in solving the problem. Cheers, Praveen. [ The information contained in this e-mail is confidential and is intended for the named recipient only. If you are not the named recipient, please notify us by telephone on +44 (0)1249 442 430 immediately, destroy the message and delete it from your computer. Silver Software has taken every reasonable precaution to ensure that any attachment to this e-mail has been checked for viruses. However, we cannot accept liability for any damage sustained as a result of any such software viruses and advise you to carry out your own virus check before opening any attachment. Furthermore, we do not accept responsibility for any change made to this message after it was sent by the sender.] From paul at boddie.net Tue Sep 3 09:27:20 2002 From: paul at boddie.net (Paul Boddie) Date: 3 Sep 2002 06:27:20 -0700 Subject: The Module Search Path is ??? References: <7153651c.0209022255.7fd50ba0@posting.google.com> Message-ID: <23891c90.0209030527.63f8ae@posting.google.com> quiteblack at yahoo.com (black) wrote in message news:<7153651c.0209022255.7fd50ba0 at posting.google.com>... > tutorial told me I could found it in the folder:/usr/local/lib/python. > but my OS is windows so folders are different. I searched the folder > "lib" but find no file named "python", any ideas ? If you've installed Python at the location C:\Python21 (for example - this is usually the answer to a question in the Windows installer), then try looking inside that directory and also inside C:\Python21\Lib. Paul From Oschler at earthlink.net Tue Sep 10 12:18:14 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Tue, 10 Sep 2002 16:18:14 GMT Subject: Trouble upgrading to 2.2.1 Message-ID: I'm trying to upgrade from 2.1.1 to 2.2.1. I'm using kpackage (KDE's rpm wrapper). When I try to install from the rpm file named "python2-2.2.1-1.i386.rpm" I get the following dependency errors: libcrypto.so.2 libsel.so.2 How can I correct this, or, is there an easier way to get upgraded? thx From loewis at informatik.hu-berlin.de Sun Sep 15 15:20:24 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 15 Sep 2002 21:20:24 +0200 Subject: Stackless Python, eventual merge? References: Message-ID: Christian Tismer writes: > Stackless is built in a way that by default there is no difference > to the standard. No stack switching occours, all is identical. Good point! Martin From magnus at thinkware.se Tue Sep 17 04:53:48 2002 From: magnus at thinkware.se (Magnus Lycka) Date: Tue, 17 Sep 2002 10:53:48 +0200 Subject: [Tutor] Not sure how to phrase this question In-Reply-To: <000501c25dd4$38711460$9865fea9@arthur> Message-ID: <5.1.0.14.0.20020917104233.02ac6000@www.thinkware.se> At 18:55 2002-09-16 -0400, Arthur wrote: >Would hate to have to resort to truely understanding >this stuff to get to where I am hoping to get. ;) Don't you think it would be simpler to make a factory function, instead of trying to mess with the constructors? def returnClassic... rather than class returnClassic... The interface would look just the same, and I think implementation would be trivial. What you are doing now certainly seems to defy the intentions of __new__, since what you are returning is not in the inheritence chain of the class. If my channeling is successful, you are neither doing what Guido intended, nor what the Gang of 4 intended with the Factory patterns. -- Magnus Lyck?, Thinkware AB ?lvans v?g 99, SE-907 50 UME? tel: 070-582 80 65, fax: 070-612 80 65 http://www.thinkware.se/ mailto:magnus at thinkware.se From aleax at aleax.it Thu Sep 19 15:23:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 19:23:45 GMT Subject: strong/weak - dynamic/static [Was: Getting started] References: Message-ID: <5vpi9.134717$pX1.4791845@news2.tin.it> Terry Reedy wrote: ... >> If you find a way to name this behavior "static", you'll be well >> placed for the yearly Humpty Dumpty award. > > This is pretty inane. Again, I specifically excluded 'this behavior' > from my comments. Anyway, my question *rhetorically* asked whether > creation-time typing (which is fixed except for the exception that I > excluded) is (to quote the OP) 'dynamic or static'. I then suggested In other words, your claim is that typing is fixed at creation time, excluding the way in which an object's type can be changed after then (showing, of course, that said type isn't fixed at all). This makes just about as much sense as, say, claiming that a list's length is fixed at creation time, excluding the ways in which the list's length can be changed (which show, of course, that said length isn't fixed at all). > that this dichotomy does not fit Python very well. That's your thesis, and I don't think you have brought any substantial arguments in its favor. I think that distinguishing things that ARE indeed fixed at the time of an object's creation (such as the length and contents of a tuple or string) from things which are not fits Python quite well, and so does the attempt to position it on the continuum between static and dynamic extremes (just about ANY dichotomy doesn't fit any realistically-complicated situation -- more often than not, shades of gray are the underlying reality, black and white just sometimes-useful, sometimes-misleading simplifications thereof for modeling purposes -- this particular case, in my opinion, is more useful and less misleading than most others). Alex From umop at psyon.org Wed Sep 18 17:05:15 2002 From: umop at psyon.org (Eric Arnold) Date: Wed, 18 Sep 2002 14:05:15 -0700 Subject: RegEx editors Message-ID: Does anybody know of any good graphical regex editors out there? Eric From robie at 1373.net Mon Sep 23 23:19:09 2002 From: robie at 1373.net (robie1373) Date: Mon, 23 Sep 2002 21:19:09 -0600 Subject: confusion about opening files References: Message-ID: <3d8fd913$0$197$75868355@news.frii.net> Thanks anyway. And you are right, I should check out the FAQ as well. "Mark McEahern" wrote in message news:mailman.1032835770.5997.python-list at python.org... > [I wrote] > > This is a FAQ. You should probably find the Python FAQ and read > > it. Short story: Don't use 'from x import *' unless you know > > what you're doing. > > I should have read the post I was replying to more carefully. I saw the > "integer required" error and didn't notice that the OP was using os.open. > So the 'from x import *' was a red herring. As Erik Max Francis pointed > out, the OP should use open instead of os.open. > > My apologies. > > Cheers, > > // mark > > - > > From peter at engcorp.com Wed Sep 4 22:31:46 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 04 Sep 2002 22:31:46 -0400 Subject: Matching a string up to a word References: <3d75ffaa$1@news.sentex.net> Message-ID: <3d76c1f7$1@news.sentex.net> Dag wrote: > In article <3d75ffaa$1 at news.sentex.net>, Peter Hansen wrote: > >>Can you instead guarantee the format of the date that follows the >>filename? Will it always consist of the day of the week, the month, >>the date, and the year? That would turn this into a relatively >>simple problem. > > Yes I can guarentee the last four fields be in that date format. > Actually I think that solved it. I'll split on whitespaces into > an array, and remove the first and last four fields, and then join > whatever's left. That should do it. I was stuck thinking how to > parse it left to right. I was thinking of something like that. This should do it then: filename = ' '.join(field.split(' ')[1:-4]) That is, provided you never expect to see more than one consecutive space in your filenames... -Peter From wlfraed at ix.netcom.com Fri Sep 20 18:10:30 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 20 Sep 2002 15:10:30 -0700 Subject: Python Sybase slow compared to Perl? References: Message-ID: Chuck May fed this fish to the penguins on Friday 20 September 2002 01:30 pm: I'm just a neophyte at this but... > and here is the Python code snippet: > > # output the actual data > c = db.cursor() > c.execute( "SELECT %s FROM %s" % ( select, table ) ) > num_recs = 0 > if os.path.isfile( "%s.gz" % dumpfile ): > os.remove( "%s.gz" % dumpfile ) > file = os.popen( "gzip -c > %s.gz" % dumpfile, "w" ) > while 1: > row = c.fetchone() How many rows do you expect? fetchall() or fetchmany() followed by looping over rows returned may be a noticeable increase (fetchall() if you have the memory). > if not row : break > > line = [] > for i in range( len( row ) ): > line.append( "%-*s" % ( lengths[i], row[i] ) ) > > print >> file, "".join( line ) > num_recs += 1 > > file.close() > c.close() > -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From rgkindya at yahoo.co.in Sat Sep 7 12:36:37 2002 From: rgkindya at yahoo.co.in (rgkindya) Date: 7 Sep 2002 09:36:37 -0700 Subject: getting input in a embeded GUI app ... Message-ID: Dear Newser, I'm a newbie for python. I wish to embed Python interpreter into my vc++ GUI app(for ms-windows only). when executing input statements (eg raw_input()) , in pythonwin environment (activepython) , it gets input using a new small input window, in IDLE , it gets input in its own window (next line). please help me to do these two type of inputs in my embeded GUI app. my app is only GUI , there is no console mode. please debug my engliz bugs ... From mhammond at skippinet.com.au Sat Sep 14 04:19:08 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 14 Sep 2002 08:19:08 GMT Subject: Calling Python from C# - please help References: <6de16ac9.0209130508.5d1b56c6@posting.google.com> Message-ID: <0iCg9.2350$Ee4.6516@news-server.bigpond.net.au> Syver Enstad wrote: > loewis at informatik.hu-berlin.de (Martin v. L?wis) writes: > > >>adila001 at yahoo.com (AdrianC) writes: >> >> >>>I am using Python 2.1 and I am tring to use my Python COM component. >> >>>From VB6 everything is OK, but in .NET i don't know how to set the >>>reference to my COM. >> >>I've never used the COM bridge in .NET, but I believe you need to >>create a type library first. > > > Although you don't have to make a typelibrary, your C# code will be > nicer if you do so (else you will have to use the dispatch interface > to work with the object). Yes on all counts. You should create a type library defining your interface, and use the .NET tlbimp.exe tool to create a standard .dll assembly. Your C# code then imports this assembly and can use the object as a "first class" .NET object. I have no examples of this, but I should. I'm co-authoring a .NET book which is nearly out :) - http://www.aw.com/catalog/academic/product/1,4096,0201770180,00.html - Python does get a bit of a mention :) Mark. From dsavitsk at e-coli.net Sun Sep 29 13:22:59 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sun, 29 Sep 2002 17:22:59 GMT Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> Message-ID: "Jurie Horneman" wrote in message news:9ac02e81.0209290839.4f4d6475 at posting.google.com... > Once again my attempt to profit from Python's vaunted productivity > increase has come to a screeching halt because some innocent thing > that one would reasonably expect to work in one line, intuitively, and > without even having to think about, turns into a nightmare already > lasting more than an hour, requiring numerous experiments, searching > through the documentation - both manually and using my editor's > find-in-files - finally leaving me no other option but to write a post > to comp.lang.python, knowing that my programming flow for today is > well and truly gone. I hate doing this, because I know I cannot keep > my frustration out of my writing, and also that someone will reply and > gently or not so gently point out something which actually IS written > down in some obscure corner of the documentation, despite my attemps > to RTFM. > > So, what is it this time? No, it's not Unicode, another aspect that > frequently trips me up, causing my face to meet the rough asphalt of > the infobahn. It's importing modules. Again. > > (This is an obscure reference to an attempt on my part to implement > MBCS conversion functions as Python codecs. This failed miserably and > despite the helpful advice I received here, I never did try again. Too > bad, because those conversion functions are pretty good. And since I'm > doing some parenthesized ranting here: does anyone outside of the > Python world use 'codec' to refer to anything except audio / video > codecs? I actually had to post here just to find out that what I was > looking for were *called* codecs. Sheesh.) > > Anyway. > > I have this script, let's call it 'blah.py'. It sits in a directory > far, far away from where my Python is installed. It wants to include a > module called 'intro' from a subdirectory called 'templates'. > > This is evidently impossible. > > Among my vain, futile attempts were: > > *** Solution 1 *** > The World is a Beautiful Place > > >>> import templates.intro > > Ha! ha! ha! OK, even I knew this was a bit optimistic. > > *** Solution 2 *** > .PTH file > > Put a templates.pth containing the single line 'templates' in the same > place as 'blah.py', then > > >>> import templates.intro > or > >>> import intro > > No dice: 'ImportError: No module named...' etc. > > *** Solution 3 *** > IMPorting by hand > > >>> import imp > >>> f = open('templates\intro.py') > > >>> imp.find_module('intro.py') > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named intro.py > > >>> imp.find_module('intro') > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named intro > > >>> imp.find_module('intro', '\\templates\\') > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No frozen submodule named .\templates\.intro > > (No WHAT?) > > >>> imp.find_module('intro', '\\templates\\') > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No frozen submodule named \templates\.intro > > >>> imp.find_module('intro', ['\\templates\\']) > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named intro > > >>> imp.find_module('intro.py', ['\\templates\\']) > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named intro.py > > >>> imp.find_module('intro', ['.\\templates\\']) > (, > '.\\templates\\intro.py', ('.py', 'r', 1)) > > Whoa! I finally managed to call imp.find_module without raising an > exception! OK, now to call imp.load_module, because the documentation > says: > > "Load a module that was previously found by find_module()" > > Alright, so there seems to be some connection between find_module and > load_module... The latter probably takes the return value of the > former as a parameter, right? Right? Wrong. > > Here are my attemps to call imp.load_module: > > x = imp.find_module('intro', ['.\\templates\\']) > > >>> y = imp.load_module('intro', f, 'intro.py', x) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: load_module() argument 4, item 0 must be string, not file > > >>> y = imp.load_module('intro', x) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: load_module() takes exactly 4 arguments (2 given) > > Okay, wait, my assumption was obviously naive, better read the doc... > aha. Almost the same parameters as find_module... wonder why I even > needed to call find_module in the first place. OK: > > >>> y = imp.load_module('intro', f, 'intro.py', imp.get_suffixes()) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: load_module() argument 4 must be sequence of length 3, not > 5 > > What? But... but... *splutter* the doc says: > > "The description argument is a tuple, as would be returned by > get_suffixes(), describing what kind of module must be loaded." > > So why doesn't this work? OK, I have no idea why I'm bothering with > these kinds of arcana, but for the heck of it I'll try: > > >>> y = imp.load_module('intro', f, 'intro.py', ('.py', 'r', 1)) > Traceback (most recent call last): > File "", line 1, in ? > File "intro.py", line 29, in ? > ImportError: No module named Base > > Yay! What?! Now my IMPORTED module can't find the modules IT is trying > to import? (It doesn't matter if I put Base next to Blah.py or in > templates - Intro can't find it.) > > Arrrgghhh!!!! OK, enough time spent on this dead end. (Oh, and by the > way not all the functions of the imp module are documented.) > > *** Solution 4 *** > Packages > > OK, more searching, browsing and scouring my hard drive for the word > 'import'. Of course! I forgot that in the Python docs, important > information is cunningly hidden in the Tutorial section! (Really, am I > being unreasonable for assuming that once one has reached a certain > level of knowledge, one shuns the Tutorial and goes straight for the > main documentation, because that's where one can find everything there > is to know? That's only how it works in every language or piece of > software in general I've ever encountered.) > > So there are these things called 'packages'. Wow! Handy, that! All one > needs to do is put an empty file called '__init__.py' in a directory, > and hey! That directory becomes a package and Bob's your uncle. > > So I put an empty file called '__init__.py' in 'templates' and try the > following: > > >>> import templates.intro > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named templates.intro > > >>> from templates import intro > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named templates > > This is *exactly* how it's written in the Tutorial, and > it-does-not-work. > > *** Solution 5 *** > Abject Defeat, Ask on Internet, Be Ridiculed by Peers for Not Managing > Basic Operation > > Amusing little anecdote: I've performed all of the above steps twice - > once while growing increasingly frustrated, and a second time while > writing this post. Twice, while typing in the code above, I at some > point entered: > > import intro > > ... and it would work. For real. The symbols were there. Not a peep > out of the interpreter. > > Because I don't trust PythonWin (don't get me started on PythonWin, I > haven't found a better IDE yet, I may actually succumb and PAY for one > soon *shock horror*) I quit and restarted and lo and behold! the > interpreter complained that there was no such module, as it had been > doing all along, the horrible beast. > > In other words, at random, unreproducable moments, Python perversely > imported my module, whereas normally it refused to. > > To cut a long story... hm... Please please help me! Stop me before I > whine again. And please don't be offended by my ranting, I just can't > hide this much frustration. I'm using Python 2.2 by the way. So, I would like to agree that, while in MS world this would be called a feature of some sort, that it is either a design flaw in Python, or a major oversight in the documentation. I have had most of the same frustration as the poster, and usually stumbled onto something that worked (which too many times sees to have involved \Lib\) Perhaps someone should write a "Complete Guide to Importing Modules" -- maybe it's in the new Nutshell Book -- which I would do if I understood it? (Too add another complaint to the above, as well, Python used in active server pages does not see .pth files forcing sys.append() as the first line of each.) -d From wlfraed at ix.netcom.com Thu Sep 26 03:52:48 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 26 Sep 2002 00:52:48 -0700 Subject: How to send Email using Python? References: Message-ID: Ken fed this fish to the penguins on Wednesday 25 September 2002 11:19 pm: > Hi all, I like to know how to send a HTML featured Email from Python? > I know how to do a text based version using SMTPLib, but not sure how > to do it with a HTML featured Email. Can someone help me? Can someone > provide me with sample code? > mimelib? SMTP stuff is really just the transport of mail from one machine to another. You can stuff anything into the body of the message -- and the MIME stuff helps in setting up the proper headers/dividers. Just don't send me any email with HTML -- where ever possible I disable HTML email (I'll accept the /original/ MIME "rich text" stuff, which predates HTML) -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From gerhard.haering at opus-gmbh.net Wed Sep 11 06:46:44 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 11 Sep 2002 10:46:44 GMT Subject: function pointer References: Message-ID: David Brown wrote: > "Christina" wrote in message > news:ffcedbc9.0209110215.644c1788 at posting.google.com... >> Hi! >> >> Does Python have function pointers? If not, is there a possibility to > emulate them? ^^ Broken quoting - yuck! Your newsreader is broken. Please repair it (using third party software) or make Usenet a better place by throwing away that crapware. > Functions are first-order objects (is that the right term?) It is. > in Python, so you can just assign them to a variable. If we want to keep the terminology right, Python doesn't have variables. It has names and values. Values are bound to names. In your case: For example: > def foo(x): > print x ... you create a function object using the def statement and bind it to the name 'foo'. > bar = foo Here you bind the name 'bar' to the value the name 'foo' refers to. -- Gerhard From skip at pobox.com Thu Sep 5 15:28:34 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 5 Sep 2002 14:28:34 -0500 Subject: Grumble about too strict an attitude about backward compatibility... In-Reply-To: <3D77F98B.3050607@nospam.free.fr> References: <3D77F98B.3050607@nospam.free.fr> Message-ID: <15735.45154.347049.776488@12-248-11-90.client.attbi.com> >> What's the Python connection? Other than a reminder not to get to >> slavish about backward compatibility, I note that these same function >> names will then go on to pollute the Python namespace because all >> this Fortran code is automatically wrapped using f2py. laotseu> Well, that may be true, but the chances of a name collision are laotseu> pretty low IMHO... Name collisions weren't what I was getting at. Python allows essentially unlimited identifier lengths, but people manipulating these functions from Python code still have to use the cryptic 4-6 character names. Perhaps f2py allows mapping such names to something more meaningful. (One can hope. ;-) Skip From Farhad.Fouladi at Dresdner-Bank.com Mon Sep 2 04:10:12 2002 From: Farhad.Fouladi at Dresdner-Bank.com (Farhad) Date: Mon, 2 Sep 2002 10:10:12 +0200 Subject: make informixdb1.3 References: <3D71300E.8010403@sschwarzer.net> Message-ID: Hi Stefan, thank you for your response. I start "make" in correct directory. The point is, there is no "_informixdb.c" file in downloaded files (from python.org). I suppose the make file should generate one but in my case it couldn't. Farhad "Stefan Schwarzer" schrieb im Newsbeitrag news:3D71300E.8010403 at sschwarzer.net... > Hi Farhad > > Farhad wrote: > > I am trying to install informixdb-1.3 with Python 2.1. When I run make I > > get the following error: > > > > make[1]: Entering directory `/export/vol4/dri/informix/informixdb-1.3/ext' > > make[1]: *** No rule to make target `_informixdb.c', needed by > > `_informixdb.o'. Stop. > > make[1]: Leaving directory `/export/vol4/dri/informix/informixdb-1.3/ext' > > make: *** [sharedmods] Error 2 > > Obviously, `make` can't find the file _informixdb.c which is the source code for > _informixdb.o . Are you starting make in the right directory? > > Stefan > From tjreedy at udel.edu Tue Sep 24 09:23:10 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Sep 2002 13:23:10 GMT Subject: Three dumb questions (ordered by dumbness descending) References: <82Zj9.136094$ub2.2966822@news1.tin.it> Message-ID: <2HZj9.260778$AR1.10903907@bin2.nnrp.aus1.giganews.com> "Alex Martelli" wrote in message news:82Zj9.136094$ub2.2966822 at news1.tin.it... > Once you do have a random or pseudo-random generator that fully > satisfies you, Ian Bicking's snippet reimplementing shuffle as a > Decorate-Sort-Undecorate idiom is truly excellent -- a little jewel, How is an O(n*log(n)) algorithm a 'jewel' compared to the simple and standard O(n) algorithm? > It does, alas, end up a little slower than Tim Peters' original -- [...] >and Ian's version only loses very very little indeed. Increase n enough and it becomes arbitrarily slower and loses arbitrarily much. > import time, sys, operator > from random import random > > def shuffle_org(x): > for i in xrange(len(x)-1, 0, -1): > # pick an element in x[:i+1] with which to exchange x[i] > j = int(random() * (i+1)) > x[i], x[j] = x[j], x[i] > > def shuffle_ian(x): > newList = [(random(), i) for i in x] > newList.sort() > x[:] = [i[1] for i in newList] > > > biggie = range(200) > > def timit(func, N=1000): > repeat = [None] * N > start = time.clock() > for x in repeat: func(biggie) > stend = time.clock() > return "%2.2f %s" % (stend-start, func.__name__) > > print sys.version > for i in range(2): > for func in shuffle_org, shuffle_ian: > print timit(func) > > > [alex at lancelot linud]$ python -O timo.py > 2.2.1 (#2, Jul 15 2002, 17:32:26) > [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] > 1.59 shuffle_org > 1.87 shuffle_ian > 1.60 shuffle_org > 1.86 shuffle_ian 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] biggie = range(20000) def timit(func, N=10): ... 10.76 shuffle_org 19.25 shuffle_ian 10.75 shuffle_org 19.81 shuffle_ian biggie = range(200000) def timit(func, N=1): ... 11.24 shuffle_org 23.18 shuffle_ian Terry J. Reedy From sismex01 at hebmex.com Thu Sep 19 11:51:54 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 19 Sep 2002 10:51:54 -0500 Subject: strong/weak - dynamic/static [Was: Getting started] Message-ID: > > Terry Reedy wrote: > ... > >>explaining or defining the concepts of ... dynamic and > >>static typing. > > > > Python objects are typed at creation. Is that dynamic or > > static? I'm > > Judge for yourself: > > >>> class X(object): pass > ... > >>> class Y(object): pass > ... > >>> x = X() > >>> type(x) > > >>> x.__class__ = Y > >>> type(x) > > >>> > > If you find a way to name this behavior "static", you'll be well > placed for the yearly Humpty Dumpty award. > > > Alex > Maybe you're being a bit rash, Alex? >>> class X(object): ... __slots__ = ('a','b') ... pass ... >>> class Y(object): ... __slots__ = ('aa','bb') ... pass ... >>> xx = X() >>> yy = Y() >>> type(xx) >>> type(yy) >>> xx.__class__ = Y Traceback (most recent call last): File "", line 1, in ? TypeError: __class__ assignment: 'Y' object layout differs from 'X' >>> The behaviour you expounded does not blindly work, it seems. -gustavo Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From jolsen at mailme.dk Tue Sep 10 15:15:02 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 10 Sep 2002 12:15:02 -0700 Subject: Graph algorithms - minimisation References: <8vrrnuckib7gbuodhrmbs2f88nq8r5r5vu@4ax.com> Message-ID: Thanks for the reference. Unfortunately a shortest path algorithm will not help here. There seems to have been several efforts to implement graph algorithms in python, but the ones have came across do not go much beyond representing the graphs and implementing eg. Dijkstras algorithm for finding shortest paths (there is also one in the Vaults of Parnassus). It probably does not exist for python, but what I am looking for is actually a python inferface to something similar to the AT&T FSM library (which is a binary distribution, and not open source). http://www.research.att.com/sw/tools/fsm/ Cheers Jesper Gon alo Rodrigues wrote in message news:<8vrrnuckib7gbuodhrmbs2f88nq8r5r5vu at 4ax.com>... > On Tue, 10 Sep 2002 09:30:01 GMT, Padraig Brady > wrote: > > >Jesper Olsen wrote: > >> Do you know of python extentions that implement efficient graph > >> algorithms? > >> > >> In particular I am interested in minimising the number of nodes & arcs > >> used for representing directed graphs. > >> > >> If you know of implementations in other languages than python - e.g. > >> C/C++, I am interested as well. > >> > >> Cheers > >> Jesper > > > >Guido wrote an essay on graphs @ > >http://www.python.org/doc/essays/graphs.html > >In there is a method to return the shortest path > >which may be useful? > > I remember seeing a recipe in ActiveState cookbook with Dijkstra's > algorithm for finding shortest paths. You can then adapt it to your own > representation of a graph. > > > > >P?draig. > > Best regards, > Gon?alo Rodrigues From tendac at wanadoo.fr Sat Sep 28 06:11:57 2002 From: tendac at wanadoo.fr (Claude) Date: 28 Sep 2002 03:11:57 -0700 Subject: print a % Message-ID: When I do print "image size=%d%" %(50) I've got an error Traceback (most recent call last): File "", line 1, in ? ValueError: incomplete format I do not know how to escape the second % print "image size=%d%" %(50) image size=50% Thank you From elimli at yahoo.com Sat Sep 28 12:17:17 2002 From: elimli at yahoo.com (eli li) Date: Sat, 28 Sep 2002 18:17:17 +0200 Subject: urllib2.urlopen(req).info() object References: <3d954f50$0$11909@echo-01.iinet.net.au> Message-ID: what is ClientCookie? "Rob Hall" wrote in message news:3d954f50$0$11909 at echo-01.iinet.net.au... > I used ClientCookie. > > Rob. > > > eli li wrote in message > news:an3fhi$3jr$1 at news.iucc.ac.il... > > The call "urllib2.urlopen(req).info()" returns an object similar to the > > dictionary, but it can have muliple values for some key. For example: > > > > Content-Type: text/html > > Set-Cookie: A=M > > Set-Cookie: WEBTRENDS_ID=192.168.120.21 > > Set-Cookie: SINFO=ca9e > > Via: 1.1 colosus1 (NetCache NetApp/5.3R2D4) > > > > How can I retrive all values related to 'Set-Cookie' key? > > > > > > From aleax at aleax.it Thu Sep 26 09:44:35 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 13:44:35 GMT Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> Message-ID: <7bEk9.145906$ub2.3213634@news1.tin.it> Dennis Lee Bieber wrote: ... > Ah, but if you can persuade the Louvre to /sell/ you the Mona > Lisa, > you are then perfectly free to do what you want with it. You don't seem to be familiar with French (and more generally European) laws about what you ARE allowed to do with works of art classified as "National Treasures" or the like, even when you do own them. Even in the US, the fact that you've persuaded somebody to sell you a house, say, doesn't mean you're then perfectly free to do what you want with it -- local regulations can constrain you so that, for example, you may not be allowed to paint its facade in wide stripes of pink and lime green. Alex From timr at probo.com Fri Sep 27 01:12:57 2002 From: timr at probo.com (Tim Roberts) Date: Thu, 26 Sep 2002 22:12:57 -0700 Subject: http file upload from Python (multipart/formdata) how-to? References: <3d937091$0$181$9b622d9e@news.freenet.de> Message-ID: "Robert" wrote: >want to upload file data (multipart formdata) - same as upload from >web-browser > >urllib.urlencode + urlopen takes only simple name/value tuples > >how do I render multipart formdata ? I guess you will have to generate the HTTP/MIME headers and send the file in your own code. See RFC 1867. Are you trying to interface with a web form that already exists, or are you just trying to do a file transfer from one machine to another? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tim.one at comcast.net Mon Sep 2 17:46:56 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 02 Sep 2002 17:46:56 -0400 Subject: Regex for String Literals In-Reply-To: <47i7nu8q5b3e5merhe7s19qvgsf244nkfq@4ax.com> Message-ID: [Stefan Franke] > Does someone know a regular expression that matches all > kinds of Python string literals (along with their finer points > WRT line breaks, unicode..)? tokenize.py (in the std library) strives to match the Python compiler's tokenization exactly. You'll find a suitable collection of hairy regexps there, but, if you can, find a way to *use* tokenize.py directly. Using the generator interface this is less mind-bending than it used to be (you can iterate over a token stream instead of fighting with stateful callback functions). From tylerdavis15 at hotmail.com Mon Sep 16 09:13:33 2002 From: tylerdavis15 at hotmail.com (davisman) Date: 16 Sep 2002 06:13:33 -0700 Subject: Good book choice? References: <3D850D21.9E34DDEF@bellatlantic.net> Message-ID: <2393234a.0209160513.469a4357@posting.google.com> If you want a book with the code included, buy "Programming with Python" by Tim Altom and Mitch Chapman. This book includes a CD with all the scripts used in the book, as well as many other programs such as the Grail Internet Browser, which is written entirely in Python, and as always, open source. Hope it helps! -Ty > ... I am looking for a suited Python book. I'd like it to have > > clear ideas about OO, as well as an straight pointing into the core > > language. > > > > It seems that 'Python Essential Reference (2nd Edition)' is a good > > choice. There is also the book 'Making use of Python' (by Rashi > > Gupta). Is there any user that bought both? Is it good the treatment > > of OO in the former? Is there a lack of applications point of view in > > the former? Could anybody compare them? pros/cons? > > > > Thanks in advance, > > Eva. From peter at engcorp.com Sun Sep 15 08:56:15 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 15 Sep 2002 08:56:15 -0400 Subject: registry question (_winreg) References: Message-ID: <3d84835f$1@news.sentex.net> idjhh wrote: > hi ^^ > i write this code today , but it is not running -_-; > i don`w find error position > see my code and then please advise me ^^ When posting questions of this nature, please *always* cut and paste the exact error message/traceback or whatever that you encountered. "Not running" is not a useful description. Also "I don't find error position" is unclear, although it suggests that the traceback may not have contained the necessary information to point you to the line with the error. Either way, the exact error message (please don't just retype it) would help. -Peter From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Fri Sep 13 13:25:16 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Fri, 13 Sep 2002 19:25:16 +0200 Subject: calling Oracle functions References: <3d81f811$1@news.mt.net.mk> <3d8210a3@news.mt.net.mk> Message-ID: <3d821f71$1@news.mt.net.mk> >> Now a simpler question: >> is it possible to specify the data source name directly not through >> the alias defined in tnsnames.ora. In perl DBD I can specify a >> connection string like cs = "dbi:Oracle:host=1.10.100.200;sid=TEST"? > cx_Oracle is passing the string directly to Oracle, so whatever it > accepts, cx_Oracle will accept. Specifically, you can take the entire > string that is in your tnsnames.ora file and pass it directly as in > v_TNS = > (DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=opus)(PORT=1521)))(CONNECT_DATA=(SID=DEV))) > v_Connection = cx_Oracle.connect("user", "pw", v_TNS) > and that works just fine. Does that answer your question? Yes. Thanks. I would only suggest that you can add a function to cx_Oracle to make that big ugly string from 3 parameters. something like: def makeDSN(host,port,sid): return """(DESCRIPTION= (ADDRESS_LIST= (ADDRESS= (PROTOCOL=TCP) (HOST=%s) (PORT=%s))) (CONNECT_DATA=(SID=%s)))""" % (host,port,sid) -- ?????? Intel: where Quality is job number 0.9998782345! From pinard at iro.umontreal.ca Wed Sep 25 11:58:46 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Wed, 25 Sep 2002 11:58:46 -0400 Subject: missing functions in os.path In-Reply-To: <31575A892FF6D1118F5800600846864DCBD876@intrepid> (Simon Brunning's message of "Wed, 25 Sep 2002 14:41:52 +0100") References: <31575A892FF6D1118F5800600846864DCBD876@intrepid> Message-ID: [Simon Brunning] > All patched gratefully received, I'm sure! I sometimes use the following code (file name here is `nicepath.py'). The documentation is a bit terse, I confess! :-) #!/usr/bin/env python # Copyright ? 2000, 2001, 2002 Progiciels Bourbeau-Pinard inc. # Fran?ois Pinard , 2000. import os, string def canonical(path, viewpoint=None): return string.join(canonical_parts(path, viewpoint), '/') def nicest(path, viewpoint=None, relative=False): if viewpoint is None: eye_parts = canonical_parts(os.getcwd()) else: eye_parts = canonical_parts(viewpoint) path_parts = canonical_parts(path, viewpoint) maximum = min(len(eye_parts), len(path_parts)) for counter in range(maximum): if eye_parts[counter] != path_parts[counter]: break else: counter = maximum if relative or len(eye_parts) < 2*counter: return string.join((['..'] * (len(eye_parts) - counter) + path_parts[counter:]), '/') def canonical_parts(path, viewpoint=None): def split_and_append(parts, name): for part in string.split(name, '/'): if part == '..': parts.pop() elif part != '.' and (part or not parts): parts.append(part) return parts if path[0] == '~': path = os.path.expanduser(path) elif path[0] != '/': if viewpoint is None: viewpoint = os.getcwd() path = os.path.join(viewpoint, path) parts = split_and_append([], path) counter = 0 while counter < len(parts): name = string.join(parts[:1+counter], '/') if name and os.path.islink(name): link = os.readlink(name) if link[0] == '/': link_parts = split_and_append([], link) else: link_parts = split_and_append(parts[:counter], link) parts = link_parts + parts[1+counter:] counter = 0 else: counter = counter + 1 return parts -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From schull at digitalgoods.com Wed Sep 4 11:15:43 2002 From: schull at digitalgoods.com (Jon Schull) Date: 4 Sep 2002 08:15:43 -0700 Subject: Tkinter report_callback_exception? 'module' object has no attribute 'print_exception' ? Message-ID: <2621b014.0209040715.1bf9fce3@posting.google.com> Hi, As I interpret this message, the environment is telling me that traceback has no "print_exception." But of course, it does. I think a file access error is triggering my problem, but why can't I get a clue from the traceback? Exception in Tkinter callback Traceback (most recent call last): File "C:\jon\python\PIL\all.py", line 101, in ? root.mainloop() File "C:\Python22\lib\lib-tk\Tkinter.py", line 929, in mainloop self.tk.mainloop(n) File "C:\Python22\lib\lib-tk\Tkinter.py", line 1296, in __call__ self.widget._report_exception() File "C:\Python22\lib\lib-tk\Tkinter.py", line 1061, in _report_exception root.report_callback_exception(exc, val, tb) File "C:\Python22\lib\lib-tk\Tkinter.py", line 1552, in report_callback_except ion traceback.print_exception(exc, val, tb) AttributeError: 'module' object has no attribute 'print_exception' From CousinStanley at HotMail.com Mon Sep 30 09:29:58 2002 From: CousinStanley at HotMail.com (Cousin Stanley) Date: Mon, 30 Sep 2002 06:29:58 -0700 Subject: Data Plotting Library DISLIN 8.0 References: <3D940A37.92FD45D5@linmpi.mpg.de> Message-ID: || Yes, you can download the file 'dl_80_py.zip' that contains the || DISLIN distribution for Python 2.2 on Windows. You don't have to || compile anything. The other DISLIN distributions are for several || commercial and non-commercial compilers. Cousin Helmut ... Thanks for the reply ... After reading the FAQs from your website a bit more closely, I downloaded dl_80_py.zip and installed yesterday ... The install process was very easy and all the Python demonstration programs included with the distribution functioned as expected and I'm looking forward to using DISLIN ... I was just a bit confused about whether or not any compilation was required, since you had listed so many different distributions with so many different compiler options available ... Cousin Stanley From brueckd at tbye.com Tue Sep 17 16:35:59 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Tue, 17 Sep 2002 13:35:59 -0700 (PDT) Subject: Earing money with Python software (was: More on Protecting Source Code) In-Reply-To: <4jt7ma.fse.ln@lenashee.goebel-consult.de> Message-ID: On Tue, 17 Sep 2002, Hartmut Goebel wrote: > Martin v. Loewis wrote: > > > For software, I think the economical risk is that somebody uses your > > software without giving you the money you want - not that somebody > > sits down and studies your code for days, to write a program that he > > could have written himself from scratch in the same time. > > Which brings me to another (related) topic): How to earn money > distributing Python software? I think the answer to that question is more or less the same regardless of the language - nothing Python-specific there. It probably depends almost entirely on your target market. > - Sell it via micro-payment? This one always appeals to me but today there are no standard & safe ways to make payments, much less micropayments (hehe.. imagine entering credit card info for each 50 cent charge). > - Declare it "Shareware" and hope somebody pays for it? Too little incentive to pay. Most people are more or less honest, unless you make it _too_ easy not to pay. You have to give them a little more incentive, whether it be extra features, support, or an end to nags. > - Offer commercial support? This works well if your target audience is a commercial entity. You asked the age-old question though. I'm partial to the completely free or free-for-personal-use-but-companies-must-pay approach when possible. Otherwise, put a bit of a "wall" up protecting your code but not much beyond that. It's a futile arms race to try and lock everyone out (and the techniques to do it frequently anger your legitimate customers), and the people who tend to crack programs usually wouldn't pay for it anyway. -Dave From b.maryniuk at forbis.lt Thu Sep 26 07:39:21 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 26 Sep 2002 13:39:21 +0200 Subject: Zope, MySQL and pictures in blob-fields ... In-Reply-To: References: Message-ID: <200209261339.21600.b.maryniuk@forbis.lt> This is crossposting. Please subscribe to the Zope maillist at zope at zope.org and post this there. On Thursday 26 September 2002 13:16, Thilo R??ler wrote: [skipped] > "". -- Regards, Bogdan Kiekvienas lai?kas su lietuvi?komis raid?mis praturtina Alberto ispell ?odyn? -- http://ieva.mif.vu.lt/~alga/lt/ispell/ From whisper at oz.net Wed Sep 18 22:34:08 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 18 Sep 2002 19:34:08 -0700 Subject: How to build Python 2.2.1 on Windows? In-Reply-To: <3D892BBD.5B38DD49@bellatlantic.net> Message-ID: I have built Python on Windows using both the distribution and CVS download. The necessary VC++ project files are included in both. You will have to also download some other components as described in the readme file, including a special version of BSDDB version 1.85, zlib, Tcl/Tk (Tk needs Tcl to build), expat and maybe some other things. These are for extensions, and are not required to build the core Python. WRT BSDDB, there are projects out there to build Sleepycat BSDDB version 4.0 and that's a better choice then the default version 1.85 used by Python (due to bugs). The downside is that Sleepycat BSDDB is free for personal use only. See \dist\Python-2.2.1\PCbuild for complete details. Oh yes, put your python source distro or cvs dump under a directory called 'dist'. I found the directions to do that unclear in the readme and it gave me a bit of trouble. The other packages you'll need also go in 'dist' as peers of the python source tree. Those should be built before Python. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of David Lees > Sent: Wednesday, September 18, 2002 18:43 > To: python-list at python.org > Subject: How to build Python 2.2.1 on Windows? > > > I have been playing with Python for awhile and would like to know how to > try building Python on a Windows machine that has MS C++ version 6. Is > there a standard download that is configured to do this? If not could > someone point me in the direction of information on builds? I > downloaded Python-2.2.1.tgz.tar on my Win98 box and WinZip 8 does not > even seem to know how to unzip it. I just transfered the tar file over > to a linux box and it unzips without and problem using tar. The README > seems to only talk about linux/unix type systems. > > David Lees > -- > http://mail.python.org/mailman/listinfo/python-list From magnus at thinkware.se Sat Sep 28 21:47:15 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Sun, 29 Sep 2002 03:47:15 +0200 Subject: Difference between MOD_PYTHON and the CGI module References: <3d904321$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: <3D965BA3.10905@thinkware.se> Gumuz wrote: > What are the differences, if any? > > Am i mixing up to things here? > > Suppose I'd like to use python as a 'replacement' for PHP, what do I use? As far as I understand, PHP typically embeds code in HTML pages. If you want to do that you want something more than mod_python. Have a look at http://www.python.org/cgi-bin/moinmoin/WebProgramming and look closer at the templating systems. I recently found CherryPy, www.cherrypy.org , and I like that. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus at thinkware.se From oren-py-l at hishome.net Wed Sep 18 11:18:34 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 18 Sep 2002 18:18:34 +0300 Subject: Stackless Python, eventual merge? In-Reply-To: <3D8880AC.7040902@tismer.com>; from tismer@tismer.com on Wed, Sep 18, 2002 at 03:33:32PM +0200 References: <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <20020918060823.GB81158@hishome.net> <3D8880AC.7040902@tismer.com> Message-ID: <20020918181834.A27703@hishome.net> On Wed, Sep 18, 2002 at 03:33:32PM +0200, Christian Tismer wrote: > Oren Tirosh wrote: > > They may be dangerous in some circumstances. IIRC, if a C extension calls > > the Python interpreter recursively with pointers to things on its stack > > it can cause memory corruption. > > Then don't switch stacks in that context. > The switching occours on your demand. > But the theoretical possibility to create a crash > is no reason to dispense with the benefits. Definitely not. Don't get me wrong - I'm very excited about stackless. > My only chance to do this magic with almost no crash > possibility would be to allocate a new stack for > every new tasklet. Yes, that's a possible solution. I wouldn't say that it's the only chance, though. There's always more than one way to skin a cat. > A benefit would be reasonably faster switching, while > the drawback would be the reasonable high memory > requirement for a full machine stack. > I might consider a hybrid solution, putting certain > "dangerous" extension stuff into a real new stack > all the time, together with the quite fast and very > cheap other safe tasklets. > > Just-need-an-idea-how-to-determine-that - ly y'rs - chris Who says you have to determine that in advance? Just try. If the extension actually calls the interpreter recusively it means that it needs its own stack. Let it have exclusive ownership of the current OS thread and its associated stack and allocate another thread from a dynamic thread pool to continue tasklet scheduling. When the extension returns back to nesting level 0 its thread will be released back into the pool. This way a relatively small pool of OS threads can be used to juggle a much larger pool of tasklets. This can also be a good way to handle extensions that make blocking I/O calls like database engines - a relatively small pool of OS threads can serve requests from a bigger pool of tasklets. This can be transparent: when the number of concurrent requests exceeds the number of threads any new request frames can be queued until a thread becomes available. The level of concurrency for any resource can be tuned dynamically to optimize the performance without affecting the overall structure of the program. Oren From syver-en+usenet at online.no Tue Sep 24 15:18:28 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 24 Sep 2002 19:18:28 GMT Subject: Limit number of concurrent threads References: Message-ID: Chuck May writes: > I've searching for examples that fit my problem, and I haven't found > any. Most examples I've found look something like this: > > threads = [] > for i in range(number_of_tasks): > thread.append(thread_for_task) > > # let the threads run - just wait for shutdown > for t in threads: > t.join() > > which whould work fine if I wanted to start all 80 threads at once. > > I've read about the Queue, but I'm not sure if it's what I want, and I > > can't seem to find any good examples on it. I think Queue would be nice to use, Have a thread (the main thread perhaps) feed all the table names (or a table object if you please) into a Queue. Set up some worker threads with access to the Queue (global variable, member). The worker threads should loop something like this: while 1: queueItem = self._queue.get() doSomethingWithQueueItemHere Then you can start your workers. (You'll have to find out some way to make the workers exit when the work is done, perhaps putting a number of None's equal to the number of workers last in the queue and testing for None in the working thread loop. -- Vennlig hilsen Syver Enstad From sholden at holdenweb.com Fri Sep 13 15:00:56 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 13 Sep 2002 15:00:56 -0400 Subject: Cursed newlines and readline() References: <6u5g9.11312$Da3.1133980@kent.svc.tds.net> Message-ID: "Thomas Wouters" wrote ... > On Thu, Sep 12, 2002 at 06:59:14PM +0000, Edward K. Ream wrote: > > > According to one of Leo's Linux users, the Python's readline() routine on > > Linux delivers "\r\n" line end strings verbatim, while the windows versions > > force the string to use the Unix convention of using only "\n". This seems > > unfortunate. Is there a justification for it? If not, I would like to > > suggest that readline() work the same on all platforms and that it deliver > > only "\n" as a line terminator. > > You can open the file in 'binary' mode (adding 'b' to the mode string) and > the file will contain '\r\n' on both platforms (and any other platforms.) > Nope. Exactly wrong. In 2.2 and those before, when files are opened in *text* mode (no "b") then reading them will provide Unix-style line endings (newline only). When you open files in binary mode then you see the bytes stored in the file. On Unix systems there's no difference in the contents of a file whether in binary or text mode. On Windows a file is shorter by the number of carriage returns. On the Mac I have no idea what they do. Probably just carriage returns, to be different :-) 2.3 will be a bit more flexible about such mattrers. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From theoryboy at my-deja.com Wed Sep 4 10:01:48 2002 From: theoryboy at my-deja.com (Peter Saffrey) Date: 4 Sep 2002 07:01:48 -0700 Subject: efficient list merging References: Message-ID: I was trying to abstract a bit. The way I get the lists of lists of strings is far too long and ugly to contemplate posting here. Sorry if I didn't post compilable code - again I was trying to abstract. Here's an example: lol1 = [['a'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j']] lol2 = [['d', 'e', 'f'], ['k', 'l', 'm'], ['d'], ['f', 'g'], ['a']] I want a function which returns mergelol = [['a'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j'], ['k', 'l', 'm'], ['d']] That is the set-union of the two lists of lists. Note that I've used very short strings and short list lengths here for simplicity. The strings would be up to 80 characters in length, the sub-lists up to 8 items in length, and the list of lists itself could contain 50 sub-lists. Peter From andrew.thompson at ashecastle.com Thu Sep 19 07:00:08 2002 From: andrew.thompson at ashecastle.com (Andrew Thompson) Date: Thu, 19 Sep 2002 12:00:08 +0100 Subject: Smalltalk style inspector In-Reply-To: <20020919074722.GB77021@partagas.as.de.cw.net> Message-ID: <007c01c25fcb$b81ccc10$4802a8c0@blair> Is there a Smalltalk style inspector (GUI with drilldown through data-structures) for Python ? I have written a rough-and-ready one in TK which is just a mixin-class Which confers the method .inspect() to any class, and then allows a user to wander through attributes, doc-strings , dictionaries and collections by double-clicking with the mouse, but not sure if it might be of value to others. I don't even know the process for contributing the module... Andrew From phr-n2002b at NOSPAMnightsong.com Mon Sep 30 00:43:17 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 29 Sep 2002 21:43:17 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xelbcgo56.fsf@ruckus.brouhaha.com> <7x65woks0i.fsf@ruckus.brouhaha.com> Message-ID: <7x1y7ckryy.fsf@ruckus.brouhaha.com> Paul Rubin writes: > Example: bunches are three for a dollar. How much do you pay if you > buy nine bananas? Whoops, meant "bananas are three for a dollar". Sorry. From mcherm at destiny.com Tue Sep 10 13:53:18 2002 From: mcherm at destiny.com (Michael Chermside) Date: Tue, 10 Sep 2002 13:53:18 -0400 Subject: dynamism References: <66715c02.0209091923.265fe77e@posting.google.com> <3d7e209a_1@news.iprimus.com.au> Message-ID: Steven Shaw wrote: >>An object of a builtin type, or with __slots__ defined in the class and >>all base classes does not have a __dict__ attribute. > > > Does this mean that the attributes are stored in a more efficient way? > > Is there a way to implement "record-based" object layout rather than > "associative-array based" object layout? In short, YES. See http://python.org/doc/2.2.1/whatsnew/sect-rellinks.html . Unfortunately, http://www.python.org/peps/pep-0253.html doesn't give full details since they haven't been written up yet. -- Michael Chermside From dgallion1 at yahoo.com Tue Sep 17 12:42:09 2002 From: dgallion1 at yahoo.com (Darrell) Date: 17 Sep 2002 09:42:09 -0700 Subject: how to cast an instance id References: <3D86E888.90AF569@millfilm.co.uk> Message-ID: class foo: def info(self): print self a = foo() a.info() ccc = "%s()"%( str(a.__class__).split(".")[-1], ) eval(ccc).info() exec("b=%s"%ccc) b.info() <__main__.foo instance at 0x00767378> <__main__.foo instance at 0x007673B0> <__main__.foo instance at 0x007673B0> --Darrell Eric Texier wrote in message news:<3D86E888.90AF569 at millfilm.co.uk>... > It there a way to create a new reference of an object > from the string representation of its id? > Thanks for any help. > From alessandro.riolo at sen.it Fri Sep 27 09:01:44 2002 From: alessandro.riolo at sen.it (Alessandro Riolo) Date: Fri, 27 Sep 2002 15:01:44 +0200 Subject: [OT] Crosspost? [was Re: Zope, MySQL and pictures in blob-fields ...] References: Message-ID: Bo M. Maryniuck wrote: > This is crossposting. Why this was crosspost? Off topics, perhaps, but surely the header of the post wasn't showing crosspost. -- ale www.sen.it From kibab at icehouse.net Mon Sep 23 13:29:47 2002 From: kibab at icehouse.net (Kaleb Pederson) Date: Mon, 23 Sep 2002 10:29:47 -0700 Subject: parsing tabs in a string In-Reply-To: <006201c26324$4148ae90$025e10ac@calibredd.com> Message-ID: <003001c26326$d05a96a0$e90dbb92@KWINXP> If you don't specify where find should start searching, it ALWAYS starts at the beginning of the line and looks for the first occurrence of the given substring. Hence,"\t" is always found at that character. The documentation clearly states that so you might want to double check it if you aren't getting the desired behavior. You might try: >>> line = 'this\tis\ta\ttest\tof\t"mydatehere"' >>> newline = line.split('\t') >>> print newline ['this', 'is', 'a', 'test', 'of', '"mydatehere"'] >>> for x in newline: ... print x ... this is a test of "mydatehere" That will break list into several lists where each column is whatever was in between your tab markers. Or, if you really want to go through and find all the '\t's.. then. >>> mystr = 'this\tis\ta\ttest\tof\t"mydatehere"' >>> index = mystr.find('\t') >>> while index != -1: ... print 'index found at:',index ... index = mystr.find('\t',index+1) ... index found at: 4 index found at: 7 index found at: 9 index found at: 14 index found at: 17 Hopefully that helps. --Kaleb -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of Andrew Alzner Sent: Monday, September 23, 2002 10:11 AM To: python-list at python.org Subject: parsing tabs in a string Hello, I'm getting to know Python and have a quick question for something I don't understand. I'm trying to parse information extracted from a spreadsheet which is tab separated. Here is a simplified version of what I have: list=['"103-01a-17"\t2\t33\t256\t227\n'] y=list[0] print y.find("\t") print y.find("\t",1) I thought the second .find should return the second occurence of "\t". To get the index of the second tab I have to type: print y.find("\t",13) This doesn't make sense to me. Can someone help me please. Thanks, Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: From rsrchstr at msn.com Sun Sep 29 20:54:59 2002 From: rsrchstr at msn.com (mike henley) Date: Mon, 30 Sep 2002 01:54:59 +0100 Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> Message-ID: i guess i'll rephrase; what i wish for is an "application-to-person" (P2A) IM-based "presence", so that a web-application that i host on a personal webserver, on my own machine, can let others become aware of its "presence" easily and be easy to connect to with a simple click-to-launch-browser-and-go-to-my-ip. This should be easy to do. I just don't have experience with Jabber or xml-rpc, or other potential useful technologies. "mike henley" wrote in message news:576c1752.0209291326.56dcdf31 at posting.google.com... > I remember a while ago reading about tim burners-lee and how his > vision of the WorldWideWeb as a medium where all can freely and easily > publish information has not materialized properly, and i felt it so > strongly over the past week when trying to look at options for hosting > a website. Hosts are either expensive or limit you in terms of what > languages, modules, applications, and OSs you can use. They also limit > you in terms of space, bandwidth used per period, number of executions > of CGIs... etc. Some of those who give good deals, seem difficult to > trust with either your credit card number or your content. > > I wish i can just use my own computer, with whatever technologies I > choose, keeping my content that i build up over time safe here on my > own machine, but unless you have a broadband connection this is not > possible. It may be possible using a dynamic DNS provider, but then > again either they add cost, end up with an ugly URL, and, most > importantly, there's no way for others to know when you get online. So > here comes the idea that occured to me, and i post it here to ask if > you know of an application that already provides this functionality, > then please tell me what it is, or if you think it is worth doing on > an open source basis, or even proprietary, in which case i invite > anyone to do so, or if you think it's a completely stupid and > impossible idea, then perhaps you can please tell me why. > > You probably guessed if you read as far as the second paragraph that > what i'm thinking about is an application functionality that enables > instant messaging to provide the dynamic DNS functionality. So instead > of giving others a URL I can just give them an IM username they can > add to their client, and when i go online, through my humble dial-up > connection that changes IP whenever i log in, they'll be aware of my > presence, and be able to connect to a server i host on my machine. > > It sounds like a simple thing; IM presence, automatic IP query of my > username, click on my username and or use a contextual menu option or > whatever and a browser launches to go to the site i'm hosting on my > machine. Perhaps it can use existing open-source platforms, such as > jabber or gnutella, or as an add-on to existing open-source > applications/clients. Basically what i'm suggesting is a little tool > to enable a server such as apache to join the whole IM/p2p thing and > have "presence". The more automated it is, and the easier it is, the > better. I think such a functionality will be especially useful for > certain uses, in my case it will be hosting a wiki, as i leave my > machine online a lot through my dial-up, can't predict the number of > executions of CGI or the amount of space needed, wish to be free to > use whatever wiki application is best for my needs and in whatever > language regardless of what a host will support, and do not wish to > pay a monthly fee, extra charges, setup fee or a domain registration. > Perhaps there can be other areas where it is useful, and i'm sure > there are other areas where it will not be suitable. Perhaps there can > also be a simple way to enable a page hosted in such a way to be > submitted to search engines, i haven't thought about that yet, but > tell me if u see any. > > What do you think? already done, worth doing, stupid, or impossible? > (p.s. please also let me know if there are other newsgroup to which > posting this will be a good idea) From pcolsen at att.com Thu Sep 12 13:08:21 2002 From: pcolsen at att.com (Olsen, Peter C, SOFED) Date: Thu, 12 Sep 2002 13:08:21 -0400 Subject: Smoothing a discrete set of data Message-ID: <8527B21850BECB478454F14257320562B46009@ACCLUST02EVS1.ugd.att.com> This is a followup to Paul Moore's post of 07 September 2002. Paul wrote: > I have a set of data, basically a histogram. The data is pretty > variable, and I'd like to "smooth" it to find trends. Actually, > this comes up a *lot* for me - some examples: sampled IO rates on > a machine - I want to look for trends (is IO higher overnight or > during the day, etc) or fuel consumption for my car (do I use > less fuel since I had the service). > > Normally, what I do with things like this is draw a graph, and > try to spot the trends "by eyeball". But it feels to me like I > should be able to write something which smooths the data out. I > just don't see how :-) > > Take an example - here's a rough ASCII-art diagram > > 9 XX XX > 8 XX XX XX > 7 XX XX XX XX XX > 6 XX XX XX XX XX XX > 5 XX XX XX XX XX XX > 4 XX XX XX XX XX XX > 3 XX XX XX XX XX XX XX XX XX > 2 XX XX XX XX XX XX XX XX XX XX XX XX XX > 1 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX > > This seems to me to have very clear peaks at the left and right, > and a shallow point in the middle. I'd say that you could > "smooth" this to something that averaged 8 for the first 3 bars, > then 2 for the next 9, then 7 for the last 3. But try to make > that precise... > > You have hit on two of the fundamental problems of data analysis: 1. How to separate data from noise, and 2. What is the "best" way to do it. First, let's simplify the problem and make it precise. What I think you want to do is find the "large trends" in the data and get rid of the noise. You give sampled IO rates as an example. Network traffic is a similar one. Network traffic seems to have a regular daily pattern. It's low in the early morning, rises until before noon (perhaps about 11:00), drops for lunch, rises again in the afternoon, and then falls at the end of the workday. That's the overall pattern (which is what I think you call a trend), but the real data is never as simple as that. If we look at short intervals, say 10 minutes, data is likely to be very ragged, with lots of hills and valleys. What I think you'd like to do is smooth out these hills and valleys. To start to do that, let's build a mental model. Let's think of the data as the sum of an underlying curve and a sequence of random errors. Let's further assume that there is no relationship between successive errors. (This is reasonable because we want to put all the relationship between successive samples into the underlying curve.) Here's how you could make such a random sequence. For every data point, roll a die and flip a coin. If the coin is heads, add the number on the die to the value of the data point; if it's tails, subtract instead. If you take a particularly easy set of data points (setting every one to the constant zero) and plot these errors, you'll see that they are randomly distributed between -6 and 6 (excluding the case of 0 error because the die has no zero face). This is a good example because actual curve is simple: a straight line at zero. There are two simple ways to eliminate the random errors (and many complex ones I won't mention). One is a "moving average," the other is a "running median." Each has its own advantages. Both are simple to implement. For a moving average, take any odd number of successive data points, take their arithmetic average (the sum of the values divided by the number of points), and replace the middle point with the average. For example, consider the sequence: s = [5, 5, 6, 3, 5, 5, 2, 5, 6, 6, 4, 1, 1, 3, 6, 1, 2, 2, 1, 1] These are random integers drawn with a uniform distribution from the set {1,2,3,4,5}, so the underlying curve should be the constant 3. If we take moving averages for a length of three, we get the sequence. [5.33, 4.67, 4.67, 4.33, 4.0, 4.0, 4.33, 5.67, 5.33, 3.67, 2.0, 1.67, 3.33, 3.33, 3.0, 1.67, 1.67] Notice that this sequence is two elements shorter than the original one. This is because there is no way to calculate the moving average for the points. There are no other points "beyond the end" to complete the average. Here's the Python function which computes the moving average of three. def ma3(s): return map(lambda x,y,z: (x+y+z)/3.0, s[0:-2], s[1:-1], s[2:]) Applying the function recursively three times ("ma3(ma3(ma3(ma3(ma3(seq)))))") yields [4.34, 4.42, 4.56, 4.56, 4.25, 3.68, 3.13, 2.80, 2.74, 2.69] If you apply the function again several times, you'll see more changes, but the successive changes become smaller and smaller. Because you are shortening the list by two every time, eventually, you'll run out of data. The other basic smoother is to consider any odd number of successive data points and replace the center one by the median. The median of a sequence of numbers is the number in the middle of them when they are sorted. For example the median of the sequence (2,5,5,10997,1,3,0) is 3. If we sort the original sequence we get (0,1,2,3,5,5,10997). There is the same number of data points above 3 as there is below it. Here is some very inelegant code to calculate running medians of three: def rm3(s): temp = map(lambda x,y,z:[x,y,z], s[:-2], s[1:-1], s[2:]) temp2 = [] for x in temp: x.sort() temp2.append(x[1]) return temp2 (I'm sure that this can be rewritten in a functional form.) Using this function to apply running medians of three to the initial sequence yields [5, 5, 5, 5, 5, 5, 5, 6, 6, 4, 1, 1, 3, 3, 2, 2, 2, 1]. You should notice one big difference right away; there are no fractions. Each number in the sequence is always replaced by a number from the sequence (maybe itself). This gets rid of statements like "the average family has 1.8 children." This sometimes gives running medians the edge when dealing with discrete data such as the number of I/O connections per minute. Notice too that the running median also reduces the influence of really wild numbers on the calculation. The median of (2,5,5,10997,1,3,0) is 3, but the mean (arithmetic average is 1573.29. This is often why it only takes one or two very high scores to "raise the average" and "bust the curve" in an academic examination. Deciding whether it is better to use moving averages or to use running medians is not always easy. In complex cases it requires deep understanding of where the data came from, how it was measured, and how you plan to use the numbers you get. It's too complex to try to discuss here. So, I hope this will help answer your question. If not, I hope I haven't wasted too much of your time. Peter Olsen, PE, Ae.E. Senior Technical Staff Member Government Solutions, ATT From henrik.motakef at web.de Wed Sep 18 18:36:57 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 19 Sep 2002 00:36:57 +0200 Subject: linux python ideas References: <3D88E578.6010001@diespammerdieuselesspython.com> Message-ID: <87u1kmncvq.fsf@pokey.henrik-motakef.de> Rob Andrews writes: > I'll be giving a presentation on Python to my local LUG > (http://lugoj.org) in a few weeks, and would like to point out at > least a few things that would be of particular interest to linux users. Aren't RedHat's installer and Gentoos "portage" packaging system written in Python? From dsavitsk at e-coli.net Sat Sep 14 18:54:21 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sat, 14 Sep 2002 22:54:21 GMT Subject: win32security.LogonUser not working Message-ID: I am trying to run code as another user. I copied the code below from ASPN, so it would seem that someone has gotten this to work. I keep getting the error pywintypes.api_error (1314, 'LogonUser', 'A required privilege is not held by the client.') Google has revealed that others gave had the same problem. does anyone know a solution, or even a different way to do this? -doug link to the original of code below http://www.google.com/search?q=cache:Jnbt2XVyGfUC:aspn.activestate.com/ASPN/ Python/Reference/Products/ActivePython/PythonWin32Extensions/Windows_NT_Secu rity_.2d.2d_Impersonation.html+self.handel%3Dwin32security.LogonUser&hl=en&i e=UTF-8 --------------------------------------------- import win32security import win32con import win32api import sys class Impersonate: def __init__(self): self.domain = '.' self.login = 'myusername' self.password = '**********' def logon(self): self.handel=win32security.LogonUser(self.login, self.domain, self.password, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT ) win32security.ImpersonateLoggedOnUser(self.handel) def logoff(self): win32security.RevertToSelf() #terminates impersonation self.handel.Close() #guarantees cleanup if __name__ == '__main__': a=Impersonate() try: a.logon() #become the user print win32api.GetUserName() #show you're someone else a.logoff() #return to normal except: print sys.exc_type , sys.exc_value From bokr at oz.net Fri Sep 6 19:44:34 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Sep 2002 23:44:34 GMT Subject: Interrupting Python References: Message-ID: On Fri, 6 Sep 2002 17:38:55 -0400, "Bob Easton" wrote: >Thanks to all. My system is Win2K. Python simply ignores Ctrl-c and >Ctrl-break. I think I'll fall back to using file existence as a simple If this were true as generally as you put it, we should be looking for a bug. Would you put the following listed catchCtlC.py file in a convenient directory, and then go there with **a plain "DOS" command window**, and type the command catchCtlC.py 1000 It should complete in a short time. Then try it again, hitting Ctrl-C before it finishes. If you have a fast machine and need more time, add another zero to the 1000. Let us know if no interrupt is reported for either Ctrl-C or Ctrl-Break. Then tell us what's different about your program. ---< catchCtlC.py >------------------ i=x=0 def foo(n): global i,x for i in xrange(n): x = i**100 if __name__ == '__main__': import sys try: foo(int(sys.argv[1])) # call your thing here instead except KeyboardInterrupt: print 'Interrupted by Ctrl-C' else: print 'Exited w/o interrupt' print 'FHOI, the last i**100 x value: %s**100 = %s' % (i, x) ---< catchCtlC.py >------------------ >semaphore. That will be good enough and cheap enough for this application. > >-- >Bob Easton > > >"David LeBlanc" wrote in message >news:mailman.1031345649.9840.python-list at python.org... >> > I have a script that can run, accessing network resources, for >> > several days. >> > Since the script does not normally need keyed input, exception >processing >> > does not raise the keyboard exception until after the program >> > ends normally. >> > I would like to be able to interrupt if from the keyboard, but have not >> > learned the trick. How can I do this? >> > >> > -- >> > Bob Easton >> >> I have had the experience of Python progs not responding to ctrl-c or >ctrl-d >> on Windows, but I found that ctrl-break works every time. >> >> Dave LeBlanc >> >> Also, please post responses below what you are responding to ;-) Regards, Bengt Richter From aleax at aleax.it Wed Sep 25 05:17:24 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 09:17:24 GMT Subject: Python Compiling References: <3D912249.6040409@something.invalid> Message-ID: Greg Ewing wrote: ... > etc. You can hardly rely on *anything* staying the > same from one moment to the next in Python! Try Ruby, where you can modify built-in types too... I _thought_ Python was pretty dynamic indeed, until I started toying a little bit with Ruby...!-) Alex From dsavitsk at e-coli.net Fri Sep 13 10:25:43 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 13 Sep 2002 14:25:43 GMT Subject: Tkinter experts out there? References: Message-ID: also, Python and Tkinter programming (by John Grayson) comes w/ an author online forum that seems to still be active? http://www.manning.com/grayson/ -d "J?rgen Cederberg" wrote in message news:nJgg9.22$6b7.514 at news.get2net.dk... > "Marcus" wrote in message > news:mOfg9.461067$UU1.75649 at sccrnsc03... > > I am trying to get some answers on using Tkinter, does anyone know if > there > > are channels or forums being actively used? > > Hi Matthew, > > you can ask away here in comp.lang.python. People are happy to answer your > questions regarding Tkinter. Other resources of interest are: > > An introduction to Tkinter by Fredrik Lundh: > http://www.pythonware.com/library/tkinter/introduction/index.htm > > Tkinter: GUI programming with Python > http://www.nmt.edu/tcc/help/lang/python/tkinter.html > > Python Faqts > http://www.faqts.com/knowledge_base/index.phtml/fid/264 > > > Regards > Jorgen > > From gerhard.haering at gmx.de Sun Sep 29 13:17:41 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 29 Sep 2002 19:17:41 +0200 Subject: Python's import: why doesn't it work? In-Reply-To: <874rc8d9c9.fsf@nospam.eml.cc> References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <874rc8d9c9.fsf@nospam.eml.cc> Message-ID: <20020929171740.GA1923@lilith.ghaering.test> * Mahesh Padmanabhan [2002-09-29 16:55 +0000]: > You need to create an empty file called __init__.py inside the > template directory and call the blah.py script as follows: > > import template.blah It's also highly recommended to start Python with "python -vv", then trying to import the module in question. This will show you where Python tries to find the module. Btw. sys.modules contains the module search path. -- Gerhard From gerhard.haering at opus-gmbh.net Mon Sep 16 08:44:12 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 16 Sep 2002 12:44:12 GMT Subject: Problem with HTTPS request References: Message-ID: Steve Holden wrote: > Well, I don't think we disagree on the importance of presentation and > compliance with standards. Perfect. > I simply think you have to allow some leeway to people who either > a) may not know any better That was the reason I was complaining, so people who read this (and not just the poster) /will/ know better. Private email would have been more appropriate, but OTOH only reach the poster. > or b) may not have a choice about the mailer they use at work, for > example. These people should be a minority of Outlook Express posters here, as reading/posting to comp.lang.python is hardly required in many jobs. Plus, if you're forced to use inappropriate tools for elementary tasks, then maybe you should try to find a job where developers are treated appropriately. > [...] but-feel-free-to-continue-ly y'rs -s teve No, the public and private replies showed that this wouldn't be welcome. -- Gerhard From tim at lesher.ws Mon Sep 9 12:26:15 2002 From: tim at lesher.ws (Tim Lesher) Date: 9 Sep 2002 09:26:15 -0700 Subject: Larry Wall's comment on python... References: Message-ID: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) wrote in message news:... > I take Larry Wall as a nice and clever guy. Perl does not marry so well with > evolution, and this is probably the doom of all languages which do not enough > foresee evolution, and overly praise backward compatibility. Because the language has grown by accretion, many Perl advocates tend to draw parallels between the evolution of a language over its lifetime and the evolution of species. I think that this leads to some invalid assumptions. Evolution of species works because of natural selection. Many random mutations are "tried", similar to the individual displacements in Brownian motion. Those that prove advantageous for a given set of circumstances persist. That's all there is to it--no worry about whether this mutation is a good idea overall, or whether it makes the organism compatible with previous generations, or whether this mutation makes the DNA sequence easier to read or harder to fit on an 80-column screen. :-) The moment you talk about designing for language evolution, or maintaining backwards compatibility, or pretty much any kind of intelligent process governing the change over time, you have to drop the comparison with natural evolution, as enticing as the comparison might be. Keeping a bad analogy just muddles conversation. -- Tim Lesher tim at lesher.ws From mmaddox at hcsmail.com Fri Sep 6 18:06:30 2002 From: mmaddox at hcsmail.com (mmaddox at hcsmail.com) Date: Fri, 6 Sep 2002 18:06:30 -0400 (EDT) Subject: Larry Wall's comment on python... Message-ID: <200209062206.g86M6UVm092251@mail.hcsmail.com> > - It causes me to factor code better. Python encourages a style that > obviates (some of) the need for the kind of syntactic structures found in older > block-structured languages. I would argue that the "older" block-structured languages were considered a breakaway from the column-based languages - RPG2 and Fortran, for instance. Although I grant the Python structure and the column-based structures are not completely analogous, they BOTH burden the programmer with arbitrary rules to govern the physical layout of the code. Although this layout may be considered more elegant from a readability standpoint, it's the enforcement of the layout that is irritating to the more Libertarian of us. It's a mindset difference similar to that between Pascal and C++. Having read Wall's comments on Slashdot, I think he is really just mildly complaining about ridiculously long page-widths in his editor, not really slashing Python seriously. He's just giving some props to his own baby at the expense of another. (He had to say something, right?) You must agree that Python can lead you to horizontal scrolling in your editor - the bane of user interface design. Yes, I am new here. Hi, everyone. -- Michael F. Maddox Senior Software Engineer Hayes Tallahassee, FL, USA From tdelaney at avaya.com Tue Sep 3 19:27:10 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Wed, 4 Sep 2002 09:27:10 +1000 Subject: Pyrex 0.4.4 Message-ID: > From: Greg Ewing > > Pyrex 0.4.4 is now available: > > http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ The Plex package appears to be a shortcut/link, rather than the package ... Tim Delaney From james.kew at btinternet.com Sun Sep 8 15:47:55 2002 From: james.kew at btinternet.com (James Kew) Date: Sun, 8 Sep 2002 20:47:55 +0100 Subject: transform a list of lists in a lit of strtings??? References: Message-ID: wrote in message news:mailman.1031507832.24527.python-list at python.org... > I have a list of lists like this: > > labels=[['D1'], ['D2'], ['D3']] > > and i want to transform ia a list of strings > > labels2==[ 'D1' , 'D2' , 'D3' ] <<<<<<<----------- how i can get it???? > Troels' answers are good if what is required is a list of the first items in all sub-lists. But it's possible the OP actually wants to produce a concatenation of all sub-lists: labels1 = [["D1"], ["D2"], ["D3", "D4"]] --> labels2 == ["D1", "D2", "D3", "D4"] Normally I'd write this as: labels2 = [] for sublist in labels1: labels2 += sublist but a quick shufti at the built-in functionals and the lambda form, both of which I've been shy of up to now, suggests also the one-liner: labels2 = reduce(lambda x, y: x+y, labels1) Can this be written in list comprehension form? Can't quite see one at the moment... -- James Kew james.kew at btinternet.com From hellen at claggetts.net Sun Sep 15 20:20:38 2002 From: hellen at claggetts.net (Jonathan Claggett) Date: 15 Sep 2002 17:20:38 -0700 Subject: representing a literal single slash References: Message-ID: "dsavitsk" wrote in message > > > str = str.replace('\\', '\') # broken > > > > in the above you are replacing a single slash with, well, with nothing. > try > > >>> str = str.replace('\\\\', '\\') # [not] broken > > > > -d > > you might also want to rename that variable. else the str() function will > be a problem. Thanks, that works. I knew it was an easy one :-) BTW, my code now looks like this: mystr = mystr.replace(r'\\', '\\') # replace two slashes with on From mlerner at nospam.is.goodspam.umich.edu Mon Sep 9 12:01:32 2002 From: mlerner at nospam.is.goodspam.umich.edu (Michael George Lerner) Date: Mon, 09 Sep 2002 16:01:32 GMT Subject: Can't exponentiate zero in NumPy References: Message-ID: Rick Muller wrote: > This crashes on Linux, but not on Mac OS X. Here's another data point for you: PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond >>> from Numeric import * >>> a = zeros(3,Float) >>> a**2 array([ 0., 0., 0.]) >>> a[1] = 1.e-310 >>> a array([ 0.00000000e+000, 1.00000000e-310, 0.00000000e+000]) >>> a**2 array([ 0., 0., 0.]) >>> import Numeric >>> Numeric.__version__ '21.0' From aleax at aleax.it Mon Sep 16 04:20:52 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 16 Sep 2002 08:20:52 GMT Subject: Source code References: <37fh9.112911$pX1.4044383@news2.tin.it> <7xk7lml7px.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: ... > hostile parties touch the hardware. Nonetheless, the pay TV industry > deploys millions of sealed computers (smart cards) every year to > customers, every single one of which is considered an attacker. While > that industry had spectacular early security failures, these days it's > a fairly solved problem and they limit losses to acceptable levels. According to a lot of discussion that was bandied around in Europe in recent months, what with Kirsch's headline-making bankruptcy and the woes of most other European pay-TV suppliers, this may not be the case in Europe. Pay-TV does seem to be plagued by widespread piracy, in Europe, that may go some way towards explaining why all pay-TV suppliers are bleeding red ink (actually, all except one UK supplier, I believe). I have no way to check whether the discussion reflects reality, of course. > It doesn't sound like the OP was asking for this type of solution though. If somebody asks for a magic wand which, when moved in appropriate ways while whispering "abra-cadabra", makes minor cuts on one's skin go away, I think it's quite helpful to point out that such magic wands, while often dreamed about, appear not to exist, and furthermore to point the poster towards the use of disinfectants and band-aids, which seem to be more effective real-world ways to deal with such minor cuts and scrapes on one's skin. Even though the OP may not have been working for the only apparently workable type of solution, pointing that type of solution out may still be the best one can do. Alex From kp at kyborg.dk Thu Sep 26 04:28:34 2002 From: kp at kyborg.dk (Kim Petersen) Date: Thu, 26 Sep 2002 10:28:34 +0200 Subject: object changing itself to another object References: Message-ID: <3D92C532.7060505@kyborg.dk> Glen Murphy wrote: > I'm creating a program that takes user input, and passes it to an object - > however, I want that object itself, and not the parent to change where that > input goes. In the highly simplified example below, I would like the output > to be "Obj1","Obj2","Obj1" - but not suprisingly, I just get Obj1, Obj1, > Obj1 > > > ### code begin ### > > class Obj1: > def key1(self): > # do obj1 specific stuff > self = Obj2() > print "Obj1" > > class Obj2: > def key1(self): > # do obj1 specific stuff > self = Obj1() > print "Obj2" > > a = Obj1() > > # simulate user keypresses > a.key1() > a.key1() > a.key1() > > ### code end ### > > I know I could achieve the result I want by doing horribly complicated trees > of ifs and such, but I'd like my code to be nice and expandable (in this > example, to easily add new Objs). I've looked through the Python FAQ, Google > Groups and Various O'Reilly books, but I don't really know the terminology > for what I'm looking for, so I haven't found anything so far, so does anyone > have any pointers? Terrible hack (but works for me...) class Obj1: def key1(self): # do obj1 specific stuff self.__class__=Obj2().__class__ print "Obj1" You might want to make a "metamorphosis" __init__ that converts/creates the variables needed in another class.... Just as a note: I needed this in Qt programming - since i couldn't change the autogenerated source's - and needed to subclass some of the Qt classes ... so i metamorph the autogenerated classes into mine instead ... which works - but i sure wish that there was a better way of telling the Designer what to do (or have a "smart" importer like the one in glade (where it loads the XML directly - and you can tell what classes a specific name must be - overriding the XML stuff...) > > Any help would be greatly appreciated, > Cheers, > Glen > > -- > Glen Murphy, http://glenmurphy.com/ > > From tjreedy at udel.edu Tue Sep 17 12:04:19 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Sep 2002 16:04:19 GMT Subject: More on Protecting Source Code References: <3d86b4a0$0$23173$afc38c87@news.optusnet.com.au> Message-ID: <7oIh9.95980$z91.3653979@bin3.nnrp.aus1.giganews.com> "Lothar Scholz" wrote in message news:icieou0lpp0cgqetbl560airkm5ohuqcn2 at 4ax.com... > But it could be changed easily if the core python developer would see > this problem as relevant as commerical users. But at the moment they > don't see the point. Thats the problem. It seems to me that current and would-be commercial users/sellers who want something written for their particular benefit should follow their philosophy and *pay* someone to make the 'easy changes'. Not-holding-my-breath, TJR From brueckd at tbye.com Mon Sep 23 10:55:23 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Mon, 23 Sep 2002 07:55:23 -0700 (PDT) Subject: Python HTTPSConnection/HTTPResponse Problem In-Reply-To: <9abedeb.0209221910.7fb75f6f@posting.google.com> Message-ID: On 22 Sep 2002, Edward Muller wrote: > I *think* I found the problem. Using m2Crypto and urllib I was able do > process the transaction through Authorize.net's ADC Direct Response > mechanism and it *looks* like their server replied first with a .. > > HTTP/1.1 100 Continue > > and then with a ... > > HTTP/1.1 200 OK > > I don't know if this is valid or not (and I sent the same info to > Authorize.net). Yes, the 100 Continue is valid. It exists so that a client can get an early indication as to whether or not the server will accept the client's request message that includes a (possibly large) request body (e.g. a large POST request). As with so many other features of HTTP, the use of the 100 code is ambiguous for backwards compatibility reasons and therefore unnecessarily complex. ;-) To handle it, your receiving code should generally _not_ expect to receive a 100 Continue, and should simply ignore it if it comes (turn around and read the response headers again). -Dave From gerhard.haering at gmx.de Sun Sep 1 15:19:41 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 1 Sep 2002 21:19:41 +0200 Subject: Executable Python Programs In-Reply-To: <1rtc9.108$LI2.7238@newsread2.prod.itd.earthlink.net> References: <1rtc9.108$LI2.7238@newsread2.prod.itd.earthlink.net> Message-ID: <20020901191940.GB3759@lilith.ghaering.test> * CotaBas [2002-09-01 18:58 +0000]: > This is probly a stupid question ...... Questions that are answered in the FAQ are stupid questions, yes. The FAQ is located here: http://www.python.org/cgi-bin/faqw.py > how do you make your python programs executable (without python IDLE). > > For example: > > I write a program that I want to give to a friend to run on his > computer. Easy solution: make your friend instal Python. > He doesn't have Python. What can I do to make it so he can run it > without Python? By read the FAQ. Item 4.28 answers your question. My personal opinion is that py2exe/Installer/etc. are for intermediate/advanced Python programmers. The reason is that it's sometimes difficult to fix the dependencies manually, if these tools are unable to hunt them down automatically for you. Installing Python on the target computer is almost always the simplest solution. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From eric.brunel at pragmadev.com Tue Sep 3 10:38:03 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 3 Sep 2002 16:38:03 +0200 Subject: How to avoid freeing memory on exit? References: <3d74b6dc$0$231$4d4ebb8e@news.nl.uu.net> Message-ID: Gumuz wrote: > so what does 'one' underscore prefixing a methodname mean? For Python, nothing. For would-be users of the method: "do not use unless you know what you're doing" ;-) -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From sismex01 at hebmex.com Fri Sep 6 19:12:09 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 6 Sep 2002 18:12:09 -0500 Subject: Larry Wall's comment on python... Message-ID: > > Of course, most of my current code has one big block, > > main(), and I just cut-and-paste the rest. This just makes me shudder... sheer horror.... :-D -gus -- Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From loewis at informatik.hu-berlin.de Sun Sep 15 13:55:03 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 15 Sep 2002 19:55:03 +0200 Subject: Is Python 2.1 for Solairs 8 broke on SunFreeware? References: <8d148763.0209131005.65de04a8@posting.google.com> Message-ID: yaipa at aol.com (yaipa) writes: > % /usr/local/bin/python CronTar.py -c cronTar.cfg > Traceback (most recent call last): > File "/export/fruid/bin/CronTar.py", line 26, in ? > import time > ImportError: ld.so.1: /usr/local/bin/python: fatal: > libgcc_s.so.1: open failed: No such file or directory > % That is somewhat unfortunate: gcc 3.2 links another shared library to every binary. > Am I required to have gcc installed also? [...] > Any ideas? No need to do that. Just install the libgcc package from Sunfreeware also. This is much less than the full GCC. Regards, Martin From Thomas.Powell at Yum.com Tue Sep 3 15:55:34 2002 From: Thomas.Powell at Yum.com (Powell, Thomas) Date: Tue, 3 Sep 2002 15:55:34 -0400 Subject: Servizi Internet Message-ID: Wasn't this spam from an _ISP_ anyway? An abuse message to the ISP might get them to back off their spamming practices, but otherwise, what is the only "legal" recourse? Complain to their backbone provider? Thomas Powell ------------------------------------ Field Systems Development, Pizza Hut SUS Yum! Brands, Inc. -----Original Message----- From: Fran?ois Pinard [mailto:pinard at iro.umontreal.ca] Sent: Tuesday, September 03, 2002 3:41 PM To: Gerhard H?ring Cc: python-list at python.org Subject: Re: Servizi Internet [Gerhard H?ring] > The only means you have is complain to their ISP > (abuse@{name_of_ISP}). This is rather discouraging, you know. Most ISP around here, and especially the big ones, could not care any less. Thinking about it, some international providers are not fully pink either. They are far more interested into protecting the anonymity of those from which they receive money. Aren't they in business, after all? They will almost never take action unless forced to do so by police intelligence services, and such services are so horribly heavy or slow to get in motion that it is almost a lost cause as far as practice is concerned. Police people affected to computer crimes told me that they are severely understaffed, and fully overwhelmed by requests emanating from big banks or military agencies, which are to be served in priority. Moreover, in far too many cases, they have youth protection law in their way. We pay all the way. Spammers use our network connectivity, our CPUs, our disks and our own time for bothering us; they misredirect rejects so companies pay postmasters or sysadmin services to handle their crap; and everybody invest effort and energies trying to escape the constant annoyance. While politicians, from their ivory towers, discourse on the virtues of Free Speech! -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard -- http://mail.python.org/mailman/listinfo/python-list This communication is confidential and may be legally privileged. If you are not the intended recipient, (i) please do not read or disclose to others, (ii) please notify the sender by reply mail, and (iii) please delete this communication from your system. Failure to follow this process may be unlawful. Thank you for your cooperation. From pyth at devel.trillke.net Wed Sep 11 19:21:51 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 12 Sep 2002 01:21:51 +0200 Subject: I must be an idiot, please pity me! In-Reply-To: ; from sam@localhost.localdomain.trillke.net on Thu, Sep 12, 2002 at 12:05:22AM +0100 References: <3D801757.1020901@nospam.free.fr> Message-ID: <20020912012151.V3893@prim.han.de> newbie wrote: > On Thu, 12 Sep 2002 01:25:59 +0100, laotseu wrote: > > > > Creating a db connection in each function for sure not be very > > efficient.But what's wrong with passing the database connection to the > > functions in mod1, mod2, and modXXX ??? > > That connection has to be passed to the other functions (where needed of > course) in mod1. Say, mod1.functiona may use functions f1, f2 and f3. My > gut feeling of having to pass that connection to all of these said "this > can't be right". This is what I've done but it sure doesn't feel right! > > > > Anyway, you can make it simpler, like this : > > Yay, now for the good stuff! > > > > in each module, > > - create a global db_connection variable - add an init() function, that > > takes a db_connection as argument and assign it to the module's global > > db_connection variable - and don't forget to call this function before > > any other. > > Yes, I can follow that. Once I saw that "global" was more "local" I've > never really considered using it. one common idiom is to do import mydb ... use mydb.connection ... and somewhere at initialization time import sys class mydb: connection = ... # initialize it sys.modules['mydb']=mydb 'import' imports always the same object. Usually it's a module-object but can you put in your class/type. of course you can also simply define a module 'mydb.py' in a file and import that everywhere. Besides not having another file the above solution makes it quite impossible to use the module/class before it is initialized. regards, holger From mstenner at phy.duke.edu Fri Sep 27 17:39:11 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Fri, 27 Sep 2002 17:39:11 -0400 Subject: watching mutables? In-Reply-To: ; from anton@vredegoor.doge.nl on Fri, Sep 27, 2002 at 11:12:05PM +0200 References: Message-ID: <20020927173911.A17971@phy.duke.edu> On Fri, Sep 27, 2002 at 11:12:05PM +0200, Anton Vredegoor wrote: > On Fri, 27 Sep 2002 22:06:41 +0200, "Thomas Heller" > >Here's what seems to be available: > >http://oomadness.tuxfamily.org/downloads/ > >and this is obviously where the EventObject is contained in: > >http://oomadness.tuxfamily.org/downloads/EditObj-0.3.tar.gz > > Very interesting module. I might add that windows doesn't seem to like > the .cfg file so this should be moved to some other place before > installing with 'python setup.py install'. > > But... > > I specifically asked for something that doesn't touch the original > object. In eventobj.py's docstring there is the following warning: > > > Caution : As event management is performed by changing the class of > the instance, you use eventobj with critical objects at your own > risk... ! > > > So, with a lot of thanks for the results sofar ... > > Is it possible? Just to be clear, it doesn't so much affect the original object, but rather REPLACES the class before the object ever gets created. If this isn't satisfactory, then I think you're going to need to modify the python interpreter. -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From wlfraed at ix.netcom.com Fri Sep 27 17:45:05 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Fri, 27 Sep 2002 14:45:05 -0700 Subject: Better terminal for windows? References: <3D94B037.2020202@motorola.com> Message-ID: <1hj2na.u44.ln@ix.netcom.com> Stephen Boulet fed this fish to the penguins on Friday 27 September 2002 12:23 pm: > I'm using python 2.2.1 on winnt. > > If I want to run python interactively (and perhaps using ipython), is > there something better than the "cmd" terminal? PythonWin (ActiveState as I recall) Idle -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From lutz at lutz-horn.de Mon Sep 16 07:25:30 2002 From: lutz at lutz-horn.de (Lutz Horn) Date: 16 Sep 2002 13:25:30 +0200 Subject: read a line from socket (was: (no subject)) References: Message-ID: "Srijak Rijal" writes: > I just migrated from perl to python and was wondering if python > socket can be read line by line too? How can I get only one line of > input from the server without losing info? Split the string returned by recv() on the newline(s), save the returned strings and use them at will. Lutz From gmcm at hypernet.com Thu Sep 19 18:38:09 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: Thu, 19 Sep 2002 18:38:09 -0400 Subject: ANN: Installer 5b4 Message-ID: <3D8A1991.8111.BE3A321@localhost> Announcing version 5b4 of Installer: http://www.mcmillan-inc.com/installer_dnld.html Changes in 5b4: Bug fixes: - recompile if .py file in a package is newer - fix segfault on Linux / Unix if executable is on the $PATH - fix segfault / access violation on very long script names - many other minor bug fixes Enhancements: - works with .pyw files (or any file extension, including none) - add --strip option to run the executable and shared libs through strip. Platforms: Windows Linux Unix (relying on volunteers) Python versions: tested with Python 1.5 to 2.2 What is it: The Installer package is any easy way to deploy Python apps to systems without Python installed (or with incompatible Pythons installed). Installer support single-file and single-directory deployments. On Windows, Installer supports COM, including in-process COM servers. License: MIT style. Contact: gmcm at hypernet.com

Installer Release 5b4Easy Python app deployment. (19-Sep- 2002). From gumuz at looze.net Tue Sep 24 06:55:18 2002 From: gumuz at looze.net (Gumuz) Date: Tue, 24 Sep 2002 12:55:18 +0200 Subject: Difference between MOD_PYTHON and the CGI module Message-ID: <3d904321$0$234$4d4ebb8e@news.nl.uu.net> What are the differences, if any? Am i mixing up to things here? Suppose I'd like to use python as a 'replacement' for PHP, what do I use? thanks, gumuz From duncan at NOSPAMrcp.co.uk Tue Sep 17 04:31:23 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 17 Sep 2002 08:31:23 +0000 (UTC) Subject: CFP: UK Python Conference 2003 References: Message-ID: Gareth.McCaughan at pobox.com (Gareth McCaughan) wrote in news:slrnaocste.qcp.Gareth.McCaughan at g.local: > Duncan Booth wrote: >> *** Call for Participation *** >> UK Python Conference 2003 >> >> April 2-3 2003 >> Holiday Inn, Oxford > ... >> To submit a proposal, send an email message to duncan at rcp.co.uk by 2nd >> October 2003. In your message, please include the following: > ^^^^ > > I'd like to propose a paper on "Novel applications of > Guido's time machine". :-) And there I was feeling miffed about not being able to spell the subject line! Well, we are hoping that Guido will be there, so I'll just ask him to nip forward and collect the abstracts in time for the real deadline of 2nd October 2002. Repost with the deadline corrected: *** Call for Participation *** UK Python Conference 2003 April 2-3 2003 Holiday Inn, Oxford The UK Python Conference 2003 is being held in conjunction with the larger ACCU conference. The conference will include two days of papers arranged in 90 minute speaking slots with either one or two tracks. The audience is highly technical and will include experts in many fields of computing, some of whom may know little or nothing about Python. Talks will be welcomed on any aspect of Python, but we are especially interested in the following: - Commercial applications for Python - Cross-language talks Speakers are welcome from the UK or the rest of the world, however our budget for overseas speakers may be limited. To submit a proposal, send an email message to duncan at rcp.co.uk by 2nd October 2002. In your message, please include the following: - Speaker name and affiliation - Contact address - Presentation title - A one paragraph abstract -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From cbrown at metservice.com Thu Sep 19 01:50:31 2002 From: cbrown at metservice.com (Colin Brown) Date: Thu, 19 Sep 2002 17:50:31 +1200 Subject: handling exceptions References: Message-ID: <3d89659d$1@news.nz.asiaonline.net> > being new to python, I have a question about handling exceptions. I > want to catch an exception which is raised from a module not written > by me, and display a messagebox with the message of the exception > rather than halting the program. The problem is: how can I access the > message string of the exception? Hi Karsten I came across the same problem some time ago when I wanted to write daemon errors into day-based logfiles and wrote myself the module Excepts.py below: --[Excepts.py]---------------------------------- # Return Exception errors as strings import sys, traceback def error(): tb = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info( )[2]) return tb[len(tb)-1].replace('\n','') def errorstack(): return ''.join(traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.e xc_info()[2])) ------------------------------------------------- example usage: import Excepts try: functional_code() except: oneliner = Excepts.error() log(oneliner) errorstack returns the full stack if you want that. Hope this helps. Colin Brown PyNZ From eugene1977 at hotmail.com Sun Sep 15 07:41:59 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Sun, 15 Sep 2002 11:41:59 +0000 Subject: two or more whitespace regular expression? Message-ID: i used this.. words = string.split(line, '['+string.whitespace +']'+'['string.whitespace+']+') which didn't work.. thanks From mennosimons at gmx.net Thu Sep 26 04:52:08 2002 From: mennosimons at gmx.net (Ulli Stein) Date: Thu, 26 Sep 2002 10:52:08 +0200 Subject: unicode woes Message-ID: Hi, in the firm I am working we have a big Python project. Four developers are working on it for over a half year now, and it has grown really big. Nevertheless, due to the Python syntax, and its high level, we still felt very strong in the decision to realize our project in Python. Some weeks ago the management decided to deploy unicode so that we can handle every charset uniformly. The problem which showed at first: we realized that we cannot change the encoding in site.py afterwards, i.e. we have to specify the encoding all the way. It got worse and worse because the unicode encoding spread like a virus through all the source code. Simple Exceptions which we wanted to print to the console throw another Exception: UnicodeError: ASCII decoding error: ordinal not in range(128) Furthermore, in Python you have no way to detect, which encoding a special unicode string atually is. We ended up having our own u() function. The problem with that: we have to pass _every_ string through it. Ouch! Now our source code is as ugly as our program is slow. Isn't there another way? When will the types string and unicode merged together like in Java? If this is not changing and we do not find another way, we will have to port _all_ source code to C++. Please help. def u(obj): encoding = getEncoding() if encoding == None: raise EncodingNotInitialized("There was no encoding defined previously.") if type(obj) == types.StringType: return unicode(obj, encoding) elif type(obj) == types.UnicodeType: # As we can't be sure what encoding the unicode object has we receive, # we will simply re-encode it. return unicode(obj.encode(encoding), encoding) elif type(obj) == types.NoneType: return None elif type(obj) == types.IntType or type(obj) == types.LongType: return unicode("%d" % obj, encoding) elif type(obj) == types.FloatType: return unicode("%f" % obj, encoding) elif type(obj) in [ types.TupleType, types.ListType, types.Dic tType, types.DictionaryType ]: return unicode(str(obj), encoding) else: raise EncodingError("Unconvertable object passed to the u-function.") >>> print "????" ???? >>> a = "????" >>> str(a) '\xe4\xf6\xfc\xdf' >>> print a ???? >>> "????%s"%unicode("???", "iso8859-15") Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII decoding error: ordinal not in range(128) From duncan at NOSPAMrcp.co.uk Thu Sep 12 04:53:11 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Thu, 12 Sep 2002 08:53:11 +0000 (UTC) Subject: dynamism References: <66715c02.0209091923.265fe77e@posting.google.com> <3d7e209a_1@news.iprimus.com.au> <66715c02.0209111633.771aa9d3@posting.google.com> Message-ID: steven_shaw at adc.com (Steven Shaw) wrote in news:66715c02.0209111633.771aa9d3 at posting.google.com: > Thanks alot for your time on this. It was fun! > I hadn't read about the __slots__ > mechanism before. I feel that there must be something wrong, though, > because the Old object layout is winning! Maybe the implementation is > finding the index of the variable in the __slots__ array and then> > using returning __values__[index] in order to implement the attribute > access. I made up the "__values__" array - there must be a values > array somewhere. Array-based object layout amounts to the same thing > as record-based-layout in Python because all primitives are the same > size (right?). There needs to be a way for Python to remember the > indexes... Hmmm. I think your test code doesn't allow the compiler to > remember the indexes since it creates an instance anonymously (using > klass). It is quite hard working out from the code what happens, but basically when you define __slots__ it allocates space in the object to hold the actual data for each slot, and makes a copy of the __slots__ list. It also creates an object of type member_descriptor for each slot and stores it in the class dictionary under the name of the slot. class C(object): __slots__ = ['a', 'b'] inst = C() If you look at C.__dict__['a'] and C.__dict__['b'] they are member_descriptor objects. Accessing inst.a therefore will call C.a.__get__(inst, C) or C.a.__set__(inst, value). Each member_descriptor object knows the offset where its data is stored. So you still have the overhead of a dictionary lookup for every __slot__ access (although Python dictionary lookup is pretty fast), and you have saved the overhead of a dictionary on every instance at the cost of an extra object in the class for each attribute. It is slower than ordinary attribute access because after the dictionary lookup instead of returning the value that was found you have to call one of its methods (although fortunately that doesn't involve another dictionary lookup, just a C call). I hope this makes sense. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From eric.brunel at pragmadev.com Mon Sep 9 04:35:32 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Mon, 9 Sep 2002 10:35:32 +0200 Subject: Accessing Tk-inter Popup menu entry References: Message-ID: Aki Niimura wrote: > Hi, > > I have created a popup menu. (see the attached example code) > Now I would like to change the state of a popup menu entry dynamically. > I tried to use > popup.entryconfig(2, state=DISABLED) > But it didn't work although it worked fine with a regular menu bar. What was the problem? I tried it and it worked, but not with index 2, because the menu item numbered 2 is the 3rd one, which is the separator. But doing: popup.entryconfigure(1, state=DISABLED) works without problem. -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From sholden at holdenweb.com Fri Sep 13 15:12:29 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 13 Sep 2002 15:12:29 -0400 Subject: transform list of int in a list of string?? References: <-1483717605.1031940885180.JavaMail.nobody@webmail2.brturbo.com> Message-ID: "Skip Montanaro" wrote ... > > juliano> How can i transform a list of integer numbers in a list of > juliano> string numbers, like that: > > juliano> x=[1,2,3,4] to y=['1', '2'...]???????? > > Try > > y = map(str, x) > > or > > y = [int(n) for n in x] Skip of course meant y = [str(n) for n in x] in his second example. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From chris.gonnerman at newcenturycomputers.net Sun Sep 8 10:30:48 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sun, 8 Sep 2002 09:30:48 -0500 Subject: python program to watch a file - example. References: <3D7B5650.4050304@zute.net> Message-ID: <004701c25744$5a91ea60$0101010a@local> ----- Original Message ----- From: "Tim Hoffman" > If it is always the same file and seeing you are looking at *nix > varient, one of the unix like ways would be to tail -f the file, and > hook it up to your process which just does blocking reads on stdin. > > ie tail -f somfile | python my_watch.py tail -f is roughly equivalent to: while 1: line = fp.readline() while line: print line line = fp.readline() time.sleep(1) You would use a break to get out of this; or you might want some other sort of exit condition. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From padraig at linux.ie Sun Sep 15 17:41:51 2002 From: padraig at linux.ie (Padraig Brady) Date: Sun, 15 Sep 2002 21:41:51 GMT Subject: representing a literal single slash References: <3D84E9F9.8090101@linux.ie> Message-ID: <3D84FEE6.90600@linux.ie> Padraig Brady wrote: > Jonathan Claggett wrote: > >> Here is an easy question (I'm hoping). >> >> I'm trying to process a string so that all doubled up backslashes (\\) >> are replaced with a single backslash (\). >> >> The obvious approach doesn't work since a single backslash can't end a >> string: >> >> str = str.replace('\\', '\') # broken >> >> So, how does one represent a literal single slash? unicode or hex >> values perhaps? > > mystr = mystr.replace(r'\\', r'\') Emm this actually doesn't work. Why can't you: s=r'\' Is it a bug? Anyway this should work: mystr=mystr.replace(r'\\', '\\') P?draig From news at nospam.eml.cc Sun Sep 29 12:55:47 2002 From: news at nospam.eml.cc (Mahesh Padmanabhan) Date: Sun, 29 Sep 2002 16:55:47 GMT Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> Message-ID: <874rc8d9c9.fsf@nospam.eml.cc> You need to create an empty file called __init__.py inside the template directory and call the blah.py script as follows: import template.blah jhorneman at pobox.com (Jurie Horneman) writes: [snip] -- Mahesh Padmanabhan ------- Replace nospam with prana to email me. From max at alcyone.com Wed Sep 18 18:21:34 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 18 Sep 2002 15:21:34 -0700 Subject: Catching results of an exec References: <3d88f701$0$304$39cecf19@nnrp1.twtelecom.net> Message-ID: <3D88FC6E.59D0DD01@alcyone.com> Greg Fortune wrote: > Is there any way to "catch" the value produced by an exec? I'm > considering > things like print statements that don't really assign a value, but do > send > a result to stdout. The problem is "the value produced by an exec" is ambiguous, because execs (as don't return values). If you want to capture some subpart of the execution of a statement, you'll have to handle it case by case. > Right now I've got a nasty hack that redirects stdout, uses an > InteractiveInterpereter from the code module to execute the code, > writes to > an output file, reads the result from the file, restores stdout and > then > sends the result to the client. Hopefully, that's a terrible way to > do it. That's probably the best way to do it, actually -- or, at least, with an overridden sys.stdout in the globals dictionary that you're passing to eval/exec (which doesn't necessarily have to be the same dictionary as your main script is running). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ I am the king of sorrow \__/ Sade EmPy / http://www.alcyone.com/pyos/empy/ A system for embedding arbitrary Python in template text as markup. From fetus at AUTO Tue Sep 24 20:04:42 2002 From: fetus at AUTO (A. Dimsdale Fetus A. Moser) Date: Wed, 25 Sep 2002 00:04:42 GMT Subject: Pythonwin (win32all build 148) on Python 2.2.1 on Win2K, bogus syntax e Message-ID: I am running Pythonwin (win32all build 148) on Windows 2000 Professional with Python 2.2.1. When I attempt to run a Python script in it, it halts the running of the script on supposed syntax errors, which are completely bogus. Examples: First line of our (Aaron L. Dimsdale and Alex S. Moser) first semi-significant Python script, called fight: """fight.py 5.0 -- crappy primitive fighting game by alex s. moser & aaron l. dimsdale""" ^^^ (note: no linebreak in that line) """if one of the players does not say "atk" or "rest" when asked, they will \ forfeit their turn""" Pythonwin barfed on the quote marks marked by carets, returning: "Failed to run script - syntax error - invalid syntax". I removed those quote marks and the quote marks at the beginning of the second documentation line, and left those two lines as one string. Then, several lines later: p1char = str(raw_input("Player 1, choose your character class: ")) ^ For some strange reason (Alex and I determined that it was either cosmic rays or Windows 2000 rot), Pythonwin returned the same error, pointing at that particular "i" character. I removed "str" and its set of parens, and it still slapped me with the same error on the same character/command. p1weap = str(raw_input("Player 1! Pick your weapon! steak knife, cleaver, tenderizer ")) ^ Pythonwin also pointed out a supposed syntax error on that "a" character in the word "Player". This is so randomly weird it hurts. We couldn't figure out what the hell is going on. By the way, these errors only occured on Aaron's computer at work, in Pythonwin; the script worked fine on Alex's computer, in the same office; on Alex's home computer; on Aaron's home computer; and on Aaron's work computer (the same that gave the syntax errors) under the interpreter packaged with Python itself (not the win32all extensions). --Aaron Dimsdale and Alex Moser From xscottgjunk at yahoo.com Tue Sep 17 04:24:27 2002 From: xscottgjunk at yahoo.com (Scott Gilbert) Date: 17 Sep 2002 01:24:27 -0700 Subject: Python "compiler" is too slow for processing large data files??? References: <3d6d097d$0$321$e2e8da3@nntp.cts.com> Message-ID: <79b2b0bb.0209170024.12ccce1b@posting.google.com> "Ron Horn" wrote > > I'm writing a fairly simple app that loads (text) data files, lets you edit > the data, and then saves them back out. Rather than parsing the data myself > when loading a new file, and building data structures for the program's data > that way, I decided to try to 'import' (or 'exec', actually) the data into > the app. The idea was to be able to format my data files as python code > (see below), and then let the python compiler do the parsing. In the > future, I could actually put 'def' and 'class' statements right into the > data file to capture some behavior along with the data. > > Simple example - I can import or exec this file to load my data (my real app > has int, float, and string data): > ------ try5a3.py -------- > list1 = [ > (323, 870, 46, ), > (810, 336, 271, ), > (572, 55, 596, ), > (337, 256, 629, ), > (31, 702, 16, ), > ] > print len(list1) > --------------------------- > try using this instead: data1 = """323 870 46 810 336 271 572 55 596 337 256 629 31 702 16""" list1 = [tuple([int(x) for x in y.split()]) for y in data1.split('\n')] del data1 It's not as pretty, but I was able to load more than 100,000 lines of 3 elements each in a few seconds with Python 2.2 on my aging laptop. Cheers, -Scott From tim at multitalents.net Mon Sep 16 13:09:40 2002 From: tim at multitalents.net (Tim Rice) Date: Mon, 16 Sep 2002 10:09:40 -0700 (PDT) Subject: test_parser fails Message-ID: I'm trying to get Python-2.2.1 working on SCO Open Server 5 I've got most of it working but I'm concerned about the parser moudle failing the test. Any tips on where to look? Thanks. Here is the output of ./python -E -tt ./Lib/test/test_parser.py -v test_basic_import_statement (__main__.RoundtripLegalSyntaxTestCase) ... FAIL test_expressions (__main__.RoundtripLegalSyntaxTestCase) ... FAIL test_function_defs (__main__.RoundtripLegalSyntaxTestCase) ... FAIL test_import_from_statement (__main__.RoundtripLegalSyntaxTestCase) ... FAIL test_print (__main__.RoundtripLegalSyntaxTestCase) ... FAIL test_simple_assignments (__main__.RoundtripLegalSyntaxTestCase) ... FAIL test_simple_augmented_assignments (__main__.RoundtripLegalSyntaxTestCase) ... FAIL test_simple_expression (__main__.RoundtripLegalSyntaxTestCase) ... FAIL test_yield_statement (__main__.RoundtripLegalSyntaxTestCase) ... FAIL Illegal input: a,,c ... ok Illegal input: a $= b ... ok Illegal yield statement: def f(): return 1; yield 1 ... ok Illegal return in generator: def f(): return 1; yield 1 ... ok test_junk (__main__.IllegalSyntaxTestCase) ... ok Illegal input: print >>fp, ... ok ====================================================================== FAIL: test_basic_import_statement (__main__.RoundtripLegalSyntaxTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_parser.py", line 129, in test_basic_import_statement self.check_suite("import sys") File "./Lib/test/test_parser.py", line 27, in check_suite self.roundtrip(parser.suite, s) File "./Lib/test/test_parser.py", line 18, in roundtrip self.fail("could not roundtrip %r" % s) File "/usr/local/src/utils/Python-2.2.1/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: could not roundtrip 'import sys' ====================================================================== FAIL: test_expressions (__main__.RoundtripLegalSyntaxTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_parser.py", line 42, in test_expressions self.check_expr("foo(1)") File "./Lib/test/test_parser.py", line 24, in check_expr self.roundtrip(parser.expr, s) File "./Lib/test/test_parser.py", line 18, in roundtrip self.fail("could not roundtrip %r" % s) File "/usr/local/src/utils/Python-2.2.1/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: could not roundtrip 'foo(1)' ====================================================================== FAIL: test_function_defs (__main__.RoundtripLegalSyntaxTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_parser.py", line 100, in test_function_defs self.check_suite("def f(): pass") File "./Lib/test/test_parser.py", line 27, in check_suite self.roundtrip(parser.suite, s) File "./Lib/test/test_parser.py", line 18, in roundtrip self.fail("could not roundtrip %r" % s) File "/usr/local/src/utils/Python-2.2.1/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: could not roundtrip 'def f(): pass' ====================================================================== FAIL: test_import_from_statement (__main__.RoundtripLegalSyntaxTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_parser.py", line 119, in test_import_from_statement self.check_suite("from sys.path import *") File "./Lib/test/test_parser.py", line 27, in check_suite self.roundtrip(parser.suite, s) File "./Lib/test/test_parser.py", line 18, in roundtrip self.fail("could not roundtrip %r" % s) File "/usr/local/src/utils/Python-2.2.1/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: could not roundtrip 'from sys.path import *' ====================================================================== FAIL: test_print (__main__.RoundtripLegalSyntaxTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_parser.py", line 71, in test_print self.check_suite("print") File "./Lib/test/test_parser.py", line 27, in check_suite self.roundtrip(parser.suite, s) File "./Lib/test/test_parser.py", line 18, in roundtrip self.fail("could not roundtrip %r" % s) File "/usr/local/src/utils/Python-2.2.1/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: could not roundtrip 'print' ====================================================================== FAIL: test_simple_assignments (__main__.RoundtripLegalSyntaxTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_parser.py", line 83, in test_simple_assignments self.check_suite("a = b") File "./Lib/test/test_parser.py", line 27, in check_suite self.roundtrip(parser.suite, s) File "./Lib/test/test_parser.py", line 18, in roundtrip self.fail("could not roundtrip %r" % s) File "/usr/local/src/utils/Python-2.2.1/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: could not roundtrip 'a = b' ====================================================================== FAIL: test_simple_augmented_assignments (__main__.RoundtripLegalSyntaxTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_parser.py", line 87, in test_simple_augmented_assignments self.check_suite("a += b") File "./Lib/test/test_parser.py", line 27, in check_suite self.roundtrip(parser.suite, s) File "./Lib/test/test_parser.py", line 18, in roundtrip self.fail("could not roundtrip %r" % s) File "/usr/local/src/utils/Python-2.2.1/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: could not roundtrip 'a += b' ====================================================================== FAIL: test_simple_expression (__main__.RoundtripLegalSyntaxTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_parser.py", line 80, in test_simple_expression self.check_suite("a") File "./Lib/test/test_parser.py", line 27, in check_suite self.roundtrip(parser.suite, s) File "./Lib/test/test_parser.py", line 18, in roundtrip self.fail("could not roundtrip %r" % s) File "/usr/local/src/utils/Python-2.2.1/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: could not roundtrip 'a' ====================================================================== FAIL: test_yield_statement (__main__.RoundtripLegalSyntaxTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "./Lib/test/test_parser.py", line 30, in test_yield_statement self.check_suite("from __future__ import generators\n" File "./Lib/test/test_parser.py", line 27, in check_suite self.roundtrip(parser.suite, s) File "./Lib/test/test_parser.py", line 18, in roundtrip self.fail("could not roundtrip %r" % s) File "/usr/local/src/utils/Python-2.2.1/Lib/unittest.py", line 254, in fail raise self.failureException, msg AssertionError: could not roundtrip 'from __future__ import generators\ndef f(): yield 1' ---------------------------------------------------------------------- Ran 15 tests in 0.130s FAILED (failures=9) Traceback (most recent call last): File "./Lib/test/test_parser.py", line 365, in ? test_main() File "./Lib/test/test_parser.py", line 361, in test_main test_support.run_suite(suite) File "./Lib/test/test_support.py", line 174, in run_suite raise TestFailed(msg) test_support.TestFailed: errors occurred; run in verbose mode for details -- Tim Rice Multitalents (707) 887-1469 tim at multitalents.net From ianholmes01 at lycos.com Tue Sep 3 06:52:00 2002 From: ianholmes01 at lycos.com (Ian Holmes) Date: 3 Sep 2002 03:52:00 -0700 Subject: The Module Search Path is ??? References: <7153651c.0209022255.7fd50ba0@posting.google.com> Message-ID: quiteblack at yahoo.com (black) wrote in message news:<7153651c.0209022255.7fd50ba0 at posting.google.com>... > tutorial told me I could found it in the folder:/usr/local/lib/python. > but my OS is windows so folders are different. I searched the folder > "lib" but find no file named "python", any ideas ? c:\pythonXX\ where XX is your version python.exe on windows rather than python if a windows search didn't find this then you are either looking on the wrong drive or python isn't installed. From mhammond at skippinet.com.au Fri Sep 6 21:54:09 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 07 Sep 2002 01:54:09 GMT Subject: Using Python to call a DCOM server - "'Class not registered" References: <3D787D95.9000907@ob_scure.dk> Message-ID: <5%ce9.1272$_l1.2960@news-server.bigpond.net.au> Thomas Jensen wrote: > Code that works: > batch = win32com.client.Dispatch("IGBatchNGBackend.IGBatch") > > Code that doesn't work: > clsctx = pythoncom.CLSCTX_SERVER & ~pythoncom.CLSCTX_INPROC_SERVER > batch = win32com.client.DispatchEx("IGBatchNGBackend.IGBatch", > 'localhost', clsctx=clsctx) > > The traceback is: > > Traceback (most recent call last): > File "test01.py", line 30, in ? > test() > File "test01.py", line 15, in test > batch = win32com.client.DispatchEx("IGBatchNGBackend.IGBatch", > 'localhost', > clsctx=clsctx) > File > "C:\PROGRA~1\PYTHON22\lib\site-packages\win32com\client\__init__.py", lin > e 109, in DispatchEx > dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, > serverInfo, (py > thoncom.IID_IDispatch,))[0] > pywintypes.com_error: (-2147221164, 'Class not registered', None, None) > Are you sure that the COM object you are using is correctly registered for use as a DCOM server. The code above insists that the COM object be registered as LocalServer - ie, other than just InprocServer32. Can you reproduce the registry entries for this COM server (the ones under HKCR\CLSID\the-long-guid-for-the-object ) Regards, Mark. From op73418 at mail.telepac.pt Wed Sep 4 15:29:25 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 04 Sep 2002 20:29:25 +0100 Subject: Why read-only nested scopes? References: Message-ID: On 04 Sep 2002 20:38:30 +0200, loewis at informatik.hu-berlin.de (Martin v. L?wis) wrote: >Gon?alo Rodrigues writes: > >> >Gon?alo Rodrigues writes: >> > >> >> So why hasn't this been extended when nested scopes were introduced, >> >> e.g. by reusing the global directive or some other one? >> > >> >I think the main reason is that nobody could propose an acceptable >> >syntax. Reusing the global directive does not work. >> >> Can you explain why it does not work? > >Consider > >x = 1 > >def foo(): > x = 2 > def bar(): > x = 3 > def baz(): > global x > x = 4 > >If you invoke baz(), which of the variables is changed? How do you >denote that you want to change the others? I think that crawling up the scope hierarchy and stopping at the first x that one finds (in the above case, the one defined in bar) is a sensible solution. Any other solution just seems perfect madness, but then again, most probably I am overseeing something. Anyway, I've been directed to PEP 227, cheerfully obeyed, and from what I have understood having read-only nested scopes was more of a design decision than something else. And while I can live happily with the decision (some would even say happier) there is something about the "You can look at it but not touch it" attitude that I dislike ;-) > >Regards, >Martin Thanks 4 everything and all the best, Gon?alo Rodrigues From sholden at holdenweb.com Tue Sep 17 14:51:44 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 17 Sep 2002 14:51:44 -0400 Subject: [FEEDBACK] Is this script efficient...is there a better way? References: <4ZRf9.1782$Lg2.248733@news2.news.adelphia.net> <3hSf9.168947$l_4.98525@atlpnn01.usenetserver.com> <8PSf9.1796$Lg2.257378@news2.news.adelphia.net> <_oUf9.170870$l_4.126599@atlpnn01.usenetserver.com> <3pkg9.3313$WV.2782@fe03> Message-ID: "Bob X" wrote in message news:fqrh9.7075$Lg2.1331983 at news2.news.adelphia.net... > Steve Holden wrote: > > > I did a test on the 30MB sized logs and the RE did indeed come out the > faster, thought not by much. The interesting thing is it caught more as > well since my script looked for exact matches and the RE based one > ignored case (as far as my feeble brain understands such things). > > I remember why I had the "result" statement. It was because I needed to > write the keyword found and then the line it was found on to the hits file. > > Can't seem to make that work with the RE based one. Then again...I know > RE as far as the east is from the west. > If the match succeeds it returns a match object. The match object has methods that will retrieve the matched substring. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- > From chris.lyon at tgm.co.uk Fri Sep 13 03:42:13 2002 From: chris.lyon at tgm.co.uk (Chris Lyon) Date: 13 Sep 2002 00:42:13 -0700 Subject: Structure Message-ID: <7652d5e7.0209122342.61cb80f2@posting.google.com> I have a set of related classes each are derived from the others in a tree. I then produce multiple instances of the different classes. I wish to edit the properties of the instances and add extra properties specifically depending on which class they are derived from. Is there a standard python approach to constructing this sort of structure. My classes are defined in one module, and the display elements are in a seperate module, since this seems to allow maximum flexibility. So I am using a dictionary with the name as the key and a tuple of display text, sort order, type of data. So for instance when I set background colour I wish to allow the edit facility to choose from a colour selection dialog etc. Since the overall structure is pickled, is there a general structure that allows me not to store a dictionary for every instance, I seem to be developing a seperate tree of classes for these definitions but my display components would seem to want to appear in my 'main' module and I feel my present approach will lead to loosing the flexibility that modules seeem to provide. Chris From leoboiko at linuxbr.com.br Wed Sep 4 19:03:35 2002 From: leoboiko at linuxbr.com.br (Leonardo Boiko) Date: 4 Sep 2002 16:03:35 -0700 Subject: newbie-question: Nested functions and variable scope Message-ID: <7a7157fd.0209041503.7b9a0f44@posting.google.com> Hi, I'm a Python newbie. I'm writing a program that uses expat. Some code looks like this: def generate_main(filename="main.xml", (...)): (...) outfile = open (filename, "w") in_reply = 0 # true if we are inside "reply" element def start_element(name, attrs): if name == "reply": in_reply = 1 elif not in_reply: outfile.write("<" + name.encode(encoding) + ">") def end_element(name): if name == "reply": in_reply = 0 elif not in_reply: outfile.write("") (...) As you may have guessed, this gives me an error: >>> generate_main() Traceback (most recent call last): File "", line 1, in ? File "../xmlgen.py", line 52, in generate_main parser.ParseFile(file) File "../xmlgen.py", line 22, in start_element elif not in_reply: UnboundLocalError: local variable 'in_reply' referenced before assignment If I put "in_reply" outside everything and use "global in_reply" inside each nested function, it works, but that's evil! What would be a better way of doing it? Do I need to use a class? From m.j.fisher at ex.ac.uk Wed Sep 11 10:21:53 2002 From: m.j.fisher at ex.ac.uk (M.J.Fisher) Date: Wed, 11 Sep 2002 15:21:53 +0100 Subject: Background programs on Windows XP Message-ID: <3D7F5181.AD09A901@ex.ac.uk> Hello, I have been using the following code the run a program in the backgroup on Windows'95 and WindowsNT machines: os.spawnl(os.P DETACH, 'c:\\python22\\python', 'python', 'c:\\agents.py') However, when one of the users of this program changed from Windows'95 to WindowsXP (they also changed from Python2.1 to Python2.2 but I didn't think this was probably relevant) this stopped working. I cannot find any information about this in the python documentation or newsgroups so I would appreciate any comments or suggestions. Thank you, Michelle From bokr at oz.net Sun Sep 29 18:00:54 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Sep 2002 22:00:54 GMT Subject: help References: Message-ID: On Tue, 24 Sep 2002 15:58:48 -0300, "Juliana Braga" wrote: >I need help. >For example: >x = ?name1? >How can I get the value of variable x (in this case the value of variable x >is ?name1?). After , I?d like to do this: >value of variable x = ?teste?. > The best advice I can give is to try things interactively. And when you have a question about what happens, copy and paste it right from your interactive session into your post. Also, in Python it's best to think of attaching names to values rather than setting values into named places. I.e., what would an assignment be overwriting a value in C or many other languages really just attaches the name on the left to a different value. Another name can still be attached to the first value. E.g., >>> x = 'name1' # attaches ('binds') name "x" to string value 'name1' >>> y = x # binds name "y" to the same value as "x" is bound to. >>> print x,y name1 name1 >>> x = 'teste' # binds name "x" to string value 'teste' >>> print x,y # y should be unaffected by rebinding of x teste name1 The above looks ordinary, but when you attach a name to a "mutable" object the differences start to become apparent, e.g., >>> x = ['name1'] >>> y = x # bind y to same list object as x >>> print x,y ['name1'] ['name1'] >>> x.append('teste') # modify the list object that x is bound to, but not the binding >>> print x,y ['name1', 'teste'] ['name1', 'teste'] The binding of y is still to the same object, so the modification we did via the x binding to that object shows up via y also. Some operations look the same for notation convenience but really do either rebinding or mutation without rebinding, depending on the target. E.g., lists are mutable, but strings are not, so: >>> x = 'name1' >>> y = x >>> x += 'teste' # x will get rebound to something different than y, whose binding is unchanged >>> print x,y name1teste name1 >>> x = ['name1'] >>> y = x >>> x += ['teste'] # the object x is bound to will get modified, but x and y bindings don't change >>> print x,y ['name1', 'teste'] ['name1', 'teste'] so the modified list shows up via both x and y. There is a good tutorial at http://www.python.org/doc/current/tut/tut.html and many other documentation links at http://www.python.org/doc/ and of course you can start at the top http://www.python.org/ where you'll also find a link to a beginner's guide at http://www.python.org/doc/Newbies.html Have fun. And [OT] thanks to you, we now have one more movie star (last) name posting to c.l.p (along with Peters, Roberts, Holden, Davis, ... ;-) Regards, Bengt Richter From trentm at ActiveState.com Fri Sep 20 21:26:54 2002 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 20 Sep 2002 18:26:54 -0700 Subject: Python threading? In-Reply-To: ; from Oschler@earthlink.net on Sat, Sep 21, 2002 at 12:35:23AM +0000 References: Message-ID: <20020920182654.A7937@ActiveState.com> [Robert Oschler wrote] > How can I tell if the version of Python I am running is thread-enabled? Run Lib/test/test_thread.py with your Python build. If you are on any common platform then Python, unless specifically crippled, is thread-enabled. > Also, what is a reasonable number of threads to expect to be able to run > before context switching overhead becomes a problem (I'm using a PIII 500 > Mhz with 512MB ram if that helps). I have no experience putting that many threads to use. Trent -- Trent Mick TrentM at ActiveState.com From Sylvain.Thenault at logilab.fr Fri Sep 20 11:24:14 2002 From: Sylvain.Thenault at logilab.fr (Sylvain =?iso-8859-1?Q?Th=E9nault?=) Date: Fri, 20 Sep 2002 17:24:14 +0200 Subject: [ANN] PyReverse 0.4 Message-ID: <20020920152414.GI28887@orion.logilab.fr> What's new ? ------------ * add pyvcg command line tool * add support for *.pyreverserc * documentation reorganization and improvement * fix a bug in pyargo What's PyReverse ? ------------------ Pyreverse is a set of utilities to reverse enginering Python code. So far, it features dependency analysis tools, unittest generation, and XMI generation for importation in a UML modeling tool. A special module can be used to generate files readable by Argo UML. It uses a representation of a Python project in a class hierarchy which can be used to extract any information (such as generating UML diagrams and make a few statistics from the Python code, as "pyargo" and "pystats") Home page --------- http://www.logilab.org/pyreverse/ Download -------- ftp://ftp.logilab.org/pub/pyreverse/ Mailing list ------------ mailto://xml-logilab at logilab.org -- Sylvain Th?nault LOGILAB http://www.logilab.org From tismer at tismer.com Sun Sep 15 15:34:41 2002 From: tismer at tismer.com (Christian Tismer) Date: Sun, 15 Sep 2002 21:34:41 +0200 Subject: Stackless Python, eventual merge? References: Message-ID: <3D84E0D1.1000809@tismer.com> David Abrahams wrote: > "Christian Tismer" wrote in message > news:mailman.1032107006.6411.python-list at python.org... > > >>The changes to Python are also so small now, that >>it doesn't matter if it will be merged or not. >>Porting Stackless to a new Python is a matter of a few >>hours. You may rely on getting a Stackless version >>of any new Python version in almost no time. > > > I think it still matters. You don't want people who need stackless' > capabilities to have to use a non-standard Python forever, do you? Who I ??? I've spent a lot of time to get Stackless into the core. I wasted many months by keeping to the rules that *might* get it into the core. This didn't help. For the new version, I gave that up. That gave me the freedom to code as I needed it, and I've come much farer than ever before, in much shorter time. I will not waste time again trying to persuade certain people to include Stackless into the core. This is definately over. If somebody else wants to try, this is fine with me. Please let me stay what I am: The one who writes Stackless Python, supports and maintains it. I really do not take responsibility for being standard or non-standard. My patches are as near to the standard as I can think of. If somebody wants to include them, easy. But not me, this has cost me too much blood, anger, lifetime, disappointment. or-I-might-define-Stackless-as-standard - ly y'rs - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From tismer at tismer.com Wed Sep 18 09:33:32 2002 From: tismer at tismer.com (Christian Tismer) Date: Wed, 18 Sep 2002 15:33:32 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <20020918060823.GB81158@hishome.net> Message-ID: <3D8880AC.7040902@tismer.com> Oren Tirosh wrote: ... > They may be dangerous in some circumstances. IIRC, if a C extension calls > the Python interpreter recursively with pointers to things on its stack > it can cause memory corruption. Then don't switch stacks in that context. The switching occours on your demand. And if this extension is essential and must be protected from any overseen switching, let me add protection code to it. This is easy. But the theoretical possibility to create a crash is no reason to dispense with the benefits. My only chance to do this magic with almost no crash possibility would be to allocate a new stack for every new tasklet. I have considered this many times. A benefit would be reasonably faster switching, while the drawback would be the reasonable high memory requirement for a full machine stack. I might consider a hybrid solution, putting certain "dangerous" extension stuff into a real new stack all the time, together with the quite fast and very cheap other safe tasklets. Just-need-an-idea-how-to-determine-that - ly y'rs - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From 2002 at weholt.org Thu Sep 26 09:54:22 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Thu, 26 Sep 2002 13:54:22 GMT Subject: Python threading? References: Message-ID: This might be just a stupid question, but I'm trying to implement a filesharing-app, based on the BaseHTTPServer in the standard python-distro. This will of course be heavy IO-processing involved. Will threading still be a bad idea? The project is aimed at small user-groups ( I do not think one person will have more than say 5-10 concurrent connections at a time, most of them downloading files 1MB + in size), it's not the new Gnutella/Naptser, but I just can't get the hang of this Threading vs. Asyncore deal. It seems as if threading is a very bad idea no matter what, still it's used almost everywhere ( I got no statistics to back up that statement ;-) ). Any info or opinion on what would be the best way to implement a filesharing app in python; threaded, async, raw-socket etc. are of interest to me. NB! It would be nice to be able to limit the number of threads, actually the number of concurrent connections, on the server too, so if anybody has any comments on some way of doing that and still handle request gracefully, it would be great. Best regards, Thomas "Aahz" wrote in message news:amogmi$r1l$1 at panix1.panix.com... > In article , > Robert Oschler wrote: > > > >Also, what is a reasonable number of threads to expect to be able to run > >before context switching overhead becomes a problem (I'm using a PIII 500 > >Mhz with 512MB ram if that helps). > > It depends. For pure Python-based computation, more than one thread > will cost you more than you gain. If it's almost pure I/O (file or > socket stuff), you might be able to use as many as a couple of hundred > threads. Mostly, you're probably best off somewhere between five and > thirty threads, depending on what you're doing. > -- > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Project Vote Smart: http://www.vote-smart.org/ From fgranger at alussinan.org Fri Sep 20 14:34:46 2002 From: fgranger at alussinan.org (=?ISO-8859-1?Q?Fran=E7ois_Granger?=) Date: Fri, 20 Sep 2002 20:34:46 +0200 Subject: [Help]: mailbox classes References: <1fitpvg.gi8n0y1iem93tN%fgranger@alussinan.org> <1fitpz7.1h4nj4m19gs2x5N%fgranger@alussinan.org> Message-ID: <1fitt21.1a27xor1bmqkizN%fgranger@alussinan.org> Fran?ois Granger wrote: > after some thought and some trial and errors, I came with this solution. > I don't like it, it look bad. > > def main(): > fp = file(folderfile) > folder = mailbox.UnixMailbox(fp, factory=email.message_from_file) > while 1: > mail = email.message_from_file(fp) > print mail > if not folder.next(): > break > #mail = email.message_from_file(fp) > > if __name__ == '__main__': > main() After reading other posts on other matters, light came at least... def main(): fp = file(folderfile) folder = mailbox.UnixMailbox(fp, factory=email.message_from_file) for message in folder: print message This works as expected, as usual in Python, the simple things _ARE_ simple, the complexe ones not difficult ;-). Sorry for any inconvenience. -- "On jouit moins de ce qu'on obtient que de ce qu'on esp?re." - Jean-Jacques Rousseau - Cit? par Anne-Marie From whisper at oz.net Thu Sep 5 17:52:56 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 5 Sep 2002 14:52:56 -0700 Subject: Graham's spam filter In-Reply-To: <3D77AC75.B9B7F27@alcyone.com> Message-ID: > Spammers are hitting upon the strategy, though, of sending emails in > which the body consists of nothing but a completely encoded base64 MIME > part. So in that case, the entire body of your message would consist > solely of your "base64encoded" token. So in the general case of any > kind of spam filter (not just limited to a Graham filter), it's > questionable how useful this will be, unless you plant to always filter > against that token, presuming it to always indicate spam. Ummm... In which case, the headers would probably control the sort. IIRC, Graham said that headers had a large impact on spam/ham determination. Spam header information is already so marked in the filter table of course. > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ > __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE > / \ There is nothing so subject to the inconstancy of fortune as war. > \__/ Miguel de Cervantes > Church / http://www.alcyone.com/pyos/church/ > A lambda calculus explorer in Python. Dave LeBlanc Seattle, WA USA From peter at engcorp.com Mon Sep 16 21:51:02 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 16 Sep 2002 21:51:02 -0400 Subject: Converting Python app to C++ completely References: <3D85D9EB.9020102@thinkware.se> <3D86209F.4080501@earthlink.nospam> Message-ID: <3d868a77$1@news.sentex.net> Roy Smith wrote: > Joe Knapka wrote: > >>You might try rewriting it in Python, using lists of characters >>instead of strings for the stuff that's causing performance >>trouble. Given str, lst = list(str), then do all the processing >>(in place) on lst, and ''.join(lst) to turn it back into a string. > > > An interesting idea, I'll try it! > > The only problem is, I really had two reasons for converting it > in the first place. One was to improve performance, the other was to > learn C++. If I solve the first problem in Python, I won't solve the > second problem at all :-( Hmmm... if instead you choose to wait until you actually *need* C++ to solve a problem that Python can't handle, you just might find that you don't ever need to learn C++. Then the second one is actually not a problem at all! :-) This thought courtesy of XP's philosophy of avoiding unnecessary work, which is acronymized as YAGNI (You Aren't Going to Need It). -Peter From tg5027 at citlink.net Wed Sep 18 00:47:48 2002 From: tg5027 at citlink.net (terry) Date: Wed, 18 Sep 2002 00:47:48 -0400 Subject: Python GUI app to impress the boss? Message-ID: >> Dave LeBlanc wrote: >> What prevents the creation of a decimal money type? Absolutely nothing! And it has been done - sort of. The problem involves the resultant code to implement a business application. In the simple situation, all the developer has to do is be aware on calculation what specific type of variables are being used ( integers for quantities, reals for percentages, etc...) and what the result 'should' be - and then apply the appropriate conditioning to the variables in the calculation and to the result. You can surely contemplate the variability in programming styles and implementations that this generates - most of which flies in the face of the simplicity and readability promised by Python. Contrast that with the following VB code: Amount = Qty * UnitPrice The more difficult problem arises when faced with a true quality assurance environment. The amount of validation rises exponentially when the calculations in a program are implementation specific, as opposed to language intrinsics. Each calculation must be tested at the limits of each of the variables involved - at each instance. The quick reply to your observation is: Yes, anything is possible - but is forcing a language into an environment to which it is not intrinsicly suited a reasonable approach? All of the databases, that Python can easily talk to, have a form of monetary data type. But when those table fields are represented in Python (as well as some other languages) they become a burden. I think Python needs to incorporate an intrinsic data type that monetary (as well as other decimal data types) can be represented by, so that the above equation yields results consistent with the decimal places of the input variables. This cannot be accomplished with real/floats, and shouldn't be accomplished with overlays on integer or character variable types. Python needs this data type, that is not hardware oriented, to become truly mainstream and be a threat to VB. I say this with all due respect to all the other positive attributes of Python and it's flexibility to solve a myriad of other non-business application problems. terry From bondpaper at earthlink.net Mon Sep 30 22:16:15 2002 From: bondpaper at earthlink.net (Tom) Date: Tue, 01 Oct 2002 02:16:15 GMT Subject: Reloading a module References: Message-ID: In article , Fernando Perez wrote: > Tom wrote: > > > > > I'm developing some python mini applets on a Mac (using os 9 and the > > 2.1.1 Python IDE), and I've found it impossible to delete and/or reload > > a module after making changes to the code during the > > debugging/verification process. Is there an easy and/or effective way to > > do this? If I execute: > > > > del mymodule > > > > and then execute a print dir(mymodule), it shows up as nonexistent. > > Then, when I execute: > > > > import mymodule > > > > followed by a print dir(mymodule), the changes do not show up. > > In [1]: reload? > Type: builtin_function_or_method > Base Class: > String Form: > Namespace: Python builtin > Docstring: > reload(module) -> module > > Reload the module. The module must have been successfully imported > before. > > cheers, > > f. I wish it were that simple. I've used reload(module) many times, each time hoping that it would do what the documentation says it will do. I've tested it by adding a simple variable to my module, watching to see if it shows up in the new import, but it never does. I noticed also that sometimes it reloads from the .pyc file, and if the reload happens before the .pyc file is updated with the new changes, the changes won't be available. Even if I force a reload from the updated .py file by deleting .pyc file, it still retains the old code. I'm at a loss to understand what's going on. Thanks, Tom From maxm at mxm.dk Mon Sep 9 03:05:23 2002 From: maxm at mxm.dk (Max M) Date: Mon, 09 Sep 2002 09:05:23 +0200 Subject: Zope Status? References: Message-ID: <3D7C4833.2080308@mxm.dk> Jeff Sasmor wrote: > That's just one thing. Also, Zope 3 is a clean-slate redesign; that is, > it is being rearchitected with no initial regard for existing Zope > applications. I suppose opinions go either way on this, but overall > it is probably a Good Thing. I recall reading that there will eventually > be backwards compatibility, perhaps with some interface layer, but > I suspect that the initial releases will be for very advanced developers. As far as I can see from the examples you actually don't need to be an advanced developer. It seems that it will indeed be much more simple to develop for Zope3 than it is for the current version. Also they are taking care of some of the things that could make it difficult to develop in Zope. Like relations. regards Max M From jmdeschamps at cvm.qc.ca Fri Sep 20 08:45:10 2002 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 20 Sep 2002 05:45:10 -0700 Subject: Tkinter: scrolling the canvas items AND widgets References: <3d06fae9.0209191255.63def2eb@posting.google.com> <3D8A8146.3030506@something.invalid> Message-ID: <3d06fae9.0209200445.6b2c168a@posting.google.com> Greg Ewing wrote in message news:<3D8A8146.3030506 at something.invalid>... > jmdeschamps wrote: > > > This code lets me scroll the graphical items but the widgets stay put > > using PythonWin 2.2.1 on Windows 2000 > > > > > > for i in range(1): > > f=Entry(canvas) > > f.place(x=10,y=10) > > > I think you need to create a window item on the > canvas, with the window attached to it, something > like this : > > f = Entry(canvas) > canvas.create_window(10, 10, window = f) Thanks, :)) - works beautifully! Jean-Marc From anandpillai6 at yahoo.com Thu Sep 26 02:06:37 2002 From: anandpillai6 at yahoo.com (Anand) Date: 25 Sep 2002 23:06:37 -0700 Subject: Pygame event problem References: <41c203e.0209250702.160102d@posting.google.com> Message-ID: <41c203e.0209252206.3c344224@posting.google.com> Hi Shinners That was very helpful! I had thought of making another post about the possibility of embedding the pygame window into wxPython, but you have answered that also. :-) I am a python newbie as you should have guessed. Just finished reading the pygame/wxPython tutorials so I thought I will make an attempt at putting them together. I will try your suggestions in order. Could you suggest some links to learn python multithreading ? Regards Anand Pillai Pete Shinners wrote in message news:... > Anand wrote: > > I wrote a simple image viewer in python using pygame image api. The > > GUI is in wxPython. There are 2 classes, one for the window frame and one > > for the pygame image processing. > > > The effect is stopped by clicking with the mouse on the pygame > > display window. My problem is that if I try to invoke any other menu methods > > in the main GUI frame *without doing this*, the application ie both the > > wxFrame and the pygame display window, hangs. > > > > > > I have a gut-feeling that this is because I am calling a method on > > the MyPyGameImgViewer class without exiting the while loop. > > > > Is there a way around this, ie to call any method in the > > MyPyGameImgViewer class from the GUI class, while one of its methods > > is executing a while loop > > i'd be a little afraid of mixing wxpython and pygame like this, but it > sounds like you are pretty close to running. to exit the pygame loop you > could probably just pass it a mouse button event > > e = pygame.event.Event(MOUSEBUTTONDOWN) > pygame.event.post(e) > > > of course, that also means you'll probably want to clear the pygame event > queue before starting your while loop. also, to clear the event queue it > will probably be better to get _all_ the events from the queue. otherwise > it will fill up with mouse motion and other types of events. change the > event part of the loop to this > > if pygame.event.peek(MOUSEBUTTONDOWN): > pygame.event.get() > break > > instead, you could also filter the pygame event queue, so only mouse button > events were put onto the queue. the code for that would be like this > > pygame.event.set_allowed(None) #allow no events > pygame.event.set_allowed(MOUSEBUTTONDOWN) #only allow buttondown > > > > also, there are ways to get SDL to work within an embedded window. > therefore embed into a wxpython control. basically it involves setting an > environment variable to an existing window id/handle. wxpython allows you > to get the id/handle you need. the code to embed the SDL window looks kind > of like this: > > > handle = wxpython_widget.get_window_id_i_forget_how() > os.environ['SDL_WINDOWID'] = str(handle) > if sys.platform == 'win32': > os.environ['SDL_VIDEODRIVER'] = 'windib' #no directx embedded > pygame.init() > size_is_ignored = 10, 10 > window = pygame.display.set_mode(size_is_ignored) > > also, since you are likely only using the display portion of pygame, no > need to initialize the whole thing (like audio/cd/joystick/etc). you could > change the "pygame.init()" call do just "pygame.display.init()" > > that should be pretty slick when you get it working. although it's been a > long time since i did anything like this. this should be all the correct info. > > oh, also remember, when you embed the SDL window like this, it will not > receive any input events. you'll need to use wxpython's event handling for > that. From igetenoughspamalreadythanksjlr at doctor.com Mon Sep 2 07:34:12 2002 From: igetenoughspamalreadythanksjlr at doctor.com (John La Rooy) Date: Mon, 02 Sep 2002 21:34:12 +1000 Subject: Problems with file.write() References: <4378fa6f.0208291457.ba738cb@posting.google.com> <4378fa6f.0208300731.18105bc7@posting.google.com> <4378fa6f.0209020824.3e658da8@posting.google.com> Message-ID: <1031009619.821203@ampungk.ozonline.com.au> Marc wrote: >>Note that all buffered data is flushed automatically when you close() >>an output file (you *are* closing the file, aren't you?). > > > Actually I wasn't closing the file originally but it had never been a > problem before. But closing the file now causes it to spill it's guts > and gives me everything I was looking for. > > However, that doesn't explain why it wasn't working in the first > place. I originally had it in unbuffered mode and wasn't getting all > my text. As I increased the buffering from 1 to 2 I kept getting more > text. But never all of it until I closed the file. It seems like it > shouldn't be necessary to flush the buffer after every write if you're > in unbuffered mode. This seems like a problem. From the docs... The optional bufsize argument specifies the file's desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size. John From bourassa-m at rmc.ca Wed Sep 25 15:02:04 2002 From: bourassa-m at rmc.ca (bourassa) Date: Wed, 25 Sep 2002 15:02:04 -0400 Subject: Scientific Python for Win32 Message-ID: <3D92082C.3050707@rmc.ca> Hi there. I'm a Python and programming newbie. I was looking for at Scientific Python esp. for its use of VRML for plotting output. Unlike many of the other Python modules I have, there are no .exe binaries. So, I have Borland C++Builder 5 on a Win2K P4. How would I compile(?) my own Scientific Python? Would it work with my Python 2.2 which I just installed from a .exe file? Any help would be appreciated. Thanks. Mike PS - I spoke with the creator of Scientific Python. He was very helpful but admits to not having expertise in this aspect, hence my question. From gerhard.haering at gmx.de Fri Sep 27 12:15:28 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 27 Sep 2002 16:15:28 GMT Subject: comp.lang.python... References: Message-ID: Vincent A. Primavera wrote in comp.lang.python: > Hello, > I've been subscribed to python-list at python.org for at least a couple of > years I would guess. I have been using a mail client to receive all of > the messages, but I figure that using a news client would be a more > organized method. However, I can't seem to find what I need to enter > for a server & user/password combination... If your ISP doesn't offer an NNTP server, you'll probably have bad luck, unless you pay for third-party NNTP access somewhere. However, there's a mail-to-news-gateway (and reverse) available at http://gmane.org/, which NNTP access for many Python mailing lists. The data you'll need are: NNTP server: news.gmane.org group name: gmane.comp.python.general No username or password required for reading. If you post, you'll need to answer a one-time confirmation message for every group. I'd still prefer to use comp.lang.python diretly. But this is quite cool for all the SIG groups, as you can read them without actually subscribing. -- Gerhard From susan at edeltech.com Thu Sep 26 13:37:40 2002 From: susan at edeltech.com (Susan Denison) Date: Thu, 26 Sep 2002 13:37:40 -0400 Subject: Please post Message-ID: <000001c26583$69cc6800$6901a8c0@SusanII> GUI Developer Boston Area Excellent salary and benefits Our client is a successful, growing enterprise software company. They are looking for a bright, versatile software engineer to develop graphical user interfaces for their product. REQUIREMENTS --4 years experience creating graphical user interfaces in VC++/MFC --Experience working on a commercial software product --Experience developing user interfaces with back-end database connectivity --Experience with operating system, kernel, and database internals, as well as multi-threading and compilers To apply please send resume to paul at edeltech.com For more information contact Paul Edelman at (508) 947-5300 Edelman & Associates is an executive search and technical recruiting firm. To see a complete listing of current positions please visit us at www.edeltech.com Susan _________________________ Susan Denison Edelman & Associates (508) 947-5300 susan at edeltech.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.net Mon Sep 2 04:13:59 2002 From: paul at boddie.net (Paul Boddie) Date: 2 Sep 2002 01:13:59 -0700 Subject: Jython and zxJDBC package References: Message-ID: <23891c90.0209020013.b05e81c@posting.google.com> billshaw+google at fastmail.fm (William Shaw) wrote in message news:... > Is anyone here using the zxJDBC package as described in "Jython > Essentials" to access a MySQL database? > > When I try to run the sample program (Example 10-1, p. 164), I receive > a NoClassDefFoundError: org/gjt/mm/mysql/Statement in > MySQLDataHandler. Decompiling MySQLDataHandler reveals an explicit > reference to org.gjt.mm.mysql.Statement; but this class isn't in the > Connector/J library. Am I missing something here? > > I'm using Jython 2.1 and Connector/J 2.0.14. It looks like MySQLDataHandler wants to use the MM.MySQL package, which can be found here: http://sourceforge.net/projects/mmmysql Note that I haven't used zxJDBC or Connector/J, whatever that is, but the above package is a fairly usable JDBC interface to MySQL, in my experience. Paul From dgallion1 at yahoo.com Wed Sep 18 22:37:15 2002 From: dgallion1 at yahoo.com (darrell) Date: Thu, 19 Sep 2002 02:37:15 GMT Subject: Regex question References: Message-ID: s="Name:AAA,BBB,CCC" print re.split(":|,", s) print re.findall("[^:,]+", s) ['Name', 'AAA', 'BBB', 'CCC'] ['Name', 'AAA', 'BBB', 'CCC'] --Darrell Eric Arnold wrote: > Hi folks, > > I'm trying to figure out why this is not working, and wonder if there are > any regexperts out there who can give me a pointer. > > The string I'm capturing is as follows: > > Name:AAA,BBB,CCC > > where I'd like to extract the following data: > > : Name > : AAA > : BBB > : CCC > > this is the regular expression I wrote to do so: > > (?.*):(?([^,]*(?=,))|((?<=,)[^,]*))+ > > I tried it with the (?<=,) as another (?=,) too, but no luck. I imagine > that the problem is that when the (?=) is used once, it can't be used with > the second group, but I don't know a way around that. > > Thanks! > > Eric From timr at probo.com Sun Sep 1 00:56:11 2002 From: timr at probo.com (Tim Roberts) Date: Sat, 31 Aug 2002 21:56:11 -0700 Subject: Crossword generator References: Message-ID: Frank Buss wrote: >Thomas Guettler wrote: > >> Has someone seen or written a crossword >> generator in python? > >Take a look at http://crosswords.50g.com/ at the bottom of the page. These are only pseudo-crosswords. Like most automatic crossword generators, it doesn't worry about symmetry, and it only crosses a few words here and there. Creating a challenging, interesting, and legitimate crossword puzzle is very, very difficult. Few humans can do it well, and it will be a while yet before they can describe their own algorithms in such a way that it can be automated. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From cstrong at arielpartners.com Mon Sep 30 11:38:09 2002 From: cstrong at arielpartners.com (Craeg K Strong) Date: Mon, 30 Sep 2002 11:38:09 -0400 Subject: Is there a way to find the name of the method currently being executed? References: <7YZl9.191322$pX1.6844789@news2.tin.it> Message-ID: <3D986FE1.9010009@arielpartners.com> Alex Martelli wrote: > Craeg K Strong wrote: >>One question: the sys._getframe() method is new for Python 2.1-- >>how likely do you think it is to change in 2.2+ >>releases? The part that worries me is that the >>method starts with an underscore. That generally means >>"protected/private" or "unpublished" to me. > > Yes, the name convention does indicate "internal". > >>I just want to know how safe it is to use for >>general business application type programming. > > Not very: it's intended to be used for debugging and > development purposes. If you can cleanly express your > application's intent WITHOUT a function needing to know > its own name, it's by far preferable to do so. If such > self-knowledge is indispensable to cleanly express your > application's intent, then sys._getframe is as usable as > any other method -- worst case, should it go away one > day, you'll have to install it in your own startup code > (code to emulate sys._getframe for old Python versions is > also available in the Cookbook, and most likely similar > code can be cooked up in the future, as long as there's > _any_ way to get such to-you-indispensable information). > > Alex > Fair enough. The functionality is not indespensible, but rather something we would like to use for debugging purposes. As such, I feel comfortable using it in limited, well defined circumstances even though it is "unpublished" functionality, as long as we put in a big fat comment. That way, when/if it breaks, we know what to do... Thanks again, --Craeg From dsavitsk at e-coli.net Wed Sep 4 12:13:22 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Wed, 04 Sep 2002 16:13:22 GMT Subject: PIDDLE install problems References: Message-ID: the answer to this from the PIDDLE Yahoo! group is to unzip and copy the contents of \src\ to the Python Path. -d "dsavitsk" wrote in message news:AT5d9.6490$yt3.3042205 at newssrv26.news.prodigy.com... > I am trying to install PIDDLE (Win2k, 2.1.3 ). I downloaded the recent .zip > file, unzipped it to C:\piddle-1.0.15, cd'd to that directory, typed "python > setup.py install" and received the following error. > > ... > copying src\piddle\python.gif -> C:\Python\piddle > Traceback (most recent call last): > File "setup.py", line 28, in ? > packages = ['piddle', 'piddle.piddleGTK', 'piddle.piddleSVG', > 'piddle.piddle > TK2'] ) > File "C:\Python\lib\distutils\core.py", line 138, in setup > dist.run_commands() > File "C:\Python\lib\distutils\dist.py", line 899, in run_commands > self.run_command(cmd) > File "C:\Python\lib\distutils\dist.py", line 919, in run_command > cmd_obj.run() > File "C:\Python\lib\distutils\command\install.py", line 484, in run > self.run_command(cmd_name) > File "C:\Python\lib\distutils\cmd.py", line 328, in run_command > self.distribution.run_command(command) > File "C:\Python\lib\distutils\dist.py", line 919, in run_command > cmd_obj.run() > File "C:\Python\lib\distutils\command\install_data.py", line 60, in run > dir = convert_path(f[0]) > File "C:\Python\lib\distutils\util.py", line 86, in convert_path > if pathname[0] == '/': > IndexError: string index out of range > > is this unusual (the same happened w/ 1.0.14), and does anyone know a way to > get around this, or why it is happening? > > thanks, > > -doug > > From wilk-spamout at flibuste.net Mon Sep 30 12:09:37 2002 From: wilk-spamout at flibuste.net (William) Date: 30 Sep 2002 18:09:37 +0200 Subject: redhat8 Message-ID: <873crr4fy6.fsf@flibuste.net> hi, anybody know wich version of python is /usr/bin/python on the new redhat release ? -- William Dod? - flibuste.net http://wikipython.tuxfamily.org From steve at ferg.org Thu Sep 12 08:28:27 2002 From: steve at ferg.org (Stephen Ferg) Date: 12 Sep 2002 05:28:27 -0700 Subject: ANN: Thinking in Tkinter References: Message-ID: > 1. You might want to point out that we can enter and experiment with > simple Tkinter scripts interactively in PythonWin or IDLE. Good idea. > I think you meant to say, 'under the name "myParent".' Yes. I'll fix that. Good catch! -- Steve From pedronis at bluewin.ch Thu Sep 5 11:30:58 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Thu, 5 Sep 2002 17:30:58 +0200 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> <3d765ce6_4@news.bluewin.ch> <3d767c4a$1_1@news.bluewin.ch> <3d774f40$1_1@news.bluewin.ch> Message-ID: <3d7779b0$1_3@news.bluewin.ch> Robin Becker wrote in message RTiVzIAJD3d9Ew2t at jessikat.demon.co.uk... > OK I get over 600 lines at the initial burst which ends with > ....... > [Loaded sun.reflect.GeneratedMethodAccessor18] > [Loaded sun.reflect.GeneratedMethodAccessor19] > [Loaded org.python.modules.MD5Object] > [Loaded reportlab.lib.fonts$py] > [Loaded java.io.RandomAccessFile from C:\Program Files\Java\j2re1.4.0_01\lib\rt.jar] > [Loaded sun.reflect.GeneratedMethodAccessor20] > > memory usage climbs continuously and then > Exception in thread "CompileThread0" java.lang.OutOfMemoryError: requested 32756 bytes > C:\jython-2.1\reportlab\test> > If I understand your report correctly, that means you get only the initial burst of [Loaded ... ] and no further [Loaded ... ] with or without [Unloading class ... ]matching the memory usage climbing? then it seems really that we are triggering some JVM bug. Have you tried with an older JVM? anyway is the code and minimal instructions to reproduce the "disaster" available ? regards. From aleax at aleax.it Sun Sep 22 17:44:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 22 Sep 2002 21:44:05 GMT Subject: sys.ps2 assignment has no effect References: Message-ID: Lance wrote: > I'm running the latest Python on Windows XP. The default installed > secondary string appears to be blank spaces rather than an ellipse. The > following has no effect: > > import sys > sys.ps2 = '... ' > > Any suggestions? Is this with the text-mode interactive Python (which would surprise me, as I've run the latest Python on XP w/o such problems), or with IDLE or other such IDE? IDLE does not use PS2, afaik (it always uses spaces instead) and other IDEs might do likewise. Alex From glingl at aon.at Mon Sep 30 16:08:11 2002 From: glingl at aon.at (Gregor Lingl) Date: Mon, 30 Sep 2002 22:08:11 +0200 Subject: Canvas.py obsolete - why? Message-ID: <3D98AF2B.6010901@aon.at> Hello! In the Standard Python distribution with Tkinter there is contained the module Canvas.py which among other things exports class definitions for several geometrical objects as lines, rectangles, arcs etc. This module starts with the following comment: # NOTE: This module was an experiment and is now obsolete. # It's best to use the Tkinter.Canvas class directly. Does anyone know, *why* this module is declared obsolete? (I consider it pretty useful.) Gregor Lingl From tjreedy at udel.edu Sun Sep 15 17:56:48 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Sep 2002 21:56:48 GMT Subject: python performance References: <3D84E66F.6020701@linux.ie> Message-ID: "Padraig Brady" wrote in message news:3D84E66F.6020701 at linux.ie... > I was wondering about the performance characteristics > of python and ran a simple test. The 2 programs > below are functionally equivalent and just read > in fields into a list. file.fields contains > 720 fields in each of 405 lines of the form of > repeating: oneoneone twotwo "thre e three" > > The time to run is shown above each program > from which I've inferred the following: > > 1. The function call version is (6.3%) faster because > the cumulative cost of parsing the simpler expressions > and function call overhead is smaller than parsing the > 1 single complex expression? Calling functions adds overhead. Running code within functions reduces overhead for object access. See end for third version to test. > Or the function is parsed > only once and doesn't have to be reparsed. This would > suggest that top level code is parsed for each iteration? No. All code is parsed only once. See above and below. > 2. Anyway I thought that parsing affects would be removed by doing the > parsing only once, i.e. compiling the code to .pyc (I used > py_compile.compile()). However this makes no difference at all? > Surely compiling is not just for code obfuscation. No. The one-time parsing of 10 lines of code is extremely fast. If it were parsed over again for each line, then you would notice the parsing time. > Note I did do the test several times and averaged the results. > ---------------------------- > 2.514s > ---------------------------- > #!/usr/bin/env python2.2 > import re > > reFieldFinder = re.compile('[^ "]+|"[^"]+"') #unquoted|quoted > def getFields(line): > fields = reFieldFinder.findall(line) > return [field.replace('"', '') for field in fields] > > for line in open("file.fields").readlines(): > listLine = getFields(line[:-1]) > > ---------------------------- > 2.672s > ---------------------------- > #!/usr/bin/env python2.2 > import re > > reFieldFinder = re.compile('[^ "]+|"[^"]+"') #unquoted|quoted > for line in open("file.fields").readlines(): > listLine = [field.replace('"', '') for field in > reFieldFinder.findall(line[:-1])] Try one more test to run at function speed without repeated getsfields(): def mytest: reFieldFinder = re.compile('[^ "]+|"[^"]+"') #unquoted|quoted for line in open("file.fields").readlines(): listLine = [field.replace('"', '') for field in reFieldFinder.findall(line[:-1])] mytest() Terry J. Reedy From tibor.simko at cern.ch Tue Sep 24 10:50:03 2002 From: tibor.simko at cern.ch (Tibor Simko) Date: Tue, 24 Sep 2002 16:50:03 +0200 Subject: Getting started References: <0%Aj9.129252$ub2.2813083@news1.tin.it> Message-ID: <877khb7884.fsf@pcdh91.cern.ch> Hello On Mon, 23 Sep 2002, Alex Martelli wrote: > as far as I know, the CAML dialect of ML (also in the O'Caml > extension, last I looked) is one of the very few programming > languages that doesn't have a polymorphic + operator -- you have to > use + for integers only, +. for floating-point. There is a good reason why OCaml does not overload the + operator: type inferring. In OCaml you do not need to declare variables explicitly in the program because OCaml infers types for you. However, this does not match well with operator overloading, since the compiler would not understand whether "a + b" stands for float or integer. Unlike SML, OCaml decided to avoid this kind of type inferring problem by not overloading the + operator. T. From jb at cascade-sys.com Tue Sep 17 04:14:30 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Tue, 17 Sep 2002 01:14:30 -0700 Subject: More on Protecting Source Code References: <20020917062412.GA85457@hishome.net> Message-ID: <3D86E466.6010208@cascade-sys.com> Oren Tirosh wrote: >Yes, there are narrow-minded people on both sides of the intellectual >property debate. > Reasonable statement. >I don't think that software 'ought' to be this or 'ought' to be that. In >other words, I believe in freedom. > Reasonable statement. >I don't think anyone would disagree with that. > Reasonable statement. >The disagreement seems to >be whether information is property or not. > Wow. I didn't hear anybody say this (though, sadly, perhaps this is the real agenda). >By its nature it isn't > Wow. An even more amazing statement. Information BY IT'S VERY NATURE is not property. How the hell do you figure? You saying the thoughts in my head are public domain? I certainly hope not. Or if I reduce those thoughts to paper or to software or to wood and metal that somehow everybody else is entitled to share the benefits of my possibly substantial endeavor? What a load of bullshit. An artist who creates an image or the specifications for a musical performance has every right to own his creation and benefit from its use. This is no different for a programmer and code of his own creation. Even if you go back to the early industrial age, key products of industry was intellectual property. E.g., engineers had to produce drawings and written specifications before they could build a bridge or a mousetrap. That "information" was every bit their property as the more tangible artifacts they later sold commercially. An unscrupulous competitor could use the IP to recreate the commercial artifacts at a fraction of the original owner's cost. Or he could reverse engineer the IP and again enjoy an unfair advantage. That's blatantly unfair and it's a good thing we have laws to protect against such theft. Now if somebody elects to give away their IP -- out of charity or in hope of scoring points in some circles -- that's fine. But if he instead elects to profit from it, in a free world, that should be perfectly reasonable and respectable also. >but it >can be made more property-like by laws that restrict people's freedom to >use information. > Copyright laws have precedent dating back to pre colonial England. Interesting new books and music were intrinsically hard to create but, (after Gutenberg) once created, they were easy for the unscrupulous to copy and receive full benefit of their publication. Robbing the creators the fruits of of their labor is inherently unfair. Not only does the IP thief unfairly benefit from work he did not perform he also robs the real owner of income he otherwise would have received. Thus IP laws naturally evolved to protect rightful property owners. It's meet and good. People fought and died (and more importantly prevailed) in defense of the rights to be free and to own property. Now I don't necessarily support some of the more recent changes and extensions to copyright laws. Some maybe go a step too far. However, I don't think they can or should be rejected altogether. At their core they're not arbitrary; rather in protecting the works' creators they're the epitome of fairness. >The state has given you the 'right' to use the power of its court and >police to forcibly restrict people that use information you have created >in violation of copy-restriction laws. > Yeah, sure, in your dreams we could instead have laws that say all information was free. I submit that such a situation would actually stifle innovation. Sure a few dreamers would still invent but the volume and time to market would be greatly diminished. Lack of ownership is precisely why most socialist countries soon became and forever remained vast economic wastelands. Denying individuals any incentive for working harder than others, the economy soon deteriorates to where it can hardly provide the necessities of life let alone invent clever and innovative luxuries. Worse, collectivist economics are unnatural in that they fly in the face of most human instincts. Thus it requires a large and oppressive government to enforce collectivism and, in practice, those governments typically become corrupt. In any case, economies invariably, immediately revert to capitalism soon as the communist/socialist oppression ceases. It is precisely the promise of commercial reward that makes America the incredible fount of invention and creativity that it is. The simple formula of rewarding people for their own hard work is what made America the worlds only superpower. Not only do we have the most powerful military in the world our people also enjoy one of the world's highest standards of living. Most socialist countries have had to choose one or the other or don't have the choice of either. I just don't get you folks who push this Communistic view of economics. It's childish. Marx sounded good on paper 100 years ago and yeah we all believed it when we were idealistic teenagers. At the cost of hundreds of millions of citizens (murdered by their own government) and a significant fraction of the 20th century's world's human resources, we gave Communism every chance to succeed. After almost a century of experimentation with collectivist economics, the results are all in and the bottom line is that it simply doesn't work. The net cost to The People in the long run is always greater than the net benefits. If you don't understand this then you really haven't been paying attention to recent world history. The problem with Capitalism is that not everyone shares equally in the wealth. The problem with Communism is that everybody DOES share equally in the misery. I prefer Capitalism. >But that is not enough for you. You also want the 'right' to complain about >something that was given to you freely and expect that righteous rants >about your view of intellectual property laws will somehow compel people >to modify it to your specification without compensation. > You're being unfair. Mr. LeBlanc was not complaining about anything that I could see. He was merely describing a tangible shortcoming of Python (one which launched this entire thread) that restricts its use for some purposes. He further, humbly suggests how it might be made a little more useful to commercial users. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From teaandbikkie at aol.com Sat Sep 7 09:52:11 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 07 Sep 2002 13:52:11 GMT Subject: Thinking of joining References: <3D7970DC.5115BCC8@earthlink.net> Message-ID: <20020907095211.24938.00000006@mb-mt.aol.com> IMHO Python has beautiful plumage, isn't nailed to the perch, and won't leave you pining for the fields. It also has a good range of cheese, even the ones you thought you didn't need, and you won't get stoned by your friends for joining. (Any implied references to Parrot are completely accidental). I'm too new to Python to give you good technical reasons to use it, but I like it :) From duncan at NOSPAMrcp.co.uk Wed Sep 11 12:03:59 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 11 Sep 2002 16:03:59 +0000 (UTC) Subject: deleting the first and the last character of a string References: <20020911105818.GC2054@partagas.as.de.cw.net> Message-ID: Sean 'Shaleh' Perry wrote in news:mailman.1031756234.22942.python-list at python.org: > On Wednesday 11 September 2002 03:58, Manuel Hendel wrote: >> I got a file with fields seperated by a "|". The problem is that there >> is also a "|" at the beginning and at the end of each line although >> there no fields in front or behind these "|". Now I want to delete >> these two "|". Is there anything which says delete the first or last >> character of a string? I checked the string module on the web, but I >> couldn't find anything. >> > >>>> s = '|f|o|o|' >>>> s.strip('|') > 'f|o|o' > > and of course the equivalent strip call from the string module. > This doesn't work on Python 2.2.1 (or earlier), I think you need to be sitting astride the cutting edge of CVS development to do this. Specifically the change to implement this was April 22nd and 2.2.1 was released April 10th. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From tismer at tismer.com Sun Sep 15 15:50:06 2002 From: tismer at tismer.com (Christian Tismer) Date: Sun, 15 Sep 2002 21:50:06 +0200 Subject: Ann: Stackless Python Update Message-ID: <3D84E46E.4020704@tismer.com> Hi Stackless users, A new version of Stackless Python is available. Changes: Stackless now supports Sun Sparc, thanks to Gerd Woetzel. The other platforms are Windows, Linux X86, Mac PPC, Cygwin. The core stack switching mechanism and the extended stackless module are now split apart. The stackless module is built as an extension and loaded on demand. The type system has been reworked. As an effect, all methods on channels and tasklets can now be re-defined from Python, without extra cost for the native implementation. I am going to propose this as a Python extension as well. Win32 binaries can be found on the website http://www.stackless.com/ For all other supported platforms you need to get the source from CVS and build it. More to come, soon - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From manuel at hendel.net Thu Sep 19 03:47:26 2002 From: manuel at hendel.net (Manuel Hendel) Date: Thu, 19 Sep 2002 09:47:26 +0200 Subject: lists in dictonaries ? Message-ID: <20020919074722.GB77021@partagas.as.de.cw.net> Is it possible to put lists in dictionaries? And is it also possible to put multiple lists in a dictionary for one key? Thanks, Manuel -- I married beneath me. All women do. -Lady Nancy Astor, first woman member of the British Parliment From tismer at tismer.com Mon Sep 2 17:11:45 2002 From: tismer at tismer.com (Christian Tismer) Date: Mon, 02 Sep 2002 23:11:45 +0200 Subject: New Stackless Beta Message-ID: <3D73D411.80205@tismer.com> Hi friends, a new beta of Stackless Python is released. The source is at the moment available via public CVS, only. PC binaries and how to access CVS can be found at http://www.stackless.com What's new? Tasklet flags have been re-worked a lot. They should be always updated correctly, now. The schedule() protocol has changed very much, internally. This made it possible to write a tasklet.raise_exception which works in any context, while waiting in a channel or being currently run. Very soon to come: tasklet.kill(), implemented by raise_exception. But there is one feature missing for a clean kill(): Tasklets will get notifiers, which make it possible to ask for an event like "tell me when this tasklet has died". Together with notifiers, waiting on a set of channels will be implemented, soon, in a very effective manner. Also in preparation: "A practical guide to Stackless Python", written by me. It will contain general information and a number of examples, like "how to make wxPython stackless" and more. watch out - ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From jcc at ibdosnorte.com Mon Sep 23 11:00:15 2002 From: jcc at ibdosnorte.com (=?ISO-8859-1?Q?Juan_Carlos_CORU=D1A?=) Date: 23 Sep 2002 08:00:15 -0700 Subject: COM: Returning IDispatch or NULL Message-ID: Hello, I'm trying to develop a COM Server in python, that has a method that returns an IDispatch object but sometimes it must return nothing. See the following example programmed in C/SIDE (Microsoft Navision Financials ERP): ---> otherCOMServer := COMServer.returnOtherCOMServer(); IF ISCLEAR(otherCOMServer) THEN MESSAGE('otherCOMServer is clear'); <---- Definition of ISCLEAR (extracted from MS Navision help): The return value is TRUE if: -the automation variable has not been created. See CREATE. -the automation variable has been cleared. See CLEAR. -the automation variable has been assigned NULL by an automation server. I thing that in this case I must assign NULL to the otherCOMServer variable in order to keep the otherCOMServer variable CLEARED. What must I return from "COMServer.returnOtherCOMServer()" method to assign NULL? I have tried: return None return wrap(None) return 1==0 return but without success. The environment responds "data type not supported". I know that other COM servers developed by Microsoft Navision works this way. Thanks in advance. From nospam_t.roessler at v-d.com Thu Sep 26 09:19:35 2002 From: nospam_t.roessler at v-d.com (Thilo =?ISO-8859-15?Q?R=F6=DFler?=) Date: Thu, 26 Sep 2002 15:19:35 +0200 Subject: Zope, MySQL and pictures in blob-fields ... References: Message-ID: I'm sorry ... > This is crossposting. Please subscribe to the Zope maillist at > zope at zope.org and post this there. From sholden at holdenweb.com Wed Sep 11 04:56:18 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 11 Sep 2002 04:56:18 -0400 Subject: blocking socket dilemma References: <3d7f046f$0$230$4d4ebb8e@news.nl.uu.net> Message-ID: "Gumuz" wrote ... > Hi all, > > I am a little bit stuck with my design (again!). > > I have this server class, which creates a session object for every accepted > incoming connection. The session object has a RequestHandler function which > is then run in a new thread. > > all fine, but... > > This RequestHandler function actually does a infinite loop. The loop wil > receive data and take some action and it will send data which is piled up in > this session's queue. The problem that i'm having is that the loop will hang > on socket.recv if the client is not sending anything. Ofcourse this is very > obvious and logical, but i can't think of another way of constructing my > design, so that this problem doesn't occur. > > I hope i've made my problem clear to you guys. > You may be ready to migrate to an asyncore-based solution. In such situations it's usually easier to adopt a more flexible program structure. Asyncore/asynchat my be just what you need. They certainly put a muc more direct emphasis on the buffering required in a TCP session. The SocketServer-based modules are sufficient for simple interactions, but don't hack it when a "Request" becomes a series of interactions over the same socket, for example like a Telnet session. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From jhorneman at pobox.com Sun Sep 29 17:26:53 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: Sun, 29 Sep 2002 23:26:53 +0200 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <874rc8d9c9.fsf@nospam.eml.cc> Message-ID: <3d976fbc$0$23666$91cee783@newsreader02.highway.telekom.at> "Gerhard H?ring" wrote in message news:mailman.1033319977.7828.python-list at python.org... > * Mahesh Padmanabhan [2002-09-29 16:55 +0000]: > > You need to create an empty file called __init__.py inside the > > template directory and call the blah.py script as follows: > > > > import template.blah > > It's also highly recommended to start Python with "python -vv", then > trying to import the module in question. This will show you where Python > tries to find the module. Actually, I just tried this in a DOS shell under Windows 98: python -v script.py >output.txt It lists the verbose output straight to the DOS shell, not to output.txt. The output is useless, I can't scroll back. Oddly, python -h >output.txt correctly sends the output to output.txt. Does anybody know if this is a bug, and how I can work around it? Jurie. From drfransch at netscape.net Sun Sep 15 18:53:43 2002 From: drfransch at netscape.net (F. Schaefer) Date: 15 Sep 2002 15:53:43 -0700 Subject: Command Line Parsing etc. (GetPot 1.0) Message-ID: Finally after one year on sourceforge, the Version 1.0 of the command line and configuration parser GetPot is ready for download. Some new features are: -- the dollar bracket language: A simple lisp-like extension, so that basic string, and arithmetic operations can be performed on the command line and inside a configuration file. -- unidentified flying object detection (UFO detection): sophisticated functions to detect unrecognized arguments, options, flags and variables. -- prefixes: narrow down search space through a 'prefix' (section name). A reviewed user manual documents all these features. Please feel free to download at: http://getpot.sourceforge.net Many people sent me suggestions and improvements, so I think we finally have a pretty useful/stable tool. However, I'm still glad about any comment/critique. Best Regards, Frank. From pecora at anvil.nrl.navy.mil Mon Sep 30 09:26:01 2002 From: pecora at anvil.nrl.navy.mil (Louis M. Pecora) Date: Mon, 30 Sep 2002 09:26:01 -0400 Subject: [Mac] Editor on Macintosh? References: <1fj7za2.1erbqps1uvzpj8N%news@agapow.net> Message-ID: <300920020926012729%pecora@anvil.nrl.navy.mil> In article , Russell E. Owen wrote: > Python has the Mac IDE is a bit limited (need an extra plug-in even to > do syntax coloring) What Plug-in works for the Python IDE? -- Lou Pecora - My views are my own. From emile at fenx.com Tue Sep 17 09:34:33 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 17 Sep 2002 06:34:33 -0700 Subject: how to cast an instance id References: <3D86E888.90AF569@millfilm.co.uk> Message-ID: Eric Texier: > It there a way to create a new reference of an object > from the string representation of its id? > Thanks for any help. > > class foo: > def info(self): > print self > > a = foo() > a.info() > ccc = "newa = 0x%x" % id(a) > exec(ccc) > There are ways of walking the object hierarchy checking ids, eg: ccc = id(a) for ii in locals().values(): if id(ii) == ccc: ccc = ii break Or, you can set things up specifically to support this if you know in advance: class foo(object): objlist = {} def __init__(self): foo.objlist[id(self)] = self def info(self): print self a = foo() ccc = id(a) ccc = foo.objlist[ccc] print ccc That said, there's probably a better way, ie, setting ccc to a instead of the id of a in the first place. Otherwise, you risk retaining ccc when a could have been refcounted away. -- Emile van Sebille emile at fenx.com --------- From skip at pobox.com Fri Sep 13 14:20:38 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 13 Sep 2002 13:20:38 -0500 Subject: transform list of int in a list of string?? In-Reply-To: <-1483717605.1031940885180.JavaMail.nobody@webmail2.brturbo.com> References: <-1483717605.1031940885180.JavaMail.nobody@webmail2.brturbo.com> Message-ID: <15746.11382.851521.129722@12-248-11-90.client.attbi.com> juliano> How can i transform a list of integer numbers in a list of juliano> string numbers, like that: juliano> x=[1,2,3,4] to y=['1', '2'...]???????? Try y = map(str, x) or y = [int(n) for n in x] -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From mstenner at phy.duke.edu Thu Sep 12 21:33:53 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Thu, 12 Sep 2002 21:33:53 -0400 Subject: Coding Style: Quotes In-Reply-To: ; from bobx@linuxmail.org on Fri, Sep 13, 2002 at 01:14:21AM +0000 References: Message-ID: <20020912213353.A8007@phy.duke.edu> On Fri, Sep 13, 2002 at 01:14:21AM +0000, Bob X wrote: > Michael Stenner wrote: > > > Since there is no "physical" difference between them, I can't imagine > > why it would matter. The only reason there "needs" to be two is for > > nested quoting. Sure, it would be annoying to alternate for each > > string, but beyond that... > Don't you have to escape a single quote within a single quote whereas > you do not while using a double quote? > > i.e. 'It\'s raining' "It's raining" Yes. But they are identical in that the reverse is also true. For example: "It\"s raining" 'It"s raining' I know it's incorrect english grammar, but that's not really relevant here. This is in contrast to languages where the single and double quotes have fundamentally different roles. For example, in c, "s" and 's' are radically different. In perl, "$_" and '$_' are again very different. -Michael P.S. As a matter of style, I'm sure most of us would agree that "It's raining" is preferable to 'It\'s raining', just as 'she said "wait"' is preferable to "she said \"what\"". -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From duncan at NOSPAMrcp.co.uk Wed Sep 11 04:13:24 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 11 Sep 2002 08:13:24 +0000 (UTC) Subject: dynamism References: <66715c02.0209091923.265fe77e@posting.google.com> <3d7e209a_1@news.iprimus.com.au> Message-ID: "Steven Shaw" wrote in news:3d7e209a_1 at news.iprimus.com.au: > Does this mean that the attributes are stored in a more efficient way? > > Is there a way to implement "record-based" object layout rather than > "associative-array based" object layout? > > It very much depends what you mean by 'more efficient'. Using object- derived classes and __slots__ means that each class no longer has the overhead of creating a dictionary for the instance attributes, so you are saving the memory overhead of the dictionary. On the other hand, object- derived classes seem to be slower to create, and setting attributes defined in object-derived classes is also slower than setting attributes in old- style classes (although setting __slots__ attributes seems to be faster than setting other attributes). The code below gives these timings on my machine: 3.84s: 1000000 x New() 3.89s: 1000000 x New2() 2.39s: 1000000 x Old() 5.19s: 10000 x attributes() 5.81s: 10000 x attributes() 4.17s: 10000 x attributes(__main__.Old) -------------------------------- class Old: pass class New(object): __slots__ = ['a', 'b', 'c', 'd'] # New-style, but not using slots. class New2(object): pass def timeit(repeat, fn, *args, **kw): import time start = time.time() for i in xrange(repeat): fn(*args, **kw) end = time.time() # Format arguments for printout argstring = ', '.join( [str(a) for a in args] + [ '%s=%s' % (k, v) for k, v in kw.items()]) if len(argstring) > 60: argstring = argstring[:57] + '...' print "%.2fs: %d x %s(%s)" % ((end-start), repeat, fn.__name__, argstring) def attributes(klass): inst = klass() inst.a = 1 for i in range(100): inst.b = inst.a+1 inst.c = inst.a+2 inst.d = inst.a+4 inst.a += 5 timeit(1000000, New) timeit(1000000, New2) timeit(1000000, Old) timeit(10000, attributes, New) timeit(10000, attributes, New2) timeit(10000, attributes, Old) -------------------------------- -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From aurin42 at yahoo.com Tue Sep 3 04:26:54 2002 From: aurin42 at yahoo.com (Ante Bagaric) Date: Tue, 3 Sep 2002 10:26:54 +0200 Subject: A "for" with "list" question. References: <3b55ea60.0208311330.4608ae71@posting.google.com> Message-ID: > >>> [item for item in a if item in b] > [1, 2] > > That third line is a list comprehension. >>> a = [0, 1, 2] >>> b = [1, 2, 3] >>> [i for i in a if i in b] + [i for i in a + b if i not in a or i not in b] [1, 2, 0, 3] :) From a_salnikov at yahoo.com Sat Sep 14 16:33:58 2002 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Sat, 14 Sep 2002 13:33:58 -0700 Subject: Anyone can tell me why? References: <1815200.1031973626@dbforums.com> Message-ID: "hpyhpy" wrote in message news:1815200.1031973626 at dbforums.com... > > hi,everybody: > > I'm puzzled about SWIG. > > [..........................] > > Then it has these files: > example.c > example.i > example.o > example_wrap.c > example_wrap.doc > example_wrap.o > _examplecmodule.so > > So I wonder where is the "example.py"??? > So I can't "import example" > The module 'example' is in the shared library (.so). But python has to find this shared lib somehow, I mean you cannot give it some random name and hope it will be found. Try to rename _examplecmodule.so to example.so, import should work then. Andy. From igetenoughspamalreadythanksjlr at doctor.com Mon Sep 2 07:10:39 2002 From: igetenoughspamalreadythanksjlr at doctor.com (John La Rooy) Date: Mon, 02 Sep 2002 21:10:39 +1000 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: <1031008206.347446@ampungk.ozonline.com.au> Bengt Richter wrote: > > I agree about new syntax, but I wouldn't mind having a re.help(regexp) function > for interactive use that would just explain in 'English' what the regexp expression > stands for. It would be a nice easy double check on whether I wrote what I meant, > and helpful for understanding someone else's magic. It shouldn't be that hard to do. > > Regards, > Bengt Richter I think that's an excellent idea (probably has already been done, anybody know?) It is unfortunate that often a re that starts off as a simple idea turns out to be a big mess. I think some sort of graphical tool would be even better so you could see what the re does. Especially if it could convert both ways and allow you to edit the re. John From anguenotj at yahoo.fr Thu Sep 19 03:26:23 2002 From: anguenotj at yahoo.fr (Julien Anguenot) Date: Thu, 19 Sep 2002 10:26:23 +0300 Subject: Code analyser + testing Message-ID: <3D897C1F.3070405@yahoo.fr> Hi !, I'm looking for a code analyser for Python 2.2. I found one dated from 1997 (pylint.py) from Ka-Ping Yee but It seems it doesn't work with the version 2.2.... Knows someone where I can find one up to date ? I'm student and I have to find a software (in Python of course) for setting tests. (unit testing, etc....) It's for a course I took this year. I will do it with an other developper. If you've a software and you're interested to have some testcases you can write me an email. What I need with the software : ** the software of course ** It must be long around 5000 loc ** the specifications in details Thanks Regards, /JA -- Julien ANGUENOT Keskisenkatu 6 B 11 33710 Tampere FINLAND Mail : anguenotj at yahoo.fr ; Web : http://www.anguenot.net Tel : +358 (0) 41 576 8888 Download and try Zope at http://www.zope.org. Zope is a leading open source application server. From self at meyarivan.org Wed Sep 4 10:45:42 2002 From: self at meyarivan.org (T.Meyarivan) Date: 04 Sep 2002 20:15:42 +0530 Subject: efficient list merging In-Reply-To: References: Message-ID: <1031150751.2615.40.camel@tass1.localdomain> > Here's an example: > > lol1 = [['a'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j']] > lol2 = [['d', 'e', 'f'], ['k', 'l', 'm'], ['d'], ['f', 'g'], ['a']] > > I want a function which returns > > mergelol = [['a'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', > 'j'], ['k', 'l', 'm'], ['d']] # lista and listb are the lists of lists def merge(lista, listb): x = {} map(x.setdefault, map(tuple, lista + listb)) return x.keys() From see_reply_address at something.invalid Tue Sep 24 23:19:30 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 25 Sep 2002 15:19:30 +1200 Subject: confusion about opening files References: Message-ID: <3D912B42.8010703@something.invalid> > Flush, and unbuffered files, ASK the OS to please, please write the > data out -- but not all OS's comply. Even on Unix, I'm not sure that flush() ensures that the data is physically written to the disk. The Linux man page for fflush(3) says: NOTES Note that fflush only flushes the user space buffers pro? vided by the C library. To ensure that the data is physi? cally stored on disk the kernel buffers must be flushed too, e.g. with sync(2) or fsync(2). -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tim.one at comcast.net Thu Sep 26 11:39:04 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 26 Sep 2002 11:39:04 -0400 Subject: Python threading? In-Reply-To: Message-ID: [Robert Oschler] > Having written _many_ state machines in my life, which async programming > boils down to in one form or another, I feel it depends on the task. > ... > Contrast this with a simple procedure call where a linear series of > function calls are made, each with appropriate error handling and status > adjustment, in a pleasant centrally located manner. [Thomas Heller] > I wonder if generators can come to a rescue here? Absolutely. Read the start of PEP 255. > Still trying to get them into my head... Think of them as resumable functions. You're familiar with functions that remember their own data state across calls, via abusing globals, or via declaring private static vrbls, in C. Methods on objects often do the same by stuffing their state into instance attributes between calls. A generator remembers its data state across resumptions simply by virtue of that its local variables don't vanish, and also remembers its control-flow state across resumptions. Remembering local data state by magic is a real convenience, but can be simulated in many other ways with reasonable effort; it's the ability to remember and restore control-flow state by magic that can make generators more than merely convenient. From Pekka.Pessi at nokia.com Wed Sep 18 01:20:31 2002 From: Pekka.Pessi at nokia.com (Pekka Pessi) Date: 18 Sep 2002 08:20:31 +0300 Subject: Detecting IPv6 support References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: loewis at informatik.hu-berlin.de (Martin v. L?wis) writes: >At the moment, you need CVS Python, and VC.NET, to get IPv6 suport on >Windows. This then works both with the released XP, and the MS >research IPv6 stack. Thanks. >> What is the recommended method of finding out if Python and >> the underlying OS support IPv6? I can, for instance, create an >> IPv6 socket with a Python version that does *not* support >> IPv6. >What system is this? If you can create an IPv6 socket, why does it not >support IPv6 (i.e. how do you know it does not support IPv6)? If you >do .listen(), .getsockname() on that socket, what does it tell you? I have Redhat 7.3. The prepackaged RPMs have disabled IPv6, but the underlying OS supports it. So, this is what happens with the bind() system call, for instance: Python 2.2.1 (#1, Jul 15 2002, 10:55:56) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import socket as so >>> s = so.socket(so.AF_INET6, so.SOCK_DGRAM) >>> s.bind(("", 0)) Traceback (most recent call last): File "", line 1, in ? socket.error: getsockaddrarg: bad family >>> So AF_INET6 is there, and I can create a socket, but everything dealing with addresses fails. Pekka From gerhard.haering at gmx.de Fri Sep 27 16:31:19 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Fri, 27 Sep 2002 22:31:19 +0200 Subject: Better terminal for windows? In-Reply-To: <3D94B037.2020202@motorola.com> References: <3D94B037.2020202@motorola.com> Message-ID: <20020927203119.GA6919@lilith.ghaering.test> * Stephen Boulet [2002-09-27 14:23 -0500]: > I'm using python 2.2.1 on winnt. > > If I want to run python interactively (and perhaps using ipython), is > there something better than the "cmd" terminal? Well, you could install MSYS from the mingw project, which is sort of a Cygwin-lite :-) > I'm used to bash on linux at home, but I'd like to avoid installing > cigwin for now. Thanks. cmd.exe isn't *that* bad once you activate tab completion in the registry. Have you done that? 4NT is also great, but it's shareware. -- Gerhard From bobx at linuxmail.org Tue Sep 17 19:47:28 2002 From: bobx at linuxmail.org (Bob X) Date: Tue, 17 Sep 2002 23:47:28 GMT Subject: Python equivalent to perldoc? References: <%Avh9.7933$Lg2.1392332@news2.news.adelphia.net> Message-ID: "Thorsten Kampe" wrote in message news:am7sna$3emja$2 at ID-77524.news.dfncis.de... > Tough Yeah aint it though... > > Shouldn't Python know its own libs? > > It does: > ,--- > | Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 > | Type "help", "copyright", "credits" or "license" for more information. > | >>> import pydoc > | >>> > `--- It doesn't...you are executing from with Python...I am trying to do a ViM script that executes it. > > Or at least put the "libs" in the ENV variable? > > Windows XP doesn't have a ENV variable. Lets see...right click "My Computer"...go to the "Advanced" tab....OH LOOKY a button that says "Environment Variables". I could have been a wee bit more specific like...putting the the lib dir in the PATH. sorry-xp-does-have-an-env-variably-yours, Bpb From marklists at mceahern.com Mon Sep 16 10:34:14 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 16 Sep 2002 09:34:14 -0500 Subject: getting username from uid In-Reply-To: Message-ID: > when I do a stat on a file I can get the UID of the owner. IS there > anyway to get from UID to username (or directly to username for that > matter)? import pwd user = pwd.getpwuid(uid) # user is a tuple print user[0] // m - From daniel.dittmar at sap.com Thu Sep 12 09:57:28 2002 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Thu, 12 Sep 2002 15:57:28 +0200 Subject: DB Cursor iterator (was: [ANN] PySQLite 0.3.0 released) References: Message-ID: Terry Reedy wrote: > Does anyone know whether there are any plans to update the Python-DB > API to the new iterator protocols, so that the above could be written > more simply something like > > for row in cursor: > print "%14s, %15s, %19s, %8s, %25s" % tuple(row) It's already in the 'Optional DB API Extensions' in http://www.python.org/peps/pep-0249.html Daniel From gupsmail at ihatespam.shaw.ca Wed Sep 25 10:30:50 2002 From: gupsmail at ihatespam.shaw.ca (Grant Hallam) Date: Wed, 25 Sep 2002 14:30:50 GMT Subject: problem with dictionaries within lists References: Message-ID: The problem with blanking out the dictionary with dict{} is that it wipes the keys out. As the loop goes through it assigns the matching second half of the list to a matching key. If you insert a print statement on the dict you can see the values in the dict are changing. Thus while it is the same dict the key values within the dict are different. Thats why I'm somewhat confused as to why its the same dic value. As for the tabs, I'll have the editor replace them with 4 spaces. Didn't notice the problem in PAN :) On Wed, 25 Sep 2002 02:11:14 -0700, Alex Martelli wrote: > Grant Hallam wrote: > ... >> However, the list seems to get populated with the same dictionary > ... >> webdatabaselist.append(dict) > > Of course -- you ARE appending the same dict over ands over (AFAICT -- > you're probably using tabs for indentation, making your code hard to > comprehend for those who read news with KDE's KNode [or MS's OE] as tabs > don't show there... use spaces, NOT tabs...). > > Anyway, you probably need something like: > > webdatabaselist.append(dict.copy()) > dict = {} > > either might suffice, but generally you'll need to copy the current dict > AND make dict empty for the next leg of the loop, if I get the general > drift. If you do rebind name dict to {} for the next leg, then you > don't need the call to the copy method. > > > Alex From wayne at tbnets.com Sun Sep 8 01:47:12 2002 From: wayne at tbnets.com (Wayne R) Date: Sun, 8 Sep 2002 01:47:12 -0400 Subject: python program to watch a file - example. Message-ID: <003801c256fb$3fdcf320$02010a0a@hackncodexp> I am trying to write a python program that will run as a deamon and watch a file for data to arrive and then wake up and perform duties on that data. I found ways to make a python program run as a deamon but I am at a loss to find anything related to watching a file for data so that it can then process the data. I didn't really want to do a sleep loop or something like, I am sure there is a better way. Any ideas or links to more info? Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From tmohr at s.netic.de Sun Sep 15 14:31:24 2002 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 15 Sep 2002 20:31:24 +0200 Subject: Tkinter in PyRun_SimpleString(char* s) References: <_OWg9.109539$pX1.3874894@news2.tin.it> Message-ID: Hi, > ...which needs to be called AFTER Py_Initialize -- I think that > may be your problem: yes, exactly. Thank you very much for that hint. Regards, Torsten. From nmichael at yahoo.com Mon Sep 9 14:19:07 2002 From: nmichael at yahoo.com (Neophytos Michael) Date: 9 Sep 2002 11:19:07 -0700 Subject: Computing directory sizes problem References: Message-ID: loewis at informatik.hu-berlin.de (Martin v. L?wis wrote in message news:... > nmichael at yahoo.com (Neophytos Michael) writes: > > > Dear Python experts, > > I wrote the following function to compute the size of a directory > > (being new to python there maybe better ways to do this - if so please > > advice). It works quite well except when the directory in question > > contains files whose names that are not made up of ascii (english) > > characters (this typically happens on my machine for my non-english > > mp3 files). > > What Python version are you using? What localized Windows version? > What are the file names in question? > > If the file names are non-ASCII, it should still work - provided the > file names are supported in the system locale (i.e. ANSI code page). > > It might be easiest to adjust your system locale. > > Regards, > Martin Dear Martin, Python version is 2.2.1. Windows localized version I am not sure. The laptop was purchased in the US so it must be the defaul US version. The filenames in question are mp3 files whose names are made up from greek characters (at least I see them as greek when listing the files with file explorer). Any advice on how to adjust my system locale would be appreciated. Thanks, Neophytos From mark at mceahern.com Mon Sep 30 15:38:43 2002 From: mark at mceahern.com (Mark McEahern) Date: Mon, 30 Sep 2002 14:38:43 -0500 Subject: a question about mailman Message-ID: I have a question about Mailman that was never answered when posting to the Mailman list: http://mail.python.org/pipermail/mailman-users/2002-September/022538.html I'm in the awkward position of having this question even though I don't personally have Mailman installed (yet). Since Mailman is written in Python, I thought I'd use the occasion of this week's Dr. Dobb's Python-URL (DDPU) to illustrate the use case I envision that is at the heart of my question about Mailman. If you examine this week's DDPU (below), you'll see Cameron provides very useful references to the Python mailist list when he references a thread that happened on comp.lang.python. (I've also seen contributors of DDPU alternatively provide a link to the thread at http://groups.google.com/, which is also very useful.) What I imagine Cameron had to do was navigate to the archive page for the Python mailing list and, by-hand, find the URL for each thread/message he wanted to reference. In that context, I wonder, "Wouldn't it be easier if you could configure Mailman to insert the archive URL into the footer of outgoing messages?" I took a peek at the Mailman code base and it seems like this could be done, but it would require hacking the Dispatch (correct name?) module since when it uses string formatting, it uses the list dictionary, not the message dictionary to format the footers. Of course, you want to do both: format with the list dictionary AND with the message dictionary. But does it make sense to combine the two into a temporary dictionary and use *that*? So my questions are: 1. Would this generally be useful--having the ability to put message specific information in the footers? 2. Would it specifically be useful to put the archive url into the footers? (I personally think so.) 3. Is the vague approach I sketched above the way you'd do it? That is, does it seem likely that it would work? Of course, I realize it's highly likely this entire message will be ignored since it's about Mailman, not Python per se. C'est la vie. Cheers, // mark -----Original Message----- From: Cameron Laird [mailto:claird at lairds.com]On Behalf Of Cameron Laird Sent: Monday, September 30, 2002 2:16 PM To: mark at mceahern.com : Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 30) QOTW: "One can always write very sparse or very dense lines of code that break the model, but in-the-large programmers do not normally do that. They tend to write code in lines that fit easily in their head and, because of this, one line of code is pretty much comparable to another." Jonathan Hogg "Why are there always jobs for salesmen?" Stephen Satchell Jack Diederich makes high-performance Permutations, Combinations, and other probability and statistics constructs available through SourceForge. http://probstat.sourceforge.net/ Puffin makes automation nice. http://www-106.ibm.com/developerworks/opensource/library/os-puffin2.html Pexpect fills in Puffin's most severe lack. http://sourceforge.net/projects/pexpect/ Uche Ogbuji introdues Python's XML and XML-RPC capabilities, and PyXML. http://www.xml.com/pub/a/2002/09/18/py.html http://www-106.ibm.com/developerworks/library/ws-pyth10.html http://www.xml.com/pub/a/2002/09/25/py.html September brought another round of attention to CP4E in the EDU-SIG group http://mail.python.org/pipermail/edu-sig/2002-September/thread.html Think in Tkinter. http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html Martin v. L?wis gives background to management of patches and contributions in the Python project. http://mail.python.org/pipermail/python-list/2002-September/122988.html Blog with Python. http://www.awaretek.com/nowak/kaa.html ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of summarizing action on the python-dev mailing list once every other week. http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.pytho n.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang .python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. - From zopestoller at thomas-guettler.de Tue Sep 10 09:34:55 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 10 Sep 2002 15:34:55 +0200 Subject: run-mailcap in python? References: <3d7de60b$1@news.sentex.net> Message-ID: Peter Hansen schrieb: > Thomas Guettler wrote: > >> Thomas Guettler schrieb: >> >>> Hi! >>> >>> On Unix there is a script called run-mailcap, which >>> opens the corresponding programm with the given file: >>> >>> run-mailcap foo.html >>> --> Default browser starts >> >> >> >> [cut] >> >>> run("foo.html") >>> --> Browser starts >> >> >> >> I just discoverd os.startfile(), but it is unfortunately >> only available on win32. >> >> A Unix version would be nice. > > > import os > if os.name == 'posix': > def startfile(name): > os.system('run-mailcap "%s"' % name) > os.startfile = startfile Yes, ugly but it works. Thank you! thomas From gerhard.haering at gmx.de Fri Sep 20 14:49:30 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 20 Sep 2002 18:49:30 GMT Subject: saving state in Python/CGI References: Message-ID: Frank Gibbons wrote in comp.lang.python: > Hi, > > I've been using Python (and Jython) for about 5 months now. So far, > so great. I'm building a CGI app that has about 5 different stages, > and I need to maintain state between them. CGI sucks. What else is new? > I need access to the data on each page, yet don't want to pass it as > a hidden field, Many people, including me, use a relational database for saving state in a CGI environment. -- Gerhard From richie at entrian.com Mon Sep 16 07:35:36 2002 From: richie at entrian.com (Richie Hindle) Date: 16 Sep 2002 04:35:36 -0700 Subject: html template system? References: Message-ID: <8a6ba1da.0209160335.2eb13353@posting.google.com> > what are good templating systems avaliable for python? > [...] i want a smaller footprint system. PyMeld is one option. It focusses on keeping the code in Python and the HTML in HTML - it doesn't mix HTML and Python. This means that the HTML is editable in any HTML editor, potentially by a non-programmer, and the programmer then manipulates the HTML using pure Python code. PyMeld wraps your HTML in a Pythonic object model, with which you can change the text, add/remove/change tags and tag attributes, clone pieces of HTML, change them and write them back in again, and so on. PyMeld is a single Python module of about 20KB - see http://entrian.com/PyMeld for example usage, manual and download. -- Richie Hindle richie at entrian.com From fperez528 at yahoo.com Fri Sep 20 18:07:11 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 20 Sep 2002 16:07:11 -0600 Subject: e vs exp()? References: <3a838998.0209191933.1f22e977@posting.google.com> Message-ID: Terry Reedy wrote: > Perhaps x**int is special-cased. But following must have a different > explanation: > >>>> e**2.1 > 8.1661699125676499 >>>> pow(e,2.1) > 8.1661699125676499 >>>> exp(2.1) > 8.1661699125676517 > > At least two of us expected x**y == pow(x,y) == exp(y*log(x)) (a > standard method, and the only one I could find in Abrahamowitz and > Stegun, Handbook of Mathematical Functions) but there must be a more > direct method being used at least in some C libraries now. Well, as Tim Peters already mentioned, implementing ** (or pow(), same thing) is a hairy problem and _not_ done through exp(log). On the other hand, exp() has its own separate implementation, even though it may or may not be as efficient as the one Tim mentioned with an error bound of .53 in the last digit, and fast to boot. Incidentally, A&S is a fabulous reference for formulas and value tables. But I wouldn't consider it authoritative as a source of optimal numerical algorithms by any stretch of the imagination. Cheers, f. From aahz at pythoncraft.com Wed Sep 18 12:02:37 2002 From: aahz at pythoncraft.com (Aahz) Date: 18 Sep 2002 12:02:37 -0400 Subject: monetary applications [was: Python GUI app to impress the boss?] References: <2R%h9.109893$ub2.2324479@news1.tin.it> Message-ID: In article <2R%h9.109893$ub2.2324479 at news1.tin.it>, Alex Martelli wrote: >Mark McEahern wrote: >> [Oren Tirosh] >>> >>> I don't understand what exactly you are complaining about but is sounds >>> interesting - can you elaborate? >> >> Perhaps the lack of a FixedPoint type? > >http://starship.python.net/crew/aahz/FixedPoint.py Note that FixedPoint is *not* BCD, particularly IEEE-854 BCD. But it's probably more than good enough for most applications, and it's extremely trustworthy. Right now, I've been stalled for many moons on my BCD module. But it's still on my list.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From sperry at newcreations.info Wed Sep 25 21:56:43 2002 From: sperry at newcreations.info (Sperry Russ) Date: Wed, 25 Sep 2002 21:56:43 -0400 Subject: Python and Scite Message-ID: <200209252156430267.0042D522@newcreations.info> Chris, Thanks for your help. The problem was in the path which I did not understand at first. Is th PythonWin your favorite editor? Sperry --------------------------------------------------------------------------------------------------------- > I am new to programming. I have downloaded Python 2.2.1 and Scite > 1.48 to learn how to program. I am trying to configure my Scite so > that it will run the python files by using go. When I try to do this > i get a message in the second window at the bottom -- unable to find > file. I have tried configuring the global options and have failed can > anyone help me? I need a step by step example if you can because I > cannot understand it according to the documentation that came with > Scite works out of the box for me. if you're on windows, make sure that python is found in the PATH. i.e. edit PATH that it contains the python directory. and you could look at PythonWin, it uses the editing component used in scite and has some additional features for the python programmer. additionaly it comes also with useful, de-facto standard, windows specific extensions. From DennisR at dair.com Thu Sep 19 19:17:04 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Thu, 19 Sep 2002 23:17:04 GMT Subject: Suggesting a filename on a HTTP-request by sending someting in the header of the reply References: Message-ID: This is really a comp.infosystems.www.authoring.cgi question, IMO. My testing/experience is that content type does not control the "save as ..." dialog. If you want your file saved as an EXE, you need to have .EXE ending your file name. So, now the question is "how can I execute a script called "xyz.exe"? While based on Perl and a different application, see my site http://www.autorunning.com/docs/abfaq/02-dnldmgr.cgi -- Dennis Reinhardt http://www.dair.com From phr-n2002b at NOSPAMnightsong.com Sun Sep 29 21:15:35 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 29 Sep 2002 18:15:35 -0700 Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> Message-ID: <7x1y7cl1l4.fsf@ruckus.brouhaha.com> "mike henley" writes: > i guess i'll rephrase; what i wish for is an "application-to-person" (P2A) > IM-based "presence", so that a web-application that i host on a personal > webserver, on my own machine, can let others become aware of its "presence" > easily and be easy to connect to with a simple > click-to-launch-browser-and-go-to-my-ip. This should be easy to do. I just > don't have experience with Jabber or xml-rpc, or other potential useful > technologies. I don't think you need anything nearly that fancy. Just use some simple AIM client on your box that runs when you connect to the internet. From wari at home.wari.org Sun Sep 15 12:46:10 2002 From: wari at home.wari.org (Wari Wahab) Date: Mon, 16 Sep 2002 00:46:10 +0800 Subject: ANN: pyblosxom weblog software Message-ID: <3D84B952.2060301@home.wari.org> pyblosxom is a weblogging tool written in Python and modelled after blosxom. It is written due to the fact that clones for blosxom exists except for python, so this is my implementation of it. In fact I'm into cloning so much that this announcement was ripped from a Kaa announcement, another weblogging tool written in python. The "download page" can be found here: http://roughingit.subtlehints.net/pyblosxom/ This is really the page of my pyblosxom blog; there are links to the distribution (a tar.gz file) and to a page with an introduction to pyblosxom. Any comments, bug reports, tips, feature requests, etc, etc, are welcome. Particularly eloquent flames will be published on my blog. :-) Especially ones that mentioned how bad my python is. (I'm a newbie:) -- Regards: Wari Wahab http://roughingit.subtlehints.net/ From aleax at aleax.it Tue Sep 17 02:52:08 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Sep 2002 06:52:08 GMT Subject: raw post data References: Message-ID: :B nerdy wrote: > how could i make it so when i read the stdin it still is there.. cause i > use cgi.FormVariables() also When you instantiate class cgi.FieldStorage (there's no such thing as cgi.FormVariables, so I'm just guessing at what it IS that you want!) you can pass it an optional first parameter that is a file object open for reading -- it uses sys.stdin as the default if you don't pass the first parameter. Thus, the following should work (untested!): import cgi, sys, cStringIO copyInput = cStringIO.StringIO(sys.stdin.read()) fieldStorage = cgi.FieldStorage(copyInput) The raw posted data are now available as the string returned by calling copyInput.getvalue(), and are also parsed by cgi to obtain fieldStorage. Alex From prouleau at impathnetworks.com Thu Sep 12 10:41:15 2002 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Thu, 12 Sep 2002 10:41:15 -0400 Subject: Is there a portable way to copy files in Python? Message-ID: <3D80A78B.5030206@impathnetworks.com> I have been using os.system() with the operating system 'cp' or copy commands when i want to copy files. I can use os.mkdir() to make directories, but i can't find a os.filecopy() or os.path.filecopy() or os.copy() or something like that. I must be missing something, since such a basic operation is likely to be needed by Python library users. I could write code that identifies the operating system (the os.path way) and use os.system("cp " + source_filename + " " + destination) for Unix-type and os.system("copy " + source_filename + " " + destination) but i would prefer to use a simple call. Is this available in the Python library? If not, why is it not part of the library? Thanks for your time! Pierre Rouleau From martin at v.loewis.de Thu Sep 19 14:57:27 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Sep 2002 20:57:27 +0200 Subject: How pass array from C to python function References: Message-ID: "Praveen Patil" writes: > mylist = PyList_New(5); > for (count=0; count< 5; count++) { > myint = PyInt_FromLong(vital_data[count]); > PyList_Append(mylist,myint); > } That is wrong. PyList_Append increases the list size by one, so the list will have ten elements at the end; 5 of them will be NULL. Either start with an empty list, or use PyList_SetItem. > arglist = Py_BuildValue("O", mylist); > ret = PyEval_CallObject(my_callback , arglist); > Py_DECREF(arglist); I recommend to use PyObject_CallFunction here, although your code is correct. > The information contained in this e-mail is confidential My reply is confidential, too. Don't read it. Regards, Martin From eddie at holyrood.ed.ac.uk Mon Sep 9 13:02:52 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Mon, 9 Sep 2002 17:02:52 +0000 (UTC) Subject: Python class ( Prolog ) ??? References: <20020905234600.11264.60328.Mailman@mail.python.org> <3D7914FD.5D713A48@anansispaceworks.com> Message-ID: Terry Hancock writes: >While we're on the subject -- I've taken a couple of >tries at Prolog in the past, but didn't really get >anywhere with it. I understand the concept of >expressing logic in code, but got rather bogged down >when it came to any practical examples. I made several attempts to understand prolog many many moons ago and likewise had difficulty relating it to practicality. Eventually I came across the book Clause and Effect by Clocksin which helped a lot. Unfortunately playing with prolog dropped so far down my 'interesting things to play with' stack about that time that its now fallen over the event horizon. Eddie From martin at v.loewis.de Mon Sep 2 01:46:58 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Sep 2002 07:46:58 +0200 Subject: status of decompyle ? References: <3D6B6A14.A6ADBFB4@engcorp.com> Message-ID: Andreas.Leitgeb at siemens.at (Andreas Leitgeb) writes: > Thus, my question to the group was just plain: > "Does anyone know about the current status of decompyle ?" That wasn't actually the question you've asked. To that question, I'd answer: "it reportedly works fine for older Python releases" However, you actually asked >Should I remain patient a little more, or mail again, > or does the author read this group, anyway ? >Or is decompyle in status "orphaned" ? to which I'd answer "yes, no, dunno, no". Regards, Martin From max at alcyone.com Thu Sep 19 17:37:13 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 19 Sep 2002 14:37:13 -0700 Subject: where is the __dict__ ? References: Message-ID: <3D8A4389.DFCB97FF@alcyone.com> black wrote: > my book said all dictionaries have __dict__ method but couldnt find > it by using dir(), where is it ? Didn't you already ask this? Dictionaries do not have a __dict__ attribute (they're dictionaries already, why would they need one?), but instances and classes do: >>> class C: pass ... >>> C.__dict__ {'__module__': '__main__', '__doc__': None} >>> c = C() >>> c.__dict__ {} -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ People are taught to be racists. \__/ Jose Abad Fauxident / http://www.alcyone.com/pyos/fauxident/ A "faux" ident daemon in Python From dfloer at topsoft.ca Mon Sep 16 19:54:52 2002 From: dfloer at topsoft.ca (Doug Floer) Date: Mon, 16 Sep 2002 23:54:52 GMT Subject: Unify Accell/SQL Message-ID: Has anyone out there had any experience converting an application from Unify Accell/SQL to Python? Thanks, Doug From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Tue Sep 24 11:23:58 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Tue, 24 Sep 2002 17:23:58 +0200 Subject: Difference between MOD_PYTHON and the CGI module References: <3d904321$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: <3d908385@news.mt.net.mk> > What are the differences, if any? > Am i mixing up to things here? > Suppose I'd like to use python as a 'replacement' for PHP, what do I use? spyce perhaps -- ?????? The NOC says: echo '16i[q]sa[ln0=aln100%Pln100/snlbx]sbA0D4D465452snlbxq'|dc From david.abrahams at rcn.com Mon Sep 30 20:15:38 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Mon, 30 Sep 2002 20:15:38 -0400 Subject: Is there a docutils / reStructuredText system for C++ source code available? References: <3D98D9D9.8000009@attglobal.net> Message-ID: "Pierre Rouleau" wrote in message news:3D98D9D9.8000009 at attglobal.net... > I have been using docutil and reStructuredText for Python code and it > works great. Pydoc does a superb job of helping in setting up an > internal web site that provides documentation for our Python code, let > alone the ability to run doctest test and show auto testing of python > documentation on line! > > That works great for our Python code. Now i want to do the same thing > for our C++ code. Since Python has been partly implemented in C / C++ > i tough there might already exist some tools for parsing C++ and some > comments (given some formatting conventions) and generate the same kind > of output the html tool of docutil does. > > Does any one know any thing that resembles that? See http://synopsis.sf.net -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From richie at entrian.com Thu Sep 26 10:28:24 2002 From: richie at entrian.com (Richie Hindle) Date: 26 Sep 2002 07:28:24 -0700 Subject: SET_LINENO References: <3D92A46E.2030706@cygnus-software.com> Message-ID: <8a6ba1da.0209260628.3a97add8@posting.google.com> Bruce, > As a partial author of the HAP Python Debugger (available on source > forge) I read about the imminent removal of SET_LINENO with some worry. I've been working on a Python debugger of my own, and having briefly tested it with 2.3a0, I'm nothing but delighted with the results. It fixes a number of minor niggles - stopping twice on block-start lines, stopping on 'def' lines and stopping on docstrings, to pick some random examples. > wouldn't a break-point opcode be a more substantial improvement This would be very nice too! -- Richie Hindle richie at entrian.com From see_reply_address at something.invalid Mon Sep 9 00:30:22 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 09 Sep 2002 16:30:22 +1200 Subject: Creating a Text widget in a Dialog (Tkinter) References: Message-ID: <3D7C23DE.9000900@something.invalid> Aki Niimura wrote: > def body(self, master): > self.usage = Text(master, height=26, width=80) > self.grid = Frame(master) > self.yscroll = Scrollbar(master, command=self.usage.yview) > self.xscroll = Scrollbar(master, orient=HORIZONTAL, The Frame should be the parent of the other three widgets: self.grid = Frame(master) self.usage = Text(self.grid, height=26, width=80) self.yscroll = Scrollbar(self.grid, command=self.usage.yview) self.xscroll = Scrollbar(self.grid, orient=HORIZONTAL, -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bdesth at nospam.free.fr Sat Sep 14 00:21:13 2002 From: bdesth at nospam.free.fr (laotseu) Date: Sat, 14 Sep 2002 00:21:13 -0400 Subject: I must be an idiot, please pity me! References: <3D801757.1020901@nospam.free.fr> Message-ID: <3D82B939.1060502@nospam.free.fr> newbie wrote: > On Thu, 12 Sep 2002 01:25:59 +0100, laotseu wrote: > > > >>Creating a db connection in each function for sure not be very >>efficient.But what's wrong with passing the database connection to the >>functions in mod1, mod2, and modXXX ??? > > > That connection has to be passed to the other functions (where needed of > course) in mod1. Say, mod1.functiona may use functions f1, f2 and f3. My > gut feeling of having to pass that connection to all of these said "this > can't be right". This is what I've done but it sure doesn't feel right! > > > >>Anyway, you can make it simpler, like this : > > > Yay, now for the good stuff! > > > >>in each module, >>- create a global db_connection variable - add an init() function, that >>takes a db_connection as argument and assign it to the module's global >>db_connection variable - and don't forget to call this function before >>any other. > > > Yes, I can follow that. Once I saw that "global" was more "local" I've > never really considered using it. ??? Not clear what you mean ??? > > >>Another, more OO way to do this would be to rewrite your modules as >>classes, each getting a db_connection argument in it's __init__(), and >>then, in the main script, create the needed objects. > > > So the resulting object would be the same as what I return with now? > A simple exemple is better than a long explanation : # this was your module mod3 import whateverYouHaveToImport class Mod3: def __init_(self, dbConnection): self.dbConnection = dbConnection # add what you need here def f1(args): something = self.dbConnection.doThis(args) return self.f2(something) def f2(args): return self.dbConnection.doThat(args) # this is you GCI module import mod3 import TheRest def main(): dbConnection = dbModule.CreateMyDbConnection(args) m3 = Mod3(dbConnection) this = m3.f1(42) Got it ? HTH Laotseu From michael at stroeder.com Sat Sep 7 11:23:00 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sat, 07 Sep 2002 17:23:00 +0200 Subject: None or 0 Message-ID: HI! I'm using the idiom a = a or b to get rid of statements like if a is None: a = b Now I wonder what happens if both a and b have zero-length values. Trying in Python 2.2.1 reveals: >>> repr(0 or None) 'None' >>> repr(None or 0) '0' >>> repr('' or None) 'None' >>> repr(None or '') "''" >>> Is it guaranteed to work like this or should that be avoided? Ciao, Michael. From tjreedy at udel.edu Thu Sep 26 17:47:00 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 26 Sep 2002 21:47:00 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <3D911FE1.1050801@something.invalid> <7nHk9.172208$pX1.6117207@news2.tin.it> Message-ID: "Alex Martelli" wrote in message news:7nHk9.172208$pX1.6117207 at news2.tin.it... > The reason > zz = a and b or c > is not the same thing as > zz = a ? b : c > is that, when a is true and b is false, the former returns c, > while the latter returns b. In almost all the practical cases where I have thought about using this, b is *not* false or cannot become false, in which important and real case the two expressions *are* equivalent. I think this is an elegant hack, and so I shared it in response to the OP. Others think it ugly. So be it. Terry J. Reedy From robie at 1373.net Mon Sep 23 23:17:21 2002 From: robie at 1373.net (robie1373) Date: Mon, 23 Sep 2002 21:17:21 -0600 Subject: confusion about opening files References: <3d8fcda4$0$198$75868355@news.frii.net> <3D8FCFF3.FD52AFE5@alcyone.com> <3d8fd215$0$192$75868355@news.frii.net> <3D8FD2F3.81F3831C@alcyone.com> Message-ID: <3d8fd8a7$0$200$75868355@news.frii.net> Cool! Thanks so much! I think I'm actually starting to get it! "Erik Max Francis" wrote in message news:3D8FD2F3.81F3831C at alcyone.com... > robie1373 wrote: > > > O. K. Now I am confused. I thought that when I imported the os > > module, i > > would have to call its functions like this: os.open() Why am I just > > using > > the function name? > > Because there are two different open functions here. One is in the > builtins, one is in the os module. They are not the same: > > >>> import os > >>> print open.__doc__ > file(name[, mode[, buffering]]) -> file object > > Open a file. The mode can be 'r', 'w' or 'a' for reading (default), > writing or appending. The file will be created if it doesn't exist > when opened for writing or appending; it will be truncated when > opened for writing. Add a 'b' to the mode for binary files. > Add a '+' to the mode to allow simultaneous reading and writing. > If the buffering argument is given, 0 means unbuffered, 1 means line > buffered, and larger numbers specify the buffer size. > Note: open() is an alias for file(). > > >>> print os.open.__doc__ > open(filename, flag [, mode=0777]) -> fd > Open a file (for low level IO). > > The os.open is a low-level API and is rarely going to be the one you > want. > > -- > Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ > __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE > / \ Insight -- the titillating knack for hurting! > \__/ Colette > Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/ > A highly categorized list of Web links. From tjreedy at udel.edu Fri Sep 27 17:22:33 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Sep 2002 21:22:33 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <7nHk9.172208$pX1.6117207@news2.tin.it> Message-ID: "Alex Martelli" wrote in message news:dITk9.175519$pX1.6209886 at news2.tin.it... > A typical, frequent, practical case is classification, e.g.: > > "Append bleep to list truebleeps when bleep is true, append it > to list falsebleeps instead when false". > > If we had a ternary operator, a natural way of expression would be: > > (bleep?truebleeps:falsebleeps).append(bleep) This reminds me of using ?: to calculate C lvalues (targets), which I am not sure all C programmers realize is legal, since all examples I read while learning only used ?: to calculate rvalues (sources). > It's _dangerous_ -- to use it, one always has to be fully aware > of the risk that subexpression b might be false. If b is a non-null constant, there is no such risk. Consider na=1; np=3; nl=1; ng=0 print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\ (na, na!=1 and 's' or '', np, np!=1 and 's' or '', nl, nl!=1 and 's' or '', ng, ng!=1 and 's' or '') Found: 1 apple, 3 plums, 1 lemon, and 0 grapes. Alternatives to this 'risky' construct: 1. forgo the nicety of correct English output 2. nest if/else four levels deep to choose correct variant of 16 print statements (ugh) 3. precalculate 4 suffixes and store in 4 temp vars with 4 if/else's (8 or 16 lines); though clearly superiour to 2), this is still tedious with some risk of typo error. To revise your statement: to properly use 'a and b or c' as a conditional expression, one must be aware of and remember the condition 'bool(b)==True'. To contrapositively paraphrase what I wrote before: if b is an expression with variables and it is not pretty clear that won't be null, then don't use it. This is as clear as "don't divide by 0 and be wary of variable expressions that might become 0." > I think this is a pitfall just waiting for the unwary to stumble. Must functions have preconditions on arguments or possibly surprising results that can cause the 'unwary' to stumble. 'x/y', 'float - (float+eps)' and '[[]]*n' are other examples. Perhaps we should better teach people "Before you use a function or language construct, make sure you understands its input conditions and output and the pitfalls thereof, lest you stumble due to unwariness". Terry J. Reedy From tismer at tismer.com Fri Sep 20 11:22:32 2002 From: tismer at tismer.com (Christian Tismer) Date: Fri, 20 Sep 2002 17:22:32 +0200 Subject: Overriding all methods in a class References: Message-ID: <3D8B3D38.8040309@tismer.com> Joao Prado Maia wrote: > Hi, > > I have been looking for an answer for this question for a while, but > couldn't find anything that would work for what I want to do. > > I know that you can use __getattr__ to overload methods that your class > don't have, but what about overloading all methods, so I could in a way > 'intercept' calls to my methods and do something different if I wanted, is > that possible ? > > What I want to do basically is create a caching system for a specific > class, and have __getattr__ (or any other magic method name) handle the > decision to sue the cached return value or to actually call the method. > > Maybe it would be just easier to rename my current class to _Classname and > create a new Classname with just __getattr__. > > Any suggestions ? Use the new class type, by deriving from some builtin, and then use the new __getattribute__. For instance class MyObject(object): def __getattribute__(self, name): print name return getattr(MyObject, name) But be *very* careful, it is easy to cause endless recursions, for instance it is not possible to use self.__class__ in that context. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From danb_83 at yahoo.com Wed Sep 4 09:53:07 2002 From: danb_83 at yahoo.com (Dan Bishop) Date: 4 Sep 2002 06:53:07 -0700 Subject: using python to call java code?? References: <3cc90cd2.0209040122.17242a04@posting.google.com> Message-ID: tim.schulz at sdm.de (Tim Schulz) wrote in message news:<3cc90cd2.0209040122.17242a04 at posting.google.com>... > I am considering to use zope in order to develop an content management > portal. My problem is, that I have to integrate some ready-built java > code. Is there any possibility to call java code from python? Is there > a API for this kind problem? http://www.jython.org From cypher_dpg at yahoo.com Sat Sep 7 00:01:42 2002 From: cypher_dpg at yahoo.com (Jeremy Jones) Date: Sat, 07 Sep 2002 04:01:42 GMT Subject: Thinking of joining References: <3D7970DC.5115BCC8@earthlink.net> Message-ID: <20020907001139.4daf27a3.cypher_dpg@yahoo.com> On Sat, 07 Sep 2002 03:18:33 GMT dark wrote: > Hello. > Im currently still learning C, but a friend has been trying to turn me > on > to python. I would consider him/her a very good friend for pointing you to Python. > From what ive seen it looks pretty good. > I was just curious if it will do everything PERL will do, as i > dont care for how PERL reads. It has done everything for me that Perl can...and then some. I started learning Perl a few years ago after beating my head against a wall after hitting some limitations with UNIX shell scripts. Perl was a wonderful breath of fresh air...until I started creating an OO module. (Actually the syntax started getting to me before I started creating the OO module, but for the sake of semi-brevity, I'll just stick to my gripes with modules.) The module itself grew to over some 700 lines of code. Any modification just got more and more painful. I decided to learn Python. That was probably the single best career-oriented decision I have ever made. I re-wrote the module in Python in almost half the lines of code (I think it's right around 400 lines of code right now). Modifications are simple to make. Very importantly, I can go months without touching the module and jump right back in with little effort (which I had a difficult time doing the same with the Perl module). I'll make this statement to keep anyone else from saying it first: it may well be that my (Perl) code just plain sucks. It probably does ;-) But it has become obvious to me that Python is a much more elegant, simple (I don't mean that in a belittling way at all), clear language to work with - unlike Perl. Anyway, that's my rant. > ( though a lot of proplr i have talked to try to push PERL on me) > Im going to try to discipline myself to get C down first, but its > tempting > to jump into Python now. I would recommend jumping into Python. Depending on what you are doing, you may well never need to even look at C code, let alone write it. (I know that there are some that would disagree with that.) And if you don't have to, then don't waste your time. I started out tinkering with C and I wish I had discovered Python first. I consider going back and brushing up on my C skills every once and again, but I find myself asking, "Why? What will getting better at C benefit me?" And I always wind up sticking pretty much solely to Python because it gets nearly every job done that I need to do. > I am a monty Python fan of many years, if that helps lol. > > Hee hee hee. That always helps. Jeremy Jones. From r.l.richardson at verizon.net Mon Sep 30 18:50:55 2002 From: r.l.richardson at verizon.net (Rick) Date: Mon, 30 Sep 2002 15:50:55 -0700 Subject: __call__ question Message-ID: <3D98D54F.5070200@verizon.net> If I generate a call method inside a class class with def __call__(self, arg1): ... everything is hunkey dorey. However if I generate the class then later try to add the __call__ function with setattribute or by create a function that behaves like call should and then assigning it to myobj.__class__ I can't call the instance of the class like a callable object. It states that that instance is not a callable object. I can however: myobj.__call__(myobj, arg1) and it works. Anyone know what I have to do to make an object callable at runtime? thanks, Rick Richardson From martin at v.loewis.de Wed Sep 25 02:28:28 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 25 Sep 2002 08:28:28 +0200 Subject: Solaris 64 bit compilation References: Message-ID: phoebe_1 at att.net (Holden Caulfield) writes: > > > Is anyone even interested in the configure.in patches? > > > > I don't really see a need, since it works fine without the patches. > > > Well, I will have to disagree here. As currently at lease in V2.2.1 vanilla > source there is *no* option to built in 64 bit mode, unless you hack the > CFLAGS, LDSHARED etc. > Unless, you know of way to pass the appropriate flags? Setting CC to "cc -xarch=v9", then running configure, has the desired effect. > Because my expectation was that I could build 64bit excutable/object/module > by running "configure", currently out of the box I could *not* figure out a > way to do this. You need to set CC for this. Regards, Martin From shalehperry at attbi.com Sat Sep 7 20:44:40 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 7 Sep 2002 17:44:40 -0700 Subject: Larry Wall's comment on python... In-Reply-To: References: <200209071429.26401.shalehperry@attbi.com> Message-ID: <200209071744.40129.shalehperry@attbi.com> On Saturday 07 September 2002 16:07, Fran?ois Pinard wrote: > [Sean 'Shaleh' Perry] > > > [yka] > > > >> [Kow Kuroda] > >> > >> > [...] For example, vi and emacs indent by 8 characters by default > >> > >> [...] Well at vim :set ts=4 makes more fitting > > > > actually emacs defaults to 4 space indenting [...] > > The Python mode writers for Emacs managed to automatically recognise the > indentation in use in a file, and continue editing that file with the same. > For new files, I get four spaces per level. > > However, for Python files indented with TABs only, Emacs cannot > successfully guess if the author's intent was to expand those TAB with four > or eight spaces. By default, I vaguely remember it picks eight. correct emacs says a tab is a tab and a tab means 8. From b.maryniuk at forbis.lt Fri Sep 6 11:08:25 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Fri, 6 Sep 2002 17:08:25 +0200 Subject: ttySx Message-ID: <200209061708.25677.b.maryniuk@forbis.lt> Hi, all. Is anybody know how to check modem status from the Python on Linux? I need something like send 'ATZ' and get "OK" or something. I've tried do somethig like: modem = open('/dev/ttyS0', 'r+') modem.write('ATZ\r') modem.read() # Hang here forewer This is bad. Then I've tried use several modules for serial port, wheere I can write, but if I read, always get ''. Perhaps I should figure out with DTR status and so on.... Any ideas? -- Regards, Bogdan Anybody who doesn't cut his speed at the sight of a police car is probably parked. From aleax at aleax.it Tue Sep 24 08:10:01 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 12:10:01 GMT Subject: list problem References: Message-ID: Duncan Booth wrote: > Thorsten Kampe wrote in > news:amp6i1$7n9bi$1 at ID- 77524.news.dfncis.de: > >> * Anthony Tuininga >>> If you have list comprehensions available, use >>> >>> [b for a in x for b in a] >> >> What about: >> reduce(lambda x, y: x + y, a) ? >> > > If you are going to use reduce, then you would be better off writing: > > import operator > reduce(operator.add, x) Maybe (marginally). But timing things is often a good idea: import time, sys, operator def alaAT(x): return [b for a in x for b in a] def alaTK(a): return reduce(lambda x, y: x+y, a) def alaDB(a): return reduce(operator.add, a) def alaAM(a, add=operator.add): return reduce(add, a) biggie = [ range(120) for i in range(160) ] def timit(func, N=100): repeat = [None] * N start = time.clock() for x in repeat: func(biggie) stend = time.clock() return "%2.2f %s" % (stend-start, func.__name__) print sys.version for i in range(3): for func in alaAT, alaTK, alaDB, alaAM: print timit(func) [alex at lancelot linud]$ python -O timit.py 2.2.1 (#2, Jul 15 2002, 17:32:26) [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] 1.43 alaAT 2.75 alaTK 2.69 alaDB 2.72 alaAM 1.42 alaAT 2.73 alaTK 2.72 alaDB 2.66 alaAM [alex at lancelot linud]$ >From this measurement it's unclear whether there's anything to choose between the versions using reduce, but Thorsten's original proposal appears to be substantially better than any of them (for these sizes of lists on this specific machine...) -- almost a factor of 2, thus almost worth noticing if the performance of this operation matters for the program being developed. Alex From gerhard.haering at opus-gmbh.net Thu Sep 12 10:23:20 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 12 Sep 2002 14:23:20 GMT Subject: DB Cursor iterator (was: [ANN] PySQLite 0.3.0 released) References: Message-ID: Daniel Dittmar wrote: > Terry Reedy wrote: >> Does anyone know whether there are any plans to update the Python-DB >> API to the new iterator protocols, so that the above could be written >> more simply something like >> >> for row in cursor: >> print "%14s, %15s, %19s, %8s, %25s" % tuple(row) > > It's already in the 'Optional DB API Extensions' in > http://www.python.org/peps/pep-0249.html Yep and these extensions are fully supported by PySQLite and pyPgSQL :-) -- Gerhard From david.abrahams at rcn.com Mon Sep 30 23:02:44 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Mon, 30 Sep 2002 23:02:44 -0400 Subject: Is there a docutils / reStructuredText system for C++ source code available? References: <3D98D9D9.8000009@attglobal.net> <3D9916E2.5030006@attglobal.net> Message-ID: "Pierre Rouleau" wrote in message news:3D9916E2.5030006 at attglobal.net... > > David Abrahams wrote: > > "Pierre Rouleau" wrote in message > > news:3D98D9D9.8000009 at attglobal.net... > > See http://synopsis.sf.net > > > > > Thanks! > I also found another tool called Doxigen at > http://www.stack.nl/~dimitri/doxygen/ > > Anyone has experience with it? Widely used, but it's half-arsed C++ "Parser" is completely inadequate for the type of code I write. I'm hoping that synopsis will pan out for me since it is built on a real parser, but so far I haven't had great success. I need more time to do a good evaluation. -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From pinard at iro.umontreal.ca Tue Sep 3 07:56:02 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Tue, 03 Sep 2002 07:56:02 -0400 Subject: ANN: Pyrex 0.4.4 In-Reply-To: (Greg Ewing's message of "Mon, 02 Sep 2002 16:38:58 +1200") References: Message-ID: [Greg Ewing] > * Tracebacks: Pyrex modules now produce tracebacks that > show you where the error occurred in the Pyrex code. Wow! :-) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From xtian at toysinabag.com Thu Sep 19 20:46:40 2002 From: xtian at toysinabag.com (xtian) Date: 19 Sep 2002 17:46:40 -0700 Subject: lists in dictonaries ? References: Message-ID: Andreas.Leitgeb at siemens.at (Andreas Leitgeb) wrote in message news:... > Andrew Thompson wrote: > > You can put any python objects into a python dictionary, even the > > dictionary itself... > > Oh, can I create a dictionary in Python that contains all those > dictionaries that don't contain themselves ... ?-) > > *scnr*'ly yours. Would it contain itself? xtian From bokr at oz.net Thu Sep 5 15:54:02 2002 From: bokr at oz.net (Bengt Richter) Date: 5 Sep 2002 19:54:02 GMT Subject: Why read-only nested scopes? References: Message-ID: On 05 Sep 2002 20:46:44 +0200, martin at v.loewis.de (Martin v. Loewis) wrote: >bokr at oz.net (Bengt Richter) writes: > >> How about introducing an optional "degree of globalness" for the >> global declaration? E.g., > >> >> x = 1 >> def foo(): >> x = 2 >> def bar(): >> x = 3 >> def baz(): >> global(1) x >> x = 4 >> >> would go outwards 1 nested scope and thus target the x in bar, >> rebinding it from 3 to 4. > >That would work - although I'd claim that some users will find that >notation plain ugly. > >It will also have confusing results: > >x = 1 >def foo(): > print x > def bar(): > global(1) x > x = 1 > >At the moment, the "print x" in foo prints the global x, since there >is no assignment to x, and hence there is no local variable foo. With >the global statement, you declare that there is a local variable >foo::x. As a result, since there is no assignment to foo::x, this >would raise an UnboundLocal error. > I Python didn't effectively look ahead of the current line to decide what scope a symbol belonged to, it wouldn't be a problem. The print x would find the global x, and if bar were called after print x (and after its definition, of course), then foo::x would be created, shadowing the global x, and another print x following that would print the new (indistinguishable above) value in foo::x. IMO, that would be more intuitive too. Compare to: [13:02] C:\pywk\junk>type foo.cpp #include int x = 123; void foo(){ printf("global x @ %p: %d\n", &x, x); int x(x); printf(" local x @ %p: %d\n", &x, x); } void main(){ foo(); } [13:03] C:\pywk\junk>cl foo.cpp Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86 Copyright (C) Microsoft Corp 1984-1998. All rights reserved. foo.cpp Microsoft (R) Incremental Linker Version 6.00.8168 Copyright (C) Microsoft Corp 1992-1998. All rights reserved. /out:foo.exe foo.obj [13:03] C:\pywk\junk>foo global x @ 00406030: 123 local x @ 0012FF74: 123 Regards, Bengt Richter From gerhard.haering at opus-gmbh.net Mon Sep 16 07:34:10 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 16 Sep 2002 11:34:10 GMT Subject: (no subject) References: Message-ID: Srijak Rijal wrote: > Hi all > > I just migrated from perl to python and was wondering if python socket > can be read line by line too? You can use makefile() on the socket and then use all the usual file methods, including readline() afterwards. -- Gerhard From spendius at muchomail.com Mon Sep 2 10:33:09 2002 From: spendius at muchomail.com (Spendius) Date: 2 Sep 2002 07:33:09 -0700 Subject: Newbie's unsurmountable pb with IO stream trick Message-ID: I'm about to give up learning Python because I've met insurmountable problems. I'm a newbie just having begun teaching myself this language a few days ago, and I already stall against unsolvable (at least to me) issues: so could you please help me and *show me* I'd be wrong giving up ? I tried to rewrite something I wrote in Java, trying to communicate with an OS process (SQL*Plus in this occurence), but big time bucked against - the lack of methods of the so-called 'file objects' (if there was an equivalent to java.io.InputStream.available() !) - the fact you don't declare variables: you just assign values to them => I immediately hit against the 'global' keyword issue (rather a global mess) and gave up... For those who know SQL*Plus y'all know you get a prompt: "SQL> " (remove the "'s to get the string) and then this frontend Oracle software waits for your input. This is somewhat tricky to deal with, but in Java I managed to find a solution [because your InputStream blocks, which makes your program hang if you don't address this 'waiting prompt' problem] thanks to a sub-thread that tries to read the InputStream every time I detect that the method available() returns 0 (zero): if the next character in my stream is easily readable -if it doesn't block- I return it, if it blocks OK I know I've reached the final 5 characters 'S', 'Q', 'L', '>', ' ' and that I'll never get the following one, so I return -1 (EOF in Java). So I have a challenge for you guys who are enough acquainted with Python: how could I perform the same with this language ? Thanks ever so much to y'all... ____________________ ( ) ( operating syst. ) ( ___________ ) ( / SQL*Plus \ ) ( \__process__/ ) ( ? | ) (____|________|______) | | | | | | | \|/ | output str. --->--> sent to a tcl window (for ex.) input ('InputStream' in Java -sic !-) stream (called 'OutputStream' in Java !!) Send "select sysdate from dual;" to the input stream & you'll get the output stream string (remove the "'s): "\n" "SYSDATE\n" "---------\n" "02-SEP-02\n" "\n" "SQL> " From vetter at lincom-asg.com Wed Sep 11 09:29:43 2002 From: vetter at lincom-asg.com (Keith) Date: 11 Sep 2002 06:29:43 -0700 Subject: Regexp Over Multiple Lines References: <565e316f.0209040740.36573b56@posting.google.com> Message-ID: <565e316f.0209110529.30e61ea4@posting.google.com> vetter at lincom-asg.com (Keith) wrote in message news:<565e316f.0209040740.36573b56 at posting.google.com>... > In Python can I have a regular expression that spans multiple lines... > e.g. In Perl I may define a regular expression like: > > $depends_def = qr/ > [\w_\.]+\s*: # simobject: > \s* > [\w_\.]+ # job name > \(\s*(?:[\d]*)?\s*\) # arg list for job (optional > num) > \s+ > depends\s+on # keywords "depends on" > \s+ > (?: > [\w_\.]+\s*: # simobject: > \s* > (?: > [\w_\.]+ # job name > \(\s*(?:[\d]*)?\s*\) # arg list for job (optional > num) > (?: > (?: > \s+ > and\s*[\w_\.]*\s*: # "and simobject:" > \s* > [\w_]* # job name > \(\s*(?:[\d]*)?\s*\) # arg list for job (optional > num) > )+ > )? # match optional "and" 1 or > more times > ) > ) > /sx; > > then later I can use that regular expression in another regular > expression. > > It helps to span multiple lines for commenting what the heck the ugly > regular expression is trying to do... > > BTW: I am investigating Python and have no knowledge of it. Our Perl > code has just gotten out-of-hand. > > Thanks, > Keith After reading the links you guys suggested... it looks like the python regular expressions are very powerful. I am sure that this has been discussed... but in a nutshell can you tell me where python lacks in power behind perl. If I go to rewrite my Perl code, which has gotten really messy, in Python will I be saying over and over again, "Man, I can't do =that= in Python!" I am testing the waters before I dive in! Take care, Keith From marklists at mceahern.com Mon Sep 9 23:36:37 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 9 Sep 2002 22:36:37 -0500 Subject: dynamism In-Reply-To: <66715c02.0209091923.265fe77e@posting.google.com> Message-ID: [Steven Shaw] > I've been away from Python for awhile and I'm wondering whether Python got > less "dynamic" while I was away. > > I thought you could just extend an object's attributes at > run-time like this: > > >>> p = object() > >>> p.x = 1 > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'object' object has no attribute 'x' object is the base type of new-style classes. Try something like this instead: >>> class foo:pass ... >>> f = foo() >>> f.x = 1 >>> f.x 1 Or 'class foo(object):pass' works too. // m - From jkraska at san.rr.com Thu Sep 26 00:36:41 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 26 Sep 2002 04:36:41 GMT Subject: Larry Wall's comment on python... References: <3D7958DB.50903@nospam.free.fr> <3D87402E.6020700@thinkware.se> <3D926C1B.7080204@something.invalid> Message-ID: <8635puklc5oj74sno9emdbl5h0oibcg0g3@4ax.com> On Thu, 26 Sep 2002 14:08:27 +1200, Greg Ewing wrote: >Jacob Hallen wrote: > >> Please note that I didn't say anything about block >> delimiters or parentheses in this. I think they were put into programming >> languages to make it easy to write fast compilers. Even Python uses block delimeters internally in order to properly parse the language. They are actually inserted by the _LEXER_, which performs an elaborate indentation-aware transformation of the code, inserting INDENT and DEDENT tokens into the stream where they are needed. Hence, this expression... for i in mylist: expr ...becomes... FOR IDENTIFIER IN IDENTIFIER INDENT expr DEDENT Well, at least notionally. I'm not highly well-informed on the particulars, and my knowledge may be a bit out of date. This is, by the way, about the most elegant design pattern one can use to solve this particular problem. There are many other approaches which have heinous hidden pitfalls. C// From martin at v.loewis.de Wed Sep 4 03:01:01 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Sep 2002 09:01:01 +0200 Subject: PyListObject & C Modules References: Message-ID: Brian Quinlan writes: > if(PyList_Size(list) == 0){ > PyErr_SetString(PyExc_ValueError, "empty lists not allowed"); > return NULL; > } > > first = PyList_GetItem(list, 0); > + if (first == NULL) return NULL; That can't happen, really - GetItem can fail only if it is not a list, or if the index is out of range. However, it is a good strategy to test all results. > + Py_ADDREF(first) > - PyList_SetItem(result, 0, first); > + if (PyList_SetItem(result, 0, first) != 0) { > + Py_DECREF(first) > + Py_DECREF(result); > + result = NULL; > + } I see: yes, this is needed. I wasn't really aware that SetItem steals a reference. This is counter-intuitive - it might be better to use PySequence_SetItem instead. Regards, Martin From sismex01 at hebmex.com Mon Sep 30 13:59:03 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 30 Sep 2002 12:59:03 -0500 Subject: Decimal arithmatic, was Re: Python GUI app to impress the bos s? Message-ID: > > Steve Holden wrote: > > > wrote... > > > > > >[ ... ] > >OK, so don't use whole pennies (or smallest currency) as your > >base, use 10,000ths of a penny, but still use integer arithmetic > >for your calculations. > > > Normal Integers aren't big enough. 2^31 / 10K == 215K. > > --jb > > -- > James J. Besemer 503-280-0838 voice > 2727 NE Skidmore St. 503-280-0375 fax > Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com > http://cascade-sys.com > "Integer arithmetic" != "32-bit integer arithmetic". The first may be based on the second but they are definitely not the same thing. Python longs are memory-limited, yet they are also based on machine integers. Does that make them unsuitable? -gustavo Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From dkuhlman at rexx.com Tue Sep 24 13:12:55 2002 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 24 Sep 2002 10:12:55 -0700 Subject: general thoughts References: <3D8B3250.BA964BCF@ObjectWay.it> Message-ID: Nicola Musatti wrote: > > > Alex Martelli wrote: > [...] >> I think you need substantial capacity and appetite for abstract thought >> to really _enjoy_ SICP -- it doesn't spoon-feed you, nor does it use >> baby-talk, lots of somewhat-repetitive examples, and other standard >> didactical techniques. But if the book's style does match your own >> character and inclination, you're likely to fall in love with it. > > Or, to put it in another way, gurus like this book. ;-) Not meaning to show my ignorance here, but ... This book is a huge time sink. One section shows you how to fake object oriented programming in a dialect of lisp with no O-O support. After working through that section, I asked myself, Why do I need to know this? What good is it going to do me, unless I'm using a lisp dialect that does not support object-oriented programming? And, a large part of the book describes how to program without variables and state. That's weird and interesting, just like the Elephant Man was weird and interesting. But, after that, then what? Am I supposed to try to program that way? What is the lesson to be learned from "Structure and interpretation of Computer Programs"? Maybe it's main purpose is to provide an enjoyable read for those who have still not given up on lisp. Seriously, what was I supposed to have gained from all that time I spent on this book. As you may suspect, it captivated me, too. It did not teach me good Python programming style. I could not hardly read my own code with all those many layers of parentheses. It did not teach me how to use Python data structures. I found myself doing too many screwy things with lists. I was supposed to learn something more theoretical, right? What was it? Or, was this book just a devious way to trick more people into using lisp? - Dave -- Dave Kuhlman dkuhlman at rexx.com http://www.rexx.com/~dkuhlman From tismer at tismer.com Tue Sep 17 16:42:24 2002 From: tismer at tismer.com (Christian Tismer) Date: Tue, 17 Sep 2002 22:42:24 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: <3D8793B0.3020906@tismer.com> Michael Chermside wrote: ... > Okay, let's see if we can settle this... because I think it has real > potential. > > I am going to pose a hypothetical situation... please don't argue about > whether these conditions are true now, or whether they will be true, but > take these as assumptions: Thanks a lot for this great summary. I'd just like to do a small addition: ... > (3) Someone (probably NOT Christian) is willing to take on the job of > merging it into the core and maintaining it afterward. I would of course not refuse to keep maintaining it, let it be in the trunk or not. I was just rying to say that I'm just not willing to fight for it by discussion any longer. I'm a coder. Stackless is my heart code and I will do for it whatever it needs. ... > ... leave Christian to do what he's doing well, and let someone else > worry about possible integration. And that would be the only contribution I'm asking for. thanks again - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From quiteblack at yahoo.com Thu Sep 19 06:07:14 2002 From: quiteblack at yahoo.com (black) Date: Thu, 19 Sep 2002 03:07:14 -0700 (PDT) Subject: where is the __dict__ ? Message-ID: <20020919100714.69003.qmail@web21304.mail.yahoo.com> Howdy~ my book said all dictionaries have __dict__ method but couldnt find it by using dir(), where is it ? --------------------------------- Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! -------------- next part -------------- An HTML attachment was scrubbed... URL: From mongo57a at comcast.net Fri Sep 27 23:54:52 2002 From: mongo57a at comcast.net (mongo57a at comcast.net) Date: Sat, 28 Sep 2002 03:54:52 GMT Subject: Help please with menubars Message-ID: <3d9516b3$1_7@goliath.newsgroups.com> I have a built a menubar and I can do pulldowns. Lots of examples of that. But if you want to directly execute a function based on selection of a menubar item, how do you do that? Specifically: I have an "exit" item on the menubar and if the user clicks on "exit", the window should be closed. What I don't want is a pulldown with "exit" as a button option. Anybody know how to do this? Thanks. -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From claird at starbase.neosoft.com Tue Sep 17 10:25:26 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 17 Sep 2002 09:25:26 -0500 Subject: concurrent programming References: Message-ID: In article , Chris wrote: >Thank you for the advice, but I have the instruction to write it in C++, so >this is a point I cannot change. Only for the scripts, Python should be >used. >Well, I know a little bit about how to do concurrent programming in Python, >and in C++ too, but my problem is that I don't know how to combine these two >technologies for the PARBEGIN, PAREND block. Now I'm even more confused. It sounds as though you're constrained to do all the scheduling in C++, so I don't understand the pertinence of Python's concurrency idioms. They don't matter. You have to schedule the parallelism with C++, so Python is just a passive interpreter embed- ded into the larger C++ scheduling application, right? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From yaipa at aol.com Fri Sep 20 16:17:34 2002 From: yaipa at aol.com (yaipa) Date: 20 Sep 2002 13:17:34 -0700 Subject: linking extension modules w/ "ld" on Solaris - to be expected? References: <8d148763.0209190901.6276b37e@posting.google.com> Message-ID: <8d148763.0209201217.36cf7080@posting.google.com> Skip Montanaro wrote in message news:... > Alan> I've tried compiling both Python 2.1.1 and 2.2.x on Solaris 8 and > Alan> 9 with gcc 2.9x and 3.x in my path. I consistently get the same > Alan> build error each time, so it is likely that there is some *switch* > Alan> I am not setting somewhere. > > ... > > Alan> gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include > Alan> -DHAVE_CONFIG_H -DBUILD=`cat buildno` -o Modules/getbuildinfo.o > Alan> ./Modules/getbuildinfo.c > Alan> rm -f libpython2.2.a > Alan> ar cr libpython2.2.a Modules/getbuildinfo.o > Alan> gmake: ar: Command not found > > You need /usr/ccs/bin in your PATH. That's where ar and several other > compilation- and link-related commands live, not just compilers proper. Bing! Da-Bang! Da-Boom! Worked like a champ. Thanks Skip. From skip at pobox.com Mon Sep 16 21:27:03 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 16 Sep 2002 20:27:03 -0500 Subject: Python equivalent to perldoc? In-Reply-To: References: Message-ID: <15750.34023.116179.238352@12-248-11-90.client.attbi.com> Bob> In Perl you can run "perldoc warnings" and get the definition of Bob> what "warnings" does. Is there a equivalent in Python? Try "pydoc warnings". -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From Inyeol_lee at yahoo.com Thu Sep 19 12:37:36 2002 From: Inyeol_lee at yahoo.com (Inyeol Lee) Date: 19 Sep 2002 09:37:36 -0700 Subject: Minimal debug/rep functionality References: Message-ID: I was writing similar tools, and found strange things related to f_lineno. For multi-line statements, python 2.2.1 sometimes sets f_lineno to the start line, and sometimes to the current line. This is not related to -O optimization. I reported this to SF bug 607092, but this case is now closed with "won't fix" status. Anyway, there seems to be an extensive change to f_lineno in 2.3, so I'm just waiting for it. --Inyeol From tismer at tismer.com Wed Sep 18 13:01:13 2002 From: tismer at tismer.com (Christian Tismer) Date: Wed, 18 Sep 2002 19:01:13 +0200 Subject: Copy with __slots__ References: <3K1i9.110352$ub2.2335897@news1.tin.it> Message-ID: <3D88B159.3080202@tismer.com> Alex Martelli wrote: > Griebel, Peer wrote: > class withslots(yetanother): > __slots__ = ('s2',) > def __copy__(self): > result = self.__class__.__new__(self.__class__) > for base in self.__class__.__mro__: > for s in getattr(base, '__slots__', []): > setattr(result, s, getattr(self, s)) > return result > > the slowdown is even more severe -- to 0.62. Still nothing > like the 1.04 you pay for NOT having the slots at all, of > course, but it's starting to undermine performance improvement, > the only real rationale for having __slots__ at all. Still, > you pays your money, and you makes your choices. You can get this to the single slot-level speed by doing the slot grabbing phase of above once, after the class has been created. I'd add an all_slots class attribute with all collected slots and then iterate over it. I think this is quite safe, since when you are using slots, you are most probably *not* assuming that the classes will change dynamically. If so, the all_slots need to be re-built. ciao - chris p.s.: I didn't do any testing at all, but I guess some more speed can be found by not caching the __slots__ but their get/set wrappers and then just calling these with the new instance... -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From wlfraed at ix.netcom.com Thu Sep 19 17:20:28 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 19 Sep 2002 14:20:28 -0700 Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <23891c90.0209190014.26c5bb9@posting.google.com> Message-ID: Paul Boddie fed this fish to the penguins on Thursday 19 September 2002 01:14 am: > It could well be that not many people do financial database > programming in Python, bizarre and unlikely as that may seem. Taking a > look at pyPgSQL, as the only database module I have installed that > actually readily documents such things (and that should tell you > something), it would seem that monetary amounts are converted to > floating point numbers - surely the first thing one would want to > avoid in manipulating financial data. Perhaps people use integers, or > perhaps other modules provide better decimal support. > If I recall from the c.l.ada group, GNAT's "fixed point" data type is implemented as scaled integers, so even that might not pass the spec for a monetary type. My VB references are on loan (or currently stuck in the Windows environment and unreadable on Linux) so I can't recall what VB6 had for fixed/monetary. The only language I've ever encountered that had a truely monetary safe fixed point data type is COBOL -- which has always used packed BCD formats (though where the sign "bit" is stored may vary). COBOL was created from the beginning for "business" applications (heck: COmmon Business Oriented Language) and was spec'd by a government team. My college mainframe required /four/ of the sixteen registers to hold /one/ BCD number (32 BCD digits, 2 digits/byte, 16bytes @ 4/register). -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From remi at cherrypy.org Mon Sep 2 04:51:06 2002 From: remi at cherrypy.org (Remi Delon) Date: Mon, 2 Sep 2002 10:51:06 +0200 Subject: [ANN] CherryPy 0.6 released (SSL support) Message-ID: We're pleased to announce the release of CherryPy-0.6. This release adds SSL support to CherryPy (based on PyOpenSSL). Many thanks to Martin Sj?gren for his PyOpenSSL package and to Mark Wormgoor for his contribution to the CherryPy SSL code. ------------------------------------------ About CherryPy: CherryPy is a Python-based tool for developing dynamic websites. It uses many powerful concepts together, which makes it unique in its approach to website development. CherryPy sits between an application server and a compiler. You write source files, compile them with CherryPy and CherryPy generates an executable containing everything to run the website (including an HTTP server). Key properties/features of CherryPy are: - Based exclusively on Python (runs everywhere Python runs) - Delivers fast, robust, and scalable websites - Developers can use OOP as well as AOP (Aspect Oriented Programming) concepts to develop websites - True separation of content and presentation - Simple but powerful templating language - "HTML editor safe" templating language (templates can go back and forth between designers and developers) - Powerful standard libraries to make your life easy Other properties/features are: - Can be linked to many databases (Oracle, Sybase, MySql, PostgreSql, ...) - Can run behind another webserver (Apache, ...) - Easy clustering and load-balancing set up for high-traffic websites - Built-in caching capability - SSL support Remi. http://www.cherrypy.org From ugoertz at mi.uni-koeln.de Sun Sep 29 09:32:34 2002 From: ugoertz at mi.uni-koeln.de (Ulrich Goertz) Date: 29 Sep 2002 15:32:34 +0200 Subject: Tkinter: bind Alt + mouse click Message-ID: Hi, I am puzzled why I cannot bind events of the type "Alt" button press plus mouse click. In other words, the following script which just opens a window and should react on Alt-clicks by printing 'click', doesn't work for me: # --------------------------------- from Tkinter import * def p(event): print 'click' root = Tk() f = Frame(root, width=100, height=100) f.pack() f.bind('', p) root.mainloop() # --------------------------------- (The window pops up, but nothing happens upon clicks.) Everything works as expected if I replace by <1>, or . I tried this on a Linux box with Python 2.0, 2.1 and 2.2, and Tk 8.3. Any hints? Ulrich From loewis at informatik.hu-berlin.de Mon Sep 9 05:20:06 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 09 Sep 2002 11:20:06 +0200 Subject: successor to htmllib References: Message-ID: Erik Price writes: > I noticed that the htmllib module is really best suited to HTML 2.0 > documents. I was wondering if there was a newer (4+) HTML or even > XHTML parsing module in development right now. (By XHTML parsing lib > I mean perhaps an XML parser that is specifically written for the > XHTML 1.0 DTD. I realize that any XML parser -should- work.) PyXML offers xml.dom.ext.reader.HtmlLib, and xml.dom.ext.reader. Both create HTML DOM trees, one from a HTML document, the other from a XHTML document. HTH, Martin From tjreedy at udel.edu Thu Sep 19 10:45:53 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Sep 2002 14:45:53 GMT Subject: strong/weak - dynamic/static [Was: Getting started] References: Message-ID: "Jacek Generowicz" wrote in message news:tyf8z1y5cp5.fsf at pcitapi22.cern.ch... > A quick google search suggests that Bruce Eckel really claims that > python is weakly typed (at least more weakly typed than C++). To my commonsense idea of strong and weak, this is exactly backwards. 1. Python is not 'typed', at least not in the sense meant here. Nor is any other computer language ;-). Languages (or programmers using them) type 'things' within the language. 2. Unlike many other languages, Python does *not* type names. Names in Python are typeless - unless you want to claim that they take on a type be virtue of being bound. Python *does* type objects with values, so you can also say that it types values. On the other hand, values in, for instance, C, can be regarded as typeless bit sequences (which, at a hardware level, they are). 3. The typing that Python does do is *stronger* than that of C; no type-changing casting allowed. In some languages, you can, for instance, treat a four-byte integer as an array of four characters, but not in Python. You can explicitly extract a byte with bit shifting and making and use chr() to make a new object, but that is different from treating the byte in place as a char. [Discussion of old and new classes and modification of instance.__class__ omitted.] > Could someone provide a serious reference I'll leave this for someone else. >explaining or defining the concepts of ... dynamic and static typing. Python objects are typed at creation. Is that dynamic or static? I'm not sure the dichotomy applies to Python very well since it partly depends on a distinction between declaration and definition that does not exist in Python and a distinction between compile time and run time that is somewhat different in Python. Terry J. Reedy From brueckd at tbye.com Fri Sep 27 01:02:33 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Thu, 26 Sep 2002 22:02:33 -0700 (PDT) Subject: How do you pronounce "__" (double underscore)? In-Reply-To: Message-ID: On 26 Sep 2002, Mark Jackson wrote: > > > Pat Notz wrote: > > >> @ = "at" > > >> ! = "bang" > > >> . = "dot" > > >> * = "star" > > >> > > >> Is there a short (one or two syllable) pronounciation for "__" (double > > >> underscore). "Underscore underscore" and "double underscore" are kind > > >> of long. Somthing like "splat"? Anyone? > > > > > > _ = 'under' > > > > > > __ = 'under-under' > > > > > > How about "underder"?? > > How about "dunder" (double under)? How about "score" and "scorescore"? From mhammond at skippinet.com.au Thu Sep 12 19:05:03 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 12 Sep 2002 23:05:03 GMT Subject: [win32all] Out parameter in outgoing interface References: Message-ID: Syver Enstad wrote: > It does not seem possible use out parameters in an outgoing interface. > > Scenario: > > outgoing dispinterface, atl implementation of server, makepy support > generated, python client which implements the outgoing interface. > > Tried with both win32com.client.getevents and > win32com.client.DispatchWithEvents > > Debugged through it, the event gets fired from atl code the python > code gets called, I thought maybe returning a tuple (the return value > + the outgoing value) would work but the out parameter, a BSTR* (ie a > OLECHAR**) is untouched back in ATL land. > > I guess this is unsupported, or?? > This does work. Try it first with a simple type. For a string, you may be expecting the string to be modified in place, but in general, a new BSTR will be allocated and returned. Mark. From theller at python.net Mon Sep 9 11:18:53 2002 From: theller at python.net (Thomas Heller) Date: Mon, 9 Sep 2002 17:18:53 +0200 Subject: Windows/DOS: double clicking a .py file References: Message-ID: "Just" wrote in message news:just-A936EC.17062909092002 at news1.xs4all.nl... > Sorry if this is a Windows FAQ, I'm a newbie to Windows, but not to > Python. > > If I double-click a Python script (or use the start command in the dos > prompt) a new dos prompt window is opened and my program is run. The > window goes away when the program is done. However, the window _also_ > goes away when the program raises an exception, making it virtually > impossible to actually _see_ the exception... Is there a way to keep the > dos prompt window in this case? One solution is outlined here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287 This is useful for the development machine. It keeps the DOS window open, and leaves you in the Python debugger, where you can play around even more to find out about the state of your program. > > A py2exe-fied version of the program shows the same behavior, which > leads my users to report problems like "the output file is mysteriously > truncated" instead of "I'm getting a traceback. Here, have a look."... > > Any suggestions? For py2exe-packages apps you should redirect sys.stdout and sys.stderr into a log-file. Thomas From martin at v.loewis.de Sat Sep 21 12:34:23 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Sep 2002 18:34:23 +0200 Subject: Solaris 64 bit compilation References: Message-ID: phoebe_1 at att.net (Holden Caulfield) writes: > > Please try to report failures carefully. It does not say sizeof(LONG), > > instead, it says SIZEOF_LONG. Which gives rise to the question: What > > value does SIZEOF_LONG have, in pyconfig.h? > > > cc -c -DNDEBUG -g -Xc xarch=v9 -xcode=pic32 -I. -I./Include > -DHAVE_CONFIG_H -o Modules/p > ython.o Modules/python.c > "./Include/pyport.h", line 480: #error: "LONG_BIT definition appears > wrong for platform (bad gcc/glibc config?)." So what value has SIZEOF_LONG in pyconfig.h? How did you invoke configure? How did you manage to get -xarch=v9 into the compiler command line? Regards, Martin From loewis at informatik.hu-berlin.de Mon Sep 2 12:56:17 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 02 Sep 2002 18:56:17 +0200 Subject: compiling extensions on linux References: <3D738D4E.35B6C712@mill.co.uk> <3D739730.DEB80478@mill.co.uk> Message-ID: Joe Connellan writes: > it does have a initmyextension declared - Here's a simple example of my > problem - I've taken all c++ related stuff out so I can use gcc However, you are still compiling it as a C++ program, since it has the .cpp extension. You either need to rename the file (to .c), or use the -x c command line option. If there was C++ stuff to take out, you best declare the function as extern "C". Regards, Martin From henrik.motakef at web.de Fri Sep 20 06:07:51 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 20 Sep 2002 12:07:51 +0200 Subject: What the heck? open() requires an integer? References: Message-ID: <87y99xrn2g.fsf@pokey.henrik-motakef.de> "Fausto Arinos de A. Barbuto" writes: > The open() function is returning me a strange error. > An attempt to create an output file with > > f = open("output.txt","w") > > yields the following error: > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: an integer is required Did you by chance import * from os? Looks as if you get os.open, that indeed wants an integer. hth Henrik From gbreed at cix.compulink.co.uk Mon Sep 16 09:23:05 2002 From: gbreed at cix.compulink.co.uk (gbreed at cix.compulink.co.uk) Date: Mon, 16 Sep 2002 13:23:05 +0000 (UTC) Subject: "if x == None" raises "'NoneType' object is not callable" References: Message-ID: Luc Saffre wrote: > Strange! Nobody told you to call 'None'! Who knows an explanation? You have an error here: > except KeyError,e: > AttributeError,str(e) You presumably intend to raise that AttributeError. Here's a corrected version with some error reporting: >>> class Row: ... def __init__(self): ... self.__dict__["_values"] = {} ... def __getattr__(self, name): ... try: ... return self._values[name] ... except KeyError, e: ... print "tried to get", name ... raise AttributeError, str(e) ... def __setattr__(self, name, value): ... self.__dict__["_values"][name] = value ... >>> row = Row() >>> row is None 0 >>> row == None tried to get __eq__ tried to get __coerce__ tried to get __cmp__ 0 Without the "raise", __getattr__ returns None for __eq__, and the interpreter then tries to call it. Note that "is None" doesn't have this problem. Graham From martin at v.loewis.de Thu Sep 5 19:42:00 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Sep 2002 01:42:00 +0200 Subject: German Umlaut Problem with raw_input in IDLE References: <3D77C66F.4040305@aon.at> Message-ID: Gregor Lingl writes: > H?? Tsch?s [...] > TypeError: object.readline() returned non-string [...] > I must confess, I do not understand the error message. Apparently, IDLE returns a Unicode object, not a string object. Regards, Martin From bobx at linuxmail.org Wed Sep 18 13:56:22 2002 From: bobx at linuxmail.org (Bob) Date: 18 Sep 2002 10:56:22 -0700 Subject: Python equivalent to perldoc? References: Message-ID: <1001ff04.0209180956.359ce174@posting.google.com> "DG" wrote in message news:... > The contents of my f:\python22\pydoc.bat file: > > @f:\python22\python f:\python22\lib\pydoc.py %1 %2 %3 %4 %5 %6 %7 %8 %9 > > Rowdy Very nice...thanks it was just the bang in the head I needed. Bob From peter at engcorp.com Sat Sep 7 22:51:36 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 07 Sep 2002 22:51:36 -0400 Subject: Larry Wall's comment on python... References: <3d796c18@news.sentex.net> <3D7A9E1A.1171C857@ihug.co.nz> Message-ID: <3d7abb20$1@news.sentex.net> Gib Bogle wrote: > Peter Hansen wrote: > >>mmaddox at hcsmail.com wrote: >>>You must agree >>>that Python can lead you to horizontal scrolling in your editor - the bane >>>of user interface design. >> >>I definitely don't understand how Python, more or less than any other >>language, leads to more horizontal scrolling. > > Maybe he is referring to an effect of default editor tab size. Apparently not, according to an email, which just said that Python leads one to do this more than with other languages. My point is that indentation (the way I've done it anyway) looks *exactly* the same in C, Pascal, Python, or any other block-structured language, so I still have no idea why Python would feel any different in this respect for someone. Clearly I'm missing some point, but I still don't know what it is. C: if (expression) { statements; } Python: if expression: statements Pascal: if (expression) begin statements; end (or whatever... haven't written any for three years). The only thing that would make me exceed 80 columns with a language like this is if I couldn't define subroutines and call them, to keep the nesting from growing too large. Since all these languages allow that, I have no idea what is special about Python that leads to excessive indentation. Oh well, whatever. -Peter From paul at boddie.net Fri Sep 20 05:05:38 2002 From: paul at boddie.net (Paul Boddie) Date: 20 Sep 2002 02:05:38 -0700 Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <23891c90.0209190014.26c5bb9@posting.google.com> Message-ID: <23891c90.0209200105.52bf42fa@posting.google.com> aahz at pythoncraft.com (Aahz) wrote in message news:... > In article <23891c90.0209190014.26c5bb9 at posting.google.com>, > Paul Boddie wrote: > > > >In that case, what do you think of this module? ;-) > > > > http://www.boddie.org.uk/python/downloads/ScaledDecimal.py > > > >I'll gladly release this into the public domain, but some commentary > >would be nice - I fear that I may not have implemented it as well as > >the "numeric gods" might like. > > Can you clearly explain the differences between your module and > FixedPoint.py? If not, the numeric gods probably won't accept it. ;-) Well, it doesn't matter so much to me whether the numeric gods accept it or not, since I wrote it partly for my own amusement and partly to use it in other things, but the only thing that I can think of is that you can specify a negative "scale" in the 'get_scaled_decimal' function and have the resulting object round to the nearest 10**n, where n is positive. For example: get_scaled_decimal("270", -2) -> 300 Apart from that, it's all aesthetics and design decisions. It would be nice if FixedPoint had a 'round' method which returns another object, for example, but then it would be nice if I had been consistent with the parameters to 'get_scaled_decimal' and the 'ScaledDecimal' constructor: one uses a precision-like thing whereas the other uses an exponent: ScaledDecimal(1002, -1) -> 1002 * (10 ** -1) : real -> 100.2 : real get_scaled_decimal("100.2", 1) -> 100.2 : real I can't remember clearly enough why I didn't use FixedPoint, but it may have been in an earlier state when I investigated it before writing ScaledDecimal - this was around the time of the integer division wars, I think. Paul From huaiyu at gauss.almadan.ibm.com Fri Sep 20 14:34:41 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Fri, 20 Sep 2002 18:34:41 +0000 (UTC) Subject: [Help]: mailbox classes References: Message-ID: J. Li wrote: >Hi, > >I am trying to extract a message from a unix mailbox file. Python does >provide few classes for easy and uniform access. So it says! After >having read the libiary references, I went nowhere. > >Can anyone give me an example as how to use these mailbox classes and >what is it relationship with email.message classes. > >thanks I just figured this out yesterday following examples in spambayes project. The documentation is very fuzzy, but this works for me: from mailbox import PortableUnixMailbox as MB from email import message_from_file as get_msg def get_mbox(mfile): return MB(file(mfile), get_msg) if __name__ == '__main__': mbox = get_mbox('test.mail') msgs = list(mbox) msg = msgs[2] print msg['Subject'] print msg Huaiyu From marklists at mceahern.com Mon Sep 16 09:14:19 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 16 Sep 2002 08:14:19 -0500 Subject: "if x == None" raises "'NoneType' object is not callable" In-Reply-To: Message-ID: Comparison to None should generally be comparison by identity rather than equality: if x is None: or: if x is not None: not: if x == None: nor: if x != None: What you might consider is adding a __len__ magic method to your Row class like so: def __len__(self): return len(self.values) Then you can do this: r = Row() if r: ... else: ... Cheers, // mark - From aleax at aleax.it Wed Sep 18 09:57:08 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 13:57:08 GMT Subject: try except ImportError failing to catch error! References: <3d888514$1@news.sentex.net> Message-ID: Peter Hansen wrote: ... > catch it. If you want to catch *any* error in the imported > module, you'll have to do "except Exception, e" instead. > Unfortunately, then you'll also have ImportErrors in the mix, > so you won't know if the module could be found but had its > own error, or if the call to __import__ failed... That's trivially easy to remedy, thanks to the fact that you may have multiple except clauses in a try statement, and they're conceptually tried in order: try: themod = __import__(whatever) except ImportError, blah: print "Can't import (%s): %s" % (whatever, blah) except Exception, bluh: print "Some other problem: %s" % bluh The only problem is, the ImportError might not be due to the __import__ call itself -- it COULD be propagating from some errant import that the module 'whatever' names is trying to perform! Discriminating between the two cases does need using the traceback module, as you suggest for other purposes in another part of this post. Alex From Padraig at Linux.ie Wed Sep 25 10:46:55 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Wed, 25 Sep 2002 14:46:55 GMT Subject: Newbie References Question References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> Message-ID: <3D91CC1C.8040405@Linux.ie> Guy Rabiller wrote: > Hi, > > let say I have: > i1 = 1 > i2 = 2 > and > p = [i1,i2] > > How can I have: > p=[*i1,*i2] > rather than > p=[**i1,**i2] as it is curently ? > > ( Sorry for this nasty hybrid syntax ) I know what you mean, and being a newbie myself I thought it would do what you want by default? If you wrap them in lists then it does as you want: i1=[1] i2=[2] p=[i1,i2] i1[0]="one" >>> p [['one'], [2]] But I'm confused also as to why this doesn't happen by default for base types? I suppose when you do: i1=4 you're creating a new object for the i1 name to reference, so the p[0] name keeps the reference to the old object. Hmm I'm confused... > Textualy, how if I want that p[0] refere to the 'i1' container, and not to > the refererence it contains ? > > What I want is that if now I set: > i1 = 4 > that automaticaly: > p -> [4,2] > and not keeping [1,2] > > Thanks in advance. From thomas.heller at ion-tof.com Thu Sep 26 08:15:50 2002 From: thomas.heller at ion-tof.com (Thomas Heller) Date: 26 Sep 2002 14:15:50 +0200 Subject: Python threading? References: Message-ID: "Robert Oschler" writes: > Having written _many_ state machines in my life, which async programming > boils down to in one form or another, I feel it depends on the task. When > you have an async event driven model, the code that services a > "transaction-package" ends up spreading functionality that services the > "transaction-package" application's code landscape. This can frequently be > a headache. As an example of a "transaction-package", take all the steps > involved in servicing an incoming TCP connection, with custom authentication > of a user, and perhaps a header and data object transacttion or two, > finishing with a proper ending and cleanup of the transaction, and with > subsequent notification of all necessary modules and data structures of the > results of the transaction. For dessert add a centralized clean error > handler that can log errors propertly and gracefully recover the app > regardless of where in the distributed event flow the error took place. > > Contrast this with a simple procedure call where a linear series of function > calls are made, each with appropriate error handling and status adjustment, > in a pleasant centrally located manner. > I wonder if generators can come to a rescue here? Still trying to get them into my head... Thomas From sross at connectmail.carleton.ca Thu Sep 5 17:57:22 2002 From: sross at connectmail.carleton.ca (Sean Ross) Date: 5 Sep 2002 21:57:22 GMT Subject: Python Source Code Documentation References: Message-ID: Terry: Yes, I did mean the Python interpreter. And I will give your suggestion a try. Martin: I will check out both of those documents. Thank you both for your suggestions. From mertz at gnosis.cx Sun Sep 29 12:47:20 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Sun, 29 Sep 2002 12:47:20 -0400 Subject: Python's import: why doesn't it work? In-Reply-To: <9ac02e81.0209290839.4f4d6475@posting.google.com> References: <9ac02e81.0209290839.4f4d6475@posting.google.com> Message-ID: |Once again my attempt to profit from Python's vaunted productivity |increase has come to a screeching halt because some innocent thing |that one would reasonably expect to work in one line, intuitively, and |without even having to think about, turns into a nightmare already |lasting more than an hour, requiring numerous experiments, searching |through the documentation - both manually and using my editor's |find-in-files ... Perhaps you would be happier using a different programming langauge (one that works without consulting documentation, apparently). I hear there are a number of other languages out there. |>>> import templates.intro Perhaps you should look into the standard documentation on import paths (PYTHONPATH). I'm not really sure why you would imagine for a moment that any of those things you suggest would have any good effect.... Python is a programming language, not magical incantations that fulfills vague wishes. |Abject Defeat, Ask on Internet, Be Ridiculed by Peers for Not Managing |Basic Operation I would say that your post deserves ridicule. Not because you ask about "basic operation", but for its obnoxious and self-important tone. You catch more flies with honey than vinegar, y'know. |import intro |... and it would work. For real. The symbols were there. Not a peep |out of the interpreter. Yep. Almost surely that's because you tried it at some point with the CWD in the same place as intro.py. Yours, Lulu... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From timr at probo.com Thu Sep 12 01:04:23 2002 From: timr at probo.com (Tim Roberts) Date: Wed, 11 Sep 2002 22:04:23 -0700 Subject: Destructor never called ??? References: <76710511.0209111450.40999dd8@posting.google.com> Message-ID: muk_pr at yahoo.com (vb) wrote: >Hi, > I have the following code my problem is when I call any methods of > TCVector_Object the destructor never executes. > >I mean > >v = module.CreateTCVector() >del v; >//destructor runs. message shown .OK > >but >in > >v = module.CreateTCVector() >v.Append(123); >del v;//or closing python interpreter > >destructor never gets called. Any ideas? Yes. Don't put critical code in a destructor. When you delete "v", it removes the name "v" from your global namespace, and decrements the reference count on your TCVector_Objet to 0. That means that no one is currently referencing the object. However, Python is a garbage-collected system. Unlike in COM, an object is NOT destroyed as soon as its reference count goes to 0. Your object will only be destroyed if the garbage collector happens to run, and decides that it might be a convenient time to actually free up the space your object occupies. If the garbage collector doesn't run before Python terminates, there is no NEED to clean up memory, so the destructor will NEVER run. Do a google search for "deterministic destructor python"; you'll see the previous threads on this. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From chrism3 at cox.net Thu Sep 12 22:04:34 2002 From: chrism3 at cox.net (Chris McDonough) Date: Fri, 13 Sep 2002 02:04:34 GMT Subject: Coding Style: Quotes References: <20020912144710.GA78280@hishome.net> Message-ID: <3D8094C3.9040603@cox.net> I use single quotes most of the time, but that's just because I'm lazy and if I use single quotes I don't need to press the shift key so much. ;-) Michael Chermside wrote: > Oren Tirosh wrote: > >> On Thu, Sep 12, 2002 at 02:25:11PM +0000, John Waycott wrote: >> >>> I'm curious if others have adopted any standards for choice of single >>> vs. >>> double quotation marks to delimit strings. [...] >> >> >> The default repr of a string uses single quotes unless the string >> contains a single quote. Most of the time I use the same convention >> but I'm not 100% consistent. >> >> For docstrings I always use triple double-quotes even if the docstring >> fits in a single line. >> >> I use triple single-quotes to comment out blocks of code. This is very >> useful since "if 0:" would require re-indentation. >> >> Oren > > > Encouragingly, I use EXACTLY the same conventions and practices that > Oren does, having developed them independently for the same reasons. > > -- Michael Chermside > > > > From propadovic.nenad at debitel.net Thu Sep 19 18:13:37 2002 From: propadovic.nenad at debitel.net (Nenad Propadovic) Date: Fri, 20 Sep 2002 00:13:37 +0200 Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> Message-ID: <3d8a4a75@news.ivm.net> Dear everybody, thank you for all the good advice. I think I now have all the hints I need (or, at least, most of it). I will definitely start reading Steve Holdens book for some more basics. I will NOT think about Zope at the moment (seems to be the one opinion in common), but I will do a short evaluation on the other recomended techniques & technologies. This is a fun place to be! :-) Nenad From theoryboy at my-deja.com Wed Sep 4 10:09:37 2002 From: theoryboy at my-deja.com (Peter Saffrey) Date: 4 Sep 2002 07:09:37 -0700 Subject: efficient list merging References: Message-ID: Sorry, there's a mistake in my previous posting. The merged listing should be: mergelol = [['a'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j'], ['k', 'l', 'm'], ['d'], ['f', 'g']] ^^^^^^^^ I'd missed the last non-repeated sub-list from the second list. Peter From peter at engcorp.com Thu Sep 26 08:38:09 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 26 Sep 2002 08:38:09 -0400 Subject: html in xml problem References: <9a1d8b0f.0209260409.3b759cba@posting.google.com> Message-ID: <3D92FFB1.5133DEC7@engcorp.com> walter hoolwerf wrote: > > I need to place some HTML code in an XML file en process it with > python. The only relatively safe way to do something like this, and even then you can get in trouble, is to use the construct. The "nasty HTML" cannot contain the sequence ]]> but as long as you can guarantee that, this should be safe for embedding HTML, or almost anything, in XML. -Peter From aleax at aleax.it Wed Sep 18 10:00:10 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 14:00:10 GMT Subject: minimizing Tk programs to the taskbar References: <3D8872F1.87850856@optushome.com.au> <656913E3D19D40D2.0831BD5165F06A87.FDA870F87AEF2207@lp.airnews.net> Message-ID: Cameron Laird wrote: > In article , > > Alex Martelli wrote: > >Richard Tardif wrote: > >> Is there any way to minimize programs to the taskbar? I'm talking about > >> windows here. By taskbar I mean the area down in the bottom right > >> corner, near the clock, that shows icons for what proggies you've got ... > ? Alex and Richard, I think you'll want to experiment with > root = Tkinter.Tk() > ... > Tkinter.Wm.iconify(root) Nope: this (at least on Win/98 -- I have no other Win release at hand to try, but I don't think the difference matters here) minimizes the window in the normal way, NOT to the system-tray, which Richard described as "the area down in the bottom right" and (probably mis-)named "taskbar". > Alex' intuition that a lot of the operations people say they > want are platform- or window-manager-specific is certainly > apt. Sure, but Richard did say he meant Windows (though he probably should have uppercased that) -- that's pretty much an acknowledgment of being platform-specific. On Win in particular, crowding the system tray with a zillion icons was all the rage once -- so many programs did it, particularly device drivers and various daemons, as to make things more or less unusable. Win/XP now tries to help by hiding most of the system tray except icons used recently, unless one specifically 'opens' the tray. It's still somewhat of a mess (and becomes worse, the more programmers learn to use Shell_NotifyIcon:-), but that's another issue. Alex From rajarshi at presidency.com Fri Sep 20 14:53:07 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Fri, 20 Sep 2002 14:53:07 -0400 Subject: mod_python and authentication Message-ID: Hi, when I want to use the Publisher method from mod_python I set up the directory entry (in http.conf) like so: SetHandler python-program PythonHandler mod_python.publisher However, I would like to add authentication. So I add the lines: PythonAuthenHandler entry AuthType Basic AuthName "DANGER!!!" And then have a file called entry.py which has the function authenhandler, the username and passwd dialog popup from the browser, but after it authenticates it says that Directory index forbidden by rule: /var/www/secured/todo/ Ideally I would like the authenhandler to serve up a page (say by using abc.xyz.com:/form.py/details ). I have also tried this: before returning apache.OK I simply write the HTML using req.write(). However then I get the error: Directory index forbidden by rule: /var/www/secured/todo/ in the logfile. But I also get the page rendered along with the error message at the bottom of the page. Is this the right way to do it? Or is this possible using the Publisher method - if so, what prevents a user from simply typing the url and bypassing the authentication function? Thanks, From see_reply_address at something.invalid Wed Sep 18 19:52:53 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 19 Sep 2002 11:52:53 +1200 Subject: Getting data into an array in NumPy from an other object? References: Message-ID: <3D8911D5.8050000@something.invalid> Maurice van de Rijzen wrote: > Dear all, > I've encountered a problem. > In one object I've a function: > > class blah: > ... > ... > def GetData(self): > return self.data > > > Now I want to put his data into an instance of Numeric.array. You'll have to tell us more about the nature of your data object before we can give you much help! If it's a sequence (i.e. a list or tuple) or something which behaves like a sequence (i.e. len(data) and data[i] work) you should be able to just pass it directly to the Numeric.array constructor. If not, you'll have to tell us more about it. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From kowk at earthlink.net Tue Sep 17 02:24:29 2002 From: kowk at earthlink.net (Kow K) Date: Mon, 16 Sep 2002 23:24:29 -0700 Subject: Python on MacOS X 10.2: a warning and instructions In-Reply-To: Message-ID: <1F30F09A-CA06-11D6-8521-00050287C0A6@earthlink.net> Oh my heck, I probaby won't migrate to Jaguar for a while. I can't trust Apple these days. Now, Apple is such a shameless company that they don't care privileges of previous users. Why do 10.1.x users have to pay as much as $129??? No matter how tight their budget is, that sucks. Well, I will upgrade when it becomes Tiger. Sorry about this posting, which is totally unrelated to Python. Kow On Monday, September 16, 2002, at 03:25 PM, Russell E. Owen wrote: > MacOS X 10.2 (Jaguar) breaks the fink installation of Python (due to > moving the ncurses package). > > MacOS X 10.2 does include Python (at least if you install the > Developer's CD, not sure otherwise) but it has no readlines support > (i.e. no command recall) and no Tkinter support. > > I upgraded before I realized this, and needed python too much to wait > for the fink binary, so I spent a day and a half figuring out how to do > the installation (with help from the MacPython list). Instructions are > at > if you are unfortunate enough to need them. > > These instructions install a version that uses xfree86 (an X server) to > display windows. However, a release version of the native aqua version > of tcl/tk now exists (version 8.4.0) but so far the only binary > installer is for 8.4a4, an older version. The source installer comes > with no instructions and what I tried failed. If anybody gets Python > with Tkinter to worth with the aqua version of tcl/tk 8.4.0 under MacOS > 10.2, I would love instructions. > > -- Russell > -- > http://mail.python.org/mailman/listinfo/python-list > From hst at empolis.co.uk Tue Sep 3 05:05:24 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Tue, 3 Sep 2002 10:05:24 +0100 Subject: string reading bug in ActiveState Python 2.2 ? Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220CFB@hendrix.empolisuk.com> Axel Kowald wrote:[mailto:kowald at molgen.mpg.de] > > I'm using ActiveStates Python 2.2.1 under win2000 to read in the > attached text file and it seems that python is only reading > part of the > string. After > > fp = open("bla.txt") > z = fp.read() > print len(z), z > > I see that only 11 of the 15 characters have been read. I > know they are > non-printable characters, but that shouldn't matter, should > it ? Using > another python on one of our unix machines everything works > as expected > and all 15 chars are read in. Is that there something special about > windows that I should know, or is this a bug in ActiveStates Python ? > > Many thanks, > > Axel Kowald > The 12th of the fifteen characters is \x1a which is EOF on Windows in text mode (the default). Use fp = open("bla.txt", 'rb') and you will read all 15 characters. _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From greek_bill at yahoo.com Wed Sep 18 14:16:29 2002 From: greek_bill at yahoo.com (Morfeas) Date: Wed, 18 Sep 2002 19:16:29 +0100 Subject: SWIG and C++ Message-ID: I don't know if this is the right place to post this, but I couldn't find anywhere better. I'm trying to use SWIG to interface C++ and python, but I'm getting an error. Here's what I have : // Hello.h class Hello { public: Hello(double aa, int bb); double GetA(); double GetB(); private: double a; int b; }; // Hello.i %module Hello %{ #include "Hello.h" %} %include "Hello.h" Then execute : swig -proxy -c++ -python Hello.i g++ -c Hello_wrap.cxx -I/usr/include/python2.2/ g++ --shared Hello_wrap.o Hello.o -o Hellomodule.so -I/usr/include/python2.2/ Python 2.2.1 (#1, Apr 9 2002, 13:10:27) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Hello Traceback (most recent call last): File "", line 1, in ? ImportError: dynamic module does not define init function (initHello) >>> Any clues? SWIG generates a Hello_wrap.cxx, which has a #define SWIG_init init_Hello is this related? Is there any way to fix this? Thanks! Morfeas -- www.freecfm.com/m/morfeas From blackhole at notformail.invalid.de Tue Sep 24 11:46:23 2002 From: blackhole at notformail.invalid.de (Volker Apelt) Date: 24 Sep 2002 17:46:23 +0200 Subject: callback + __call__ + TypeError: unbound method; on non method References: Message-ID: Alex Martelli writes: > Volker Apelt wrote: > > > But I can't remove the .__call__ method from my > > Callback class. The method is essential for > > The problem is not with method __call__, as it gets called > with an instance. Rather, it's right here: > > > class Callback: > > """ > > """ > > _default_Func = call_me # class wide default callback function > > > > def __init__(self): > > """ """ > > self._m_func = Callback._default_Func > > Here, self._m_func is NOT a function -- it's an unbound method, > thus it's not callable unless the first argument is an instance > of the class (or any subclass thereof). > > When you fetch from a class an attribute that is a Python coded > function object, what you get is an unbound method object. This > behavior is intrinsic to Python's OO mechanisms. > > Remedy: have Callback._default_Func be just about ANY callable > except a Python-coded function object:-). In Python 2.2, the > built-in staticmethod is made just for the purpose: > > class Callback: > """ > """ > _default_Func = staticmethod(call_me) # class wide default callback > > and the rest can stay unchanged (haven't examined it in detail, but > this is the surely-buggy spot in your code and explains the traceback > that you report). Let me rephrase what you stated above. Callback._default_Func is *always* a method. Thats the way python understands this code. So Python below v2.2 can not store a function reference in a class static variable (c++ speak) and use it later as for function call. So, I have to upgrade to v2.2 and write: class Callback: """ """ _default_Func = staticmethod(call_me)# class wide default callback function def __init__(self): """ """ self._m_func = staticmethod(Callback._default_Func) def __call__(self): self._m_func() # << this will call call_me() ??? Thank you Alex, Volker -- Volker Apelt From aglyportREMOvethispart at nospam.yahoo.com Wed Sep 4 18:21:07 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Wed, 04 Sep 2002 15:21:07 -0700 Subject: Memory fault - core dumped while compiling 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> <3D765A05.6030004@nospam.yahoo.com> Message-ID: <3D768753.8030302@nospam.yahoo.com> Martin v. L?wis wrote: > Anton Graph writes: > > >>Did not even take nearly as long for it to coredump. With optionless >>configure build was going at least for a half an hour and this one >>bailed out pretty much right away... > > > Can you please try to run the resulting Python binary in a debugger > (say, dbx), and report a backtrace? > python -E setup.py build in gdb: (gdb) where #0 0x80016d06 in do_reloc () from /usr/lib/libc.so.1 #1 0x80016bec in _relocate () from /usr/lib/libc.so.1 #2 0x800181fd in _rtld () from /usr/lib/libc.so.1 #3 0x80015569 in dlopen () from /usr/lib/libc.so.1 #4 0x808e315 in _PyImport_GetDynLoadFunc () #5 0x8086ec0 in _PyImport_LoadDynamicModule () #6 0x8085372 in load_module () #7 0x8085ffb in import_submodule () #8 0x8085c01 in load_next () #9 0x808583e in import_module_ex () #10 0x8085988 in PyImport_ImportModuleEx () #11 0x80b7a61 in builtin___import__ () #12 0x80b629a in PyCFunction_Call () #13 0x80736dd in eval_frame () #14 0x80748b6 in PyEval_EvalCodeEx () #15 0x8075794 in fast_function () #16 0x80737a6 in eval_frame () #17 0x80748b6 in PyEval_EvalCodeEx () #18 0x80ab7cd in function_call () #19 0x809d8fc in PyObject_Call () #20 0x80a3225 in instancemethod_call () #21 0x809d8fc in PyObject_Call () #22 0x80759fc in do_call () ---Type to continue, or q to quit--- #23 0x80737c2 in eval_frame () #24 0x80748b6 in PyEval_EvalCodeEx () #25 0x8075794 in fast_function () #26 0x80737a6 in eval_frame () #27 0x80748b6 in PyEval_EvalCodeEx () #28 0x8075794 in fast_function () #29 0x80737a6 in eval_frame () #30 0x80748b6 in PyEval_EvalCodeEx () #31 0x8075794 in fast_function () #32 0x80737a6 in eval_frame () #33 0x80748b6 in PyEval_EvalCodeEx () #34 0x8075794 in fast_function () #35 0x80737a6 in eval_frame () #36 0x80748b6 in PyEval_EvalCodeEx () #37 0x8075794 in fast_function () #38 0x80737a6 in eval_frame () #39 0x80748b6 in PyEval_EvalCodeEx () #40 0x8075794 in fast_function () #41 0x80737a6 in eval_frame () #42 0x80748b6 in PyEval_EvalCodeEx () #43 0x8075794 in fast_function () #44 0x80737a6 in eval_frame () #45 0x80748b6 in PyEval_EvalCodeEx () ---Type to continue, or q to quit--- #46 0x8075794 in fast_function () #47 0x80737a6 in eval_frame () #48 0x80748b6 in PyEval_EvalCodeEx () #49 0x8075794 in fast_function () #50 0x80737a6 in eval_frame () #51 0x80748b6 in PyEval_EvalCodeEx () #52 0x8071542 in PyEval_EvalCode () #53 0x808bb8e in run_node () #54 0x808bb46 in run_err_node () #55 0x808bb0f in PyRun_FileExFlags () #56 0x808aee1 in PyRun_SimpleFileExFlags () #57 0x808a9f2 in PyRun_AnyFileExFlags () #58 0x8052a64 in Py_Main () #59 0x8052300 in main () #60 0x805224b in _start () Noone around here admits making any changes in hardware or OS to the box I'm building on. From b.maryniuk at forbis.lt Mon Sep 16 04:10:19 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 16 Sep 2002 10:10:19 +0200 Subject: CPAN for Python Message-ID: <200209161010.19478.b.maryniuk@forbis.lt> Hi. I "heard" that Python will have something like CPAN for Perl soon. Is there is something new and moving forward in this area? -- Regards, Bogdan "I know you believe you understood what you think I said, but I am not sure you realize that what you heard is not what I meant!" -- G.Romney From guy at lightwork.co.uk Thu Sep 19 11:34:56 2002 From: guy at lightwork.co.uk (Guy) Date: 19 Sep 2002 08:34:56 -0700 Subject: python on the mac. Message-ID: Hi I just managed to get sys admin to put an uptodate version of python on our macs. I normally stay well away from the things as I'm not use to there strange way of doing stuff (or should I stay different way of doing stuff.) I have a script which I created on a win32 machine, I now want to port it to a mac sys9x, python version 2.2.1. I've got the scripts over on to the mac with there modules and they run. Firstly when I was doing this I got an error which allowed me to open up the debugger (which I got the hang of, and quite liked the look of). Question : How do I open the debugger without having to get an error to start with ? The must be something quite obvious that I'm missing, perhaps the afternoon is not helping (dragging on and on.) I'm also having problems with command line arguments. Which I've been reading a lot of posted messages on here about them. Say I am running my script like this on win32 : dist_set.py -V 3 -L c:\error.log etc etc can, is it possible to run this under mpw like this ? One of the messages I read on the newsgroup said hold down the options button on the mac and double click on the script, to produce a window which can take unix style command line options. This only works if the script has been converted to a applet. Is there any way of running the python text file in python using the same idea ? (As the script I am wanting to run won't convert to an applet, comes up with an error and quits. no hint no nothing.) If I could run my script in the debugger, using correct command line args, then I might have a chance to see whats going on. Many Thanks Guy From magnus at thinkware.se Fri Sep 20 11:28:32 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Fri, 20 Sep 2002 17:28:32 +0200 Subject: [newbie] Calling Python from C++ References: <8L5i9.841$Ew4.62552@newsfep2-gui> Message-ID: <3D8B3EA0.6050500@thinkware.se> Morfeas wrote: > What I want to do though, is to execute a python script that operates on an > existing object (that may or may not have been instantiated from Python). > So my question is : How do I pass an object into the python script? ... > I'm kind of relying on SWIG to do all the data conversion to and from > python, so I don't really know much on this topic! I'm really as clueless as you are about this, but as far as I understand, there are better tools than SWIG to connect Python with C++. SWIG is really a C thing rather than a C++ thing, right? Boost and CXX comes to mind. See http://www.thinkware.se/cgi-bin/thinki.cgi/UsingPythonWithOtherLanguages -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus at thinkware.se From bloke at ii.net Sat Sep 14 23:10:24 2002 From: bloke at ii.net (Rob Hall) Date: Sun, 15 Sep 2002 11:10:24 +0800 Subject: confused with class inheritance Message-ID: <3d83fa2c$0$24041@echo-01.iinet.net.au> In a sample app, I have the following: >>> class a(sgmllib): pass >>> a >>> dir(a) [] >>> dir(sgmllib) ['SGMLParseError', 'SGMLParser', 'TestSGMLParser', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'attrfind', 'charref', 'commentclose', 'endbracket', 'entityref', 'incomplete', 'interesting', 'markupbase', 'piclose', 're', 'shorttag', 'shorttagopen', 'starttagopen', 'tagfind', 'test'] >>> b=a >>> dir(b) [] >>> Why doesn't dir(b) show the same as dir(sgmllib) ? Rob From ben at remove.Stanford.EDU Wed Sep 11 13:00:02 2002 From: ben at remove.Stanford.EDU (Ben Escoto) Date: Wed, 11 Sep 2002 10:00:02 -0700 Subject: Large file support and stat vs stat64 in extension modules References: Message-ID: On Wed, 11 Sep 2002 06:22:08 -0700, Skip Montanaro wrote: > Did you #include ? Yes, but perhaps I'm not including something else. Here is a short program (test.c): #include main() { struct stat st; if (stat("/home/ben/work/big/bigfile", &st) != 0) perror("Error"); else printf("OK\n"); } when I "gcc test.c; ./a.out" it says: "Error: Value too large for defined data type". I assume in my extension module the same thing is happening. What needs to be defined so that this works? Looking through posixmodule.c it doesn't seem to define __USE_FILE_OFFSET64 or __USE_LARGEFILE64, yet it gets things right. > Note that in posixmodule.c references are made to a > HAVE_LARGEFILE_SUPPORT macro. When #defined, it causes the output > struct to be interpreted differently (the sizes of some fields change). > You might scan through your configure.in file. If "long long" support > is present and sizeof(off_t) is greater than sizeof(long) and > sizeof(long long) is greater than or equal to sizeof(off_t), large file > support is assumed. I am using distutils so don't have a Configure.in. But I think there are two separate problems: firstly getting the stat() call to work without raising an error, and secondly interpreting the filled in stat structure. Perhaps I will have problems with #2 later, but I'm still on #1 for now. As far as I can tell HAVE_LARGEFILE_SUPPORT, off_t, and long long don't affect this first step. Thanks a lot for your help! -- Ben Escoto From sadams123 at optushome.com.au Mon Sep 30 19:23:07 2002 From: sadams123 at optushome.com.au (Steven) Date: Tue, 1 Oct 2002 09:23:07 +1000 Subject: Id, or stinky primo? References: <7A4m9.25416$V64.5149538@newsfeed.slurp.net> Message-ID: <3d98dcdc$0$23174$afc38c87@news.optusnet.com.au> "Bruce Edge" wrote in message news:7A4m9.25416$V64.5149538 at newsfeed.slurp.net... > Is the Id it really worth the $$$$? > I've been looking at a kona stinky primo, and it seems like a comparable > bike for less dough. > What's the general opinion out there? > Why is the Id better? I think you posted to the wrong group who makes the Id? what are you intending on doing with the bike? the the Kona doesn't look like something you'd want to take on a downhill run. Steven From jb at cascade-sys.com Tue Sep 10 17:12:25 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Tue, 10 Sep 2002 14:12:25 -0700 Subject: "str"(expr)"str" interpolation syntax References: Message-ID: <3D7E6039.9060809@cascade-sys.com> I don't see that your proposals materially improve upon "abc" + `x*3` + "def" which already works. Having previously used a number of languages where string concatination is implied by adjacent expressions and where numeric expressions in this context are automatically coerced to strings, I agree that having to explicitly spell out "+" and `` or str() seems a BIT tedious, at least at first. However, this is a case where I have to agree that it's no big deal and after using it for a while you get used to it. Regards --jb Beni Cherniavksy wrote: >Hi all. > >I was searching for a new interpolation syntax that would use quotes >for starting/ending the interpolated part (I don't feel comfortable >putting code inside unclosed quotes...) > >After contemplating some horrors like $"""str"expr"str""" or >$("str" expr "str"), I noticed that currently both "( and )" are >illegal (first because strings are not callable, second is a syntax >error). So I propose that a parenthesized expresion near a string would >imply concatenation. In other words, > "foo"(x * 3)"bar" >would be equivallent to > "foo" + str(x * 3) + "bar". >This works of course with only one side, e.g. "foo"(x) or (y)"bar" but in >longer cases it would be good style to add empty strings on either end, >e.g. ""(y)"bar". And of course it all works with single quotes too. One >of the benefits over current interpolation PEPs is that you can change the >quote type in the middle... > >It is slightly more verbose (especially when interpolating into tripple >quote strings: """foo"""(x)"""bar""") but it is more readable and >understandable (just extends the current concatenation of constant >strings), allows clear nesting of strings into the expr: > "foo"('%3d' % x)"bar" >and most importantly, you never need to remember arbitrary rules where the >interpolation ends... > >What do you think? > From llothar at web.de Sun Sep 1 10:32:29 2002 From: llothar at web.de (Lothar Scholz) Date: Sun, 01 Sep 2002 16:32:29 +0200 Subject: Python GUI References: <3d8d3c0.0208262339.e7bc02c@posting.google.com> <3D6FBB3B.5090700@river-bank.demon.co.uk> Message-ID: On Fri, 30 Aug 2002 19:36:43 +0100, Phil Thompson wrote: >Or take the Qt (and PyQt) approach and implement all styles on all >platforms and let the user decide on a global or per application basis >with a simple command line argument. Thats completely wrong it the user selects a style from the OS style manager. At least for MacOS Users this is very popular and then your QT application looks again like an alien. Same is true for WinXP From sfeil at io.com Fri Sep 20 11:51:06 2002 From: sfeil at io.com (Steven Feil) Date: Fri, 20 Sep 2002 15:51:06 GMT Subject: [Jython] serialization transient Message-ID: I would like to prevent Jython from attempting to write out unserializable variable within a class. Is there a Jython equivalent to the java keyword transient? ======================================================================== Steven Feil | Gram-pa, back at the turn of the .~. Programmer/Developer | century, why did people use an /V\ sfeil at io.com | operating system, when they were not // \\ | allowed to see the source code? (X_X) ======================================================================== From jb at cascade-sys.com Wed Sep 25 12:37:33 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 25 Sep 2002 09:37:33 -0700 Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> <3D911A1B.1000109@something.invalid> Message-ID: <3D91E64D.8030802@cascade-sys.com> Alan Daniels wrote: >Sometimes I wonder if Guido would have saved a lot of debate by declaring, >long ago, that Python code would never allow tabs in it, period. Which may >be a bit extreme, I'll admit. :-) > Ironically, Guido originally ruled (in the style guide, IIRC) that thou shalt use tabs and tabs are 8 spaces, "as god intentended them to be." Unfortunately, he later changed position to the present, unsatisfying, compromise position. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From phr-n2002b at NOSPAMnightsong.com Fri Sep 20 08:44:36 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Sep 2002 05:44:36 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> Message-ID: <7xn0qcvnij.fsf@ruckus.brouhaha.com> Magnus Lyck? writes: > Ok, you might say that it's not a big thing to write > > x = 5 * Decimal(2.43) > > instead, but it's not quite the same thing. It would have to be x = 5 * Decimal('2.43') From aldo at nullcube.com Sun Sep 15 00:40:24 2002 From: aldo at nullcube.com (Aldo Cortesi) Date: Sun, 15 Sep 2002 14:40:24 +1000 Subject: two or more whitespace regular expression? In-Reply-To: References: Message-ID: <20020915044024.GA21615@nullcube.com> Thus spake eugene kim (eugene1977 at hotmail.com): > i used this.. > > words = string.split(line, '['+string.whitespace > +']'+'['string.whitespace+']+') The string "split" method does not take regular expressions - you need to use the re module for that. Try the following: import re line = "a b c d e" print re.split(r"\s+", line) Read the re module documentation for more information on regular expression syntax. Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com From aleax at aleax.it Mon Sep 23 03:54:30 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 23 Sep 2002 07:54:30 GMT Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <7xwupf52jx.fsf@ruckus.brouhaha.com> Message-ID: Robin Becker wrote: ... > rules evolved before modern computers are mostly computable using > fingers and counting. In particular almost all the calculations have to > be with pre-specified precision and rounding rules. Right. > EG a bond pays fixed amounts of money at pre-specified intervals, no > calculations are involved at all. Of course when I want to compute the > yield or npv I need to do some arithmetic and FP is usually easiest and > faster as well. Wrong! At least, if you have to follow legally mandated procedures to post the yield, etc -- and at least in the EU there are quite a few cases where you do. For example, whenever you offer something for sale to the public on any kind of instalment-payment plan, you have to publish TWO different values for the interest rate that the buyer ends up paying, exactly because there are subtly different ways to compute such things and the legislators wanted to make VERY certain that no seller tries to skew the computation and thereby misinform buyers. The two ways of computing interest use the acronyms TAEG and TAEV in Italy -- I'm not sure what they refer to, exactly: in practice, everybody looks at the higher one of the two before entering into any financially substantial transaction (and/or for a LARGE discrepancy between them, to take as an indication that there is something fishy about the whole deal -- but fractions of a percent of difference are quite typical, and the numbers are posted with specified accuracy of two decimal digits, e.g. "TAEG 10.23%"). I don't think there's any degree of freedom about how you can perform these calculations -- the whole purpose of the legislation seems to be exactly to ensure that sellers do NOT get any freedom to choose what numbers to display in order to mislead buyers in any way. In particular, I think rounding procedures are strictly specified (but I don't know the exact details). > Anyhow it seems to me that BCD is pretty good only for additive type > calculations. I can't see that BCD is any better than FP at representing > 1/3 unless we go fully rational, but that's another story. Yes, but I don't see legal specifications to use such fractions; rather, I see specifications such as "18.75% of the sum" -- always a finite number of decimal digits. Your quoted paragraph at the start may explain why -- things must in principle be computable with "fingers and counting"... and, of course, "pre-specified precision and rounding rules", which are never expressed in terms compatible with binary floating-point hardware... always in terms of somebody conducting a decimal computation with finite numbers of digits. Alex From jh at web.de Fri Sep 27 03:46:35 2002 From: jh at web.de (Juergen Hermann) Date: Fri, 27 Sep 2002 09:46:35 +0200 Subject: [XML-SIG] well-formed xml In-Reply-To: Message-ID: On Thu, 26 Sep 2002 19:08:48 -0500, Mark McEahern wrote: >I'm obviously missing something because this seemingly innocent chunk of >xhtml: > > from xml.dom import minidom > > s = "search" This is not well-formed and thus not XHTML. ... en&q= ... is the correct form. Ciao, J?rgen -- J?rgen Hermann, Developer WEB.DE AG, http://webde-ag.de/ From e_fax_t at hotmail._ZAPME_.com Wed Sep 25 12:06:10 2002 From: e_fax_t at hotmail._ZAPME_.com (Justin) Date: Wed, 25 Sep 2002 18:06:10 +0200 Subject: readlines() and "binary" files References: <3d90cacf$0$30457$afc38c87@sisyphus.news.be.easynet.net> <9r8k9.46422$V7.11170409@twister.socal.rr.com> Message-ID: <3d91de2d$0$30457$afc38c87@sisyphus.news.be.easynet.net> > I think readlines() is just a shortcut for a very common task. Since your > task isn't quite as common, I think it would be a better idea to use > read() to read the whole thing, splitting the lines up by the 0x0d 0x0a > pair (CR NL). Good suggestion, Jeff, thanks. I did not not realise that even data read from a 'binary' stream could be split()'ed. Maybe someone else will have a use for this, and I wanted to correct what I had said: it's extra newlines and not carriage returns that the data contains. f = open('testdata.csv','rb') # swallow everything in memory block = f.read() lines = block.split( "\r\n" ) f.close() # free our in-core file copy asap del block for line in lines: # get rid of the odd extra NL line = line.replace( "\n", "_" ) fields = line.split(';') print len(fields) # now constant My biggest data file is about 8 megs, so reading it in one swoop is doable. Still I only actually need to look at about 120 bytes at a time, so that's rather overkill. If anyone can think of a more economical way of doing it (short of defining my own iterator), I'd be interested. Thanks. From magnus at thinkware.se Fri Sep 20 08:31:51 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Fri, 20 Sep 2002 14:31:51 +0200 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: <3D8B1537.4010803@thinkware.se> ChrisBarker wrote: > The only reason I can see > to not writing your class in Python is performance, and unless you are > doing a lot of calculations, that is probably a non-issue. Performance issues might well matter in large financial systems, but that's not the only reason. If we want a statement like x = 5 * 2.43 to yield an exact decimal number, and not a float, we can't get away with a Python class. Ok, you might say that it's not a big thing to write x = 5 * Decimal(2.43) instead, but it's not quite the same thing. And if someone would write x = Decimal(9.999999999999999) - Decimal(9.9999) they would not get what they expected (unless they expected 0.000099999999998). Ok, they could write x = Decimal('9.999999999999999') - Decimal('9.9999') but now it's starting to look pretty ugly compared to x = 9.999999999999999 - 9.9999 Python is claimed to use the principle of least surprise: Thus 1 / 2 is being changed from meaning 0 to meaning 0.5. Quite a few people have expressed their surprise over things like >>> 0.9 0.90000000000000002 and reported it as a bug. Floating point arithmetic is surprising to a lot of people. It's annoying when people report this behaviour as a bug. It's worse if it leads them to make buggy programs. Particularly if they are used at your bank! I've seen ambitious and appreciated programmers with a non-technical background doing things like "if (a == (b / 5))" in tools that create C++ using doubles for a and b. Python is in many ways an excellent language for people who are beginners at programming, or not full time programmers. It would be great if we could remove some more of the remaining stumbling blocks. What you see as a natural restriction, completely logic, is an evil, subtle and completely absurd bug to some people. I don't want to break a lot of existing code though. It's boring if we have to change a lot of 3.14 to 3.14e0. That's hardly acceptable before Python 3.0. But perhaps a command line argument or something like "import exact_arithmetic" could change the behaviour to using exact instead of floating point arithmetic. I guess we'd need a module anyway, to specify things. Like: >>> import exact_arithmetics as exact >>> exact.default_rounding(exact.UP) >>> exact.default_fractions(2) >>> exact.max_precision = 20 >>> 7.5/20 0.38 >>> From ianb at colorstudy.com Tue Sep 17 01:53:33 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 17 Sep 2002 00:53:33 -0500 Subject: Stackless Python, eventual merge? In-Reply-To: References: <3D854B7D.1060209@one.net> Message-ID: <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> On Mon, 2002-09-16 at 16:50, Martin v. Loewis wrote: > I looked at the old Stackless patches once, and spotted significant > amounts of unexplicable code - code that did not serve any obvious > purpose, was not documented, or clearly should have been removed. So > the old Stackless patch was incomplete for integration into Python - > it would have taken efforts to complete it, and to work with Python > maintainers to integrate it. Nobody went through this effort (and > again, I don't blame anybody for not doing that). > > >From a shallow inspection, the code merely looked complex - but it > really was complicated, and complex is better than complicated. But it doesn't seem like complexity was ever the fundamental problem -- the complexity could have been dealt with, but I don't believe there was ever any indication that if it was simplified or documented that it would get into standard Python. It has been simplified, but I don't think that changes anything with regard to getting it into standard Python -- the same barriers still exist. It's simplification just means that it might be easier (and more viable) to continue to maintain a forked version. Ian From jkraska at san.rr.com Sat Sep 28 21:45:57 2002 From: jkraska at san.rr.com (Courageous) Date: Sun, 29 Sep 2002 01:45:57 GMT Subject: What does Python fix? References: <3d95fb09@news.vip.fi> Message-ID: <1hmcpusq28e8fnbpkashc5coh5n2iot98d@4ax.com> >After studying Python for 2 years I myself have >recently switched to DrScheme because I have no interest >relearning C to write extensions to Python. > >What an eye opener it has been to study scheme... Scheme continuations are pretty cool. A fair criticism of Python. "Python is not for that," applies to the degree that you can't get Python to work without extensions for certain classes of compute-bound problems. OTOH, I've prototyped whole systems under Python in order to get complex design right. One such system, later ported fully to C++, actually really wasn't all that much faster. It was fast enough to matter (2 hours of compute time is indeed better than 5), but for small tasks, the limit formula pushes the practical difference to zero. What's the difference between 20 and 4 milliseconds? In *user time*, that's no difference. C// From andrewa at calibredigital.com Mon Sep 23 14:23:53 2002 From: andrewa at calibredigital.com (Andrew Alzner) Date: Mon, 23 Sep 2002 14:23:53 -0400 Subject: parsing tabs in a string References: Message-ID: <008701c2632e$5f54e5c0$025e10ac@calibredd.com> Thanks everyone for the quick response! This helps out a lot. I will be using the string.split to make it more manageable. Andrew ----- Original Message ----- From: "Mark McEahern" To: "Andrew Alzner" ; Sent: Monday, September 23, 2002 1:18 PM Subject: RE: parsing tabs in a string > [Andrew Alzner] > > I'm trying to parse information extracted from a spreadsheet > > which is tab separated. Here is a simplified version of what I have: > > > > list=['"103-01a-17"\t2\t33\t256\t227\n'] > > y=list[0] > > print y.find("\t") > > print y.find("\t",1) > > Don't use list as a variable name, you'll stomp all over the builtin list. > Rather than finding each tab, why not split on tabs: > > a = ['"103-01a-17"\t2\t33\t256\t227\n'] > y = a[0] > for x in y.split("\t"): > print x > > // m > From ods at strana.ru Tue Sep 24 11:43:58 2002 From: ods at strana.ru (Denis S. Otkidach) Date: Tue, 24 Sep 2002 19:43:58 +0400 (MSD) Subject: hex numbers?? In-Reply-To: <574747556.1032881448716.JavaMail.nobody@webmail2.brturbo.com> Message-ID: On Tue, 24 Sep 2002 jubafre at brturbo.com wrote: > >>> y=hex(x) > >>> y > '0xa' > >>> type(y) > > > the hex() function put the hexadecimal number in a string type > like this '0xa', but the real hexadecimal number of 10 is 'a', > why python puts a '0x', and how i can get just the real > hexadedcimal number, for example i want to write in a file 10 > in hexadecimal, but if i use hex(10) the result is '0xa' as a > string, is not the same as 'a'. > > '0xa' != 'a' > > x = [12,13,14] > y = ['0xc', '0xd', '0xe'] > > hex() create a list of string, how i can write in a file just > the real value of hexadecimal number? >>> hex(10)[2:] 'a' >>> '%x' % 10 'a' >>> '%X' % 10 'A' -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From dan65536 at hotmail.com Wed Sep 18 22:20:03 2002 From: dan65536 at hotmail.com (daniel w. moore) Date: 18 Sep 2002 19:20:03 -0700 Subject: conditional expressions Message-ID: <33b491f.0209181820.17b6ea70@posting.google.com> It's occurred to me after some brainstorming on the subject that the C/perl construct a ? b : c can be arranged like this in python: (a and [b] or [c])[0] or, putting into lambda form, and using tuples for a slight efficiency gain: cond_switch = lambda a,b,c : (a and (b,) or (c,))[0] Has anyone put this to good use, i wonder? Or have I just made a daring and heroic discovery in my own particular idiom ;) (http://www.stone-dead.asn.au/movies/holy-grail/scene-15.html) From kp at kyborg.dk Fri Sep 20 04:31:34 2002 From: kp at kyborg.dk (Kim Petersen) Date: Fri, 20 Sep 2002 10:31:34 +0200 Subject: Python embedded - linking problem on Linux - RESOLVED References: <3D57BD22.8090305@kyborg.dk> Message-ID: <3D8ADCE6.5020404@kyborg.dk> Thank you to everyone who helped me on this one.... The trouble *was* the Cobol call to dlopen() ... it did _not_ have the RTLD_GLOBAL flag set on their load of my extention (their own way of extending). (After some quaralling over dlopen() i finally got them to send me a patched version of their runtime with RTLD_GLOBAL to test). Conclusion: in the *first* call to a chain of dynamic objects, it is neccesary to do dlopen() with RTLD_GLOBAL - otherwise python will not be able to export its symbols to its own symbols. -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S IT - Innovationshuset Havnepladsen 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From davids at simutility.com Thu Sep 19 15:40:28 2002 From: davids at simutility.com (Dave Swindell) Date: 19 Sep 2002 12:40:28 -0700 Subject: Controlling IE 5.x from Python: HTTP Status Codes Message-ID: I'm trying to control IE 5.5 from Python and ham having some problems. Using PythonWin with Mark Hammond's COM interface extensions, I've been able to launch IE and navigate to a specified website using the following code: from win32com.client import constants, Dispatch, DispatchWithEvents ie=Dispatch("InternetExplorer.Application) ie.Visible=1 ie.Navigate("http://www.python.org",2) This all works fine, except that I'd like to know the HTTP Status Code that resulted from the Navigate automation interface in IE. Using the DispatchWithEvents call, I've been able to trap OnDocumentComplete and OnNavigate2Complete events, but these don't appear to provide you with access to the HTTP status codes resulting from the Navigate call. IE 6.0 has a NavigateError event which, according to the documentation, will allow you to access the HTTP status code, but the project I'm working on needs to use IE 5.0/5.5. Anyone else run into this issue or even better, found a way around it? Thanks, -- Dave Swindell davids at simutility.com From mstenner at phy.duke.edu Thu Sep 12 09:32:21 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Thu, 12 Sep 2002 09:32:21 -0400 Subject: how can i make a executable program with a python2's script In-Reply-To: ; from jingguoming@yahoo.com.cn on Wed, Sep 11, 2002 at 07:29:00PM -0700 References: <3D7924BF.805@motorola.com> Message-ID: <20020912093221.A6377@phy.duke.edu> On Wed, Sep 11, 2002 at 07:29:00PM -0700, jgm2163 wrote: > Michael Stenner wrote in message news:... > > On Fri, Sep 06, 2002 at 04:57:19PM -0500, Stephen Boulet wrote: > > > You can put > > > > > > #/usr/bin/env python > > > > > > at the top of the file and do a chmod +x file. Is this the answer to the > > > right question? > > > > Although since you're trying to use python 2.2.1 on a RHL 7.2 box, you > > may need to make that > > > > #!/usr/bin/env python2 > > > > Otherwise, you'll get python 1.5.2, which can lead to confusing errors. > > > > -Michael > > > jgm2163 wrote: > > > > os :RedHat 7.2 > > > > Python :Python2.2.1 > > > > > > > > now,i had writen a python's script (extend with .py) > > > > how can i make a executable program on RedHat 7.2? > > sorry,i want to make a release program on the computer that donot > install python2.1 (because that python1.5 was installed on the redhat > 7.2 defaultly). Well, the most practical way is to just go ahead and install the python2 package under RHL 7.2 (have your program "Require" it in its rpm). If that's not feasible for you, then probably the easiest thing is to backport your program to 1.5.2. After that, the next easiest (and basically only other) thing you can do is to include python 2.1 (or later) in your program. I don't know of any tricky ways to do that. You would just have to include python and all of it's files (or all the ones YOU use anyway) in your program's rpm in such a way that they don't conflict with any other programs/rpms. Realistically, this is just silly. Your admin should probably be willing to install python2. -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From phr-n2002b at NOSPAMnightsong.com Mon Sep 23 23:53:23 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 23 Sep 2002 20:53:23 -0700 Subject: Python threading? References: Message-ID: <7xfzw0avrg.fsf@ruckus.brouhaha.com> Mark Hammond writes: > A "one thread per connection" model is doomed from the start - > therefore, in most applications, I would consider 5 threads a large > number - particularly when all are actively doing something. OTOH, if > you are willing to accept that your first version will accept a max of > ~20 connections, the brain-power saved by using threads beats the > additional OS overhead by a mile ;) The new Linux native thread implementation was recently benchmarked running 100,000 simultaneous threads on a 1 GB machine. Starting all the threads and closing them took around 2 seconds. From fperez528 at yahoo.com Sat Sep 7 17:50:20 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sat, 07 Sep 2002 15:50:20 -0600 Subject: Smoothing a discrete set of data References: <3csmdso5.fsf@morpheus.demon.co.uk> Message-ID: Tim Churches wrote: > AFAIK, there is no native Python package which > implements a > comprehensive range of regression and smoothing techniques, but I can > highly > recommend the R package for statistics and statistical graphics - this > mature, free, open > source package has more statistical facilities than you are ever likely > to need. While not as comprehensive as R in its statistical coverage, SciPy probably has enough in it for what the OP wants (which sounded fairly basic). Quick linear (in the parameters) fits are easily done with scipy, plotting, simple smoothing (if he wants to), etc. I know R is industrial-strength statistics, but it sounds like more than what the OP needed. cheers, f. From sperry at newcreations.info Wed Sep 25 13:05:41 2002 From: sperry at newcreations.info (Sperry Russ) Date: Wed, 25 Sep 2002 13:05:41 -0400 Subject: Python and Scite Message-ID: <200209251305410290.00B482C8@newcreations.info> Hello, I am new to programming. I have downloaded Python 2.2.1 and Scite 1.48 to learn how to program. I am trying to configure my Scite so that it will run the python files by using go. When I try to do this i get a message in the second window at the bottom -- unable to find file. I have tried configuring the global options and have failed can anyone help me? I need a step by step example if you can because I cannot understand it according to the documentation that came with Scite I installed scite like this: D:\Scintilla Text Editor\SciTE because I keep programs in a seperate partition. Thanks, Sperry Russ From polux2001 at wanadoo.fr Mon Sep 2 09:52:21 2002 From: polux2001 at wanadoo.fr (polux) Date: Mon, 02 Sep 2002 15:52:21 +0200 Subject: Does IDLE handle unicode? References: Message-ID: <3D736D15.5040800@wanadoo.fr> Edward K. Ream wrote: > IDLE took an exception writing a .py file containing the copyright > character. This happened a while ago; IIRC, I lost the file. > > Is this a known problem? I see nothing about this in the FAQ. > > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edream at tds.net > Leo: Literate Editor with Outlines > Leo: http://personalpages.tds.net/~edream/front.html > -------------------------------------------------------------------- > > > Read in the FAQ : ---------------------------- 4.102. UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128) This error indicates that your Python installation can handle only 7-bit ASCII strings. There are a couple ways to fix or workaround the problem. If your programs must handle data in arbitary character set encodings, the environment the application runs in will generally identify the encoding of the data it is handing you. You need to convert the input to Unicode data using that encoding. For instance, a program that handles email or web input will typically find character set encoding information in Content-Type headers. This can then be used to properly convert input data to Unicode. Assuming the string referred to by "value" is encoded as UTF-8: value = unicode(value, "utf-8") will return a Unicode object. If the data is not correctly encoded as UTF-8, the above call will raise a UnicodeError. If you only want strings coverted to Unicode which have non-ASCII data, you can try converting them first assuming an ASCII encoding, and then generate Unicode objects if that fails: try: x = unicode(value, "ascii") except UnicodeError: value = unicode(value, "utf-8") else: # value was valid ASCII data pass If you normally use a character set encoding other than US-ASCII and only need to handle data in that encoding, the simplest way to fix the problem may be simply to set the encoding in sitecustomize.py. The following code is just a modified version of the encoding setup code from site.py with the relevant lines uncommented. # Set the string encoding used by the Unicode implementation. # The default is 'ascii' encoding = "ascii" # <= CHANGE THIS if you wish # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] if encoding != "ascii": import sys sys.setdefaultencoding(encoding) Also note that on Windows, there is an encoding known as "mbcs", which uses an encoding specific to your current locale. In many cases, and particularly when working with COM, this may be an appropriate default encoding to use. ------------------------------- try to use mbcs on windows i did it and it works From gherron at islandtraining.com Tue Sep 10 21:28:02 2002 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 10 Sep 2002 18:28:02 -0700 Subject: Maybe a dumb question In-Reply-To: <3D7E6B0E.4060709@caramail.com> References: <3D7E6B0E.4060709@caramail.com> Message-ID: <200209101828.02617.gherron@islandtraining.com> On Tuesday 10 September 2002 02:58 pm, Fabien HENON wrote: > I have written an editor for Povray using Python, Tkinter and Pmw > > It is available at : > > http://pyvon.sourceforge.net > > The software includes one main file and 6 others which are for the > language customization. People can choose between French, English, > German,... > All the translations for these languages are stored in files called > menu_francais.py, menu_english.py, menu_deutsch.py ....when the editor > is started. > > I would like to clean the directory a bit and put all these 'languages > files' into a sub-directory called Lang. > How do I tell python to look into a particular sub-directory when > importing a file. > > I tried the os.path.join syntax, but to no avail. Two possibilities: 1. You can manipulate the search path for imports thus: import sys langDir = '...whatever...' sys.path.append(langDir) import Whatever where the calculation of the path to the language directory is something like: thisPyFile = os.path.join(os.getcwd(), sys.argv[0]) thisDir = os.path.normpath(os.path.dirname(thisPyFile)) langDir = os.path.join(thisDir, 'Lang') 2. Use the package interface for the directory Lang: Create an empty file Lang/__init__.py. Then you can import Lang/menu_francais.py like this: import Lang.menu_francais.py Look through the standard library for many examples of (non empty) __init__.py files. Gary Herron From mak at trisoft.com.pl Mon Sep 30 17:46:42 2002 From: mak at trisoft.com.pl (Grzegorz Makarewicz) Date: Mon, 30 Sep 2002 23:46:42 +0200 Subject: Printing with python References: Message-ID: <3D98C642.3090003@trisoft.com.pl> Florian Schulze wrote: > Hi! > > I would like to know what solutions exist for printing (on paper) with > python. Preferable would be a crossplatform approach, but only for Windows > would be good enough. I also thought about using the reportlab pdf lib and > using the free Acrobat Reader for preview and printing. It has a nice API > and I don't think it will be too hard to send it to Acrobat Reader. > > Any suggestions or thoughts about this? > > Regards, > Florian Schulze > > > try DDE connection to AR: import os import win32ui import dde fname=os.path.join(os.getcwd(),'demo.pdf') server = dde.CreateServer() server.Create("PyAcroview") conversation = dde.CreateConversation(server) conversation.ConnectTo("acroview", "control") conversation.Exec("[DocOpen(%s)]" %fname) -- You can print, select pages and documents, ... mak From Dick.Zantow at lexisnexis.com Tue Sep 17 11:01:54 2002 From: Dick.Zantow at lexisnexis.com (rzed) Date: Tue, 17 Sep 2002 11:01:54 -0400 Subject: Good book choice? References: <3D873E8F.7060501@diespammerdieuselesspython.com> Message-ID: "Rob Andrews" wrote in message news:3D873E8F.7060501 at diespammerdieuselesspython.com... > > > > This isn't directed at the book mentioned (which is why I didn't quote > > its name in this rant), rather at all books which come with CDs. I hate > > it when books come with CDs. I'm perfectly capable of downloading the > > source code used in the book, and in fact I prefer to hand-type it while > > reading from the book anyway, to make sure I see every part of the > > code. When a book comes with a CD, it is cumbersome to read portably, > > which is the whole advantage of books, unless you take the CD out. And > > if I take the CD out, then there is no doubt that it will get lost, or I > > will be unable to return the book if dissatisfied, etc. Plus, you can't > > tell me that the inclusion of a CD and the envelope/publishing used to > > include the CD doesn't add a few units of currency to the book's cost. > > > > Poke this opinion full of holes, but when I buy a book, I want a book, > > not a software package. The book should be good enough to stand on its > > own without the "bonus" material on CD. I think twice about buying a > > book that comes with a CD, to tell you the truth. > > > > All perfectly valid sentiments, of course. But for the village in Nepal > lacking bandwidth because they are still six months away from having a > phone line (not as far-fetched an example as it may seem), an entirely > different set of considerations may be found. > > I find myself on the middle path on this issue, since I rarely have > personal use for the CDs, but find that they do make it easier to > distribute Python in my fits of zealous advocacy. I have bandwidth, but > no burner, and some are more interested in hearing me out if they don't > have to face a long (in some cases, expensive) download before they even > get to see if they would be interested. > The further aspect to it is that code written in a book may be dependent on the environment the author is working with. Some or all of it may still be valid a couple of releases later, but if things are not working, it is useful to be able to set up the *same* environment the author had to verify that the code is not the problem. Otherwise you're left translating to the current version of things, and then debugging code that doesn't correspond to what the author wrote to begin with. -- rzed From sismex01 at hebmex.com Thu Sep 26 17:32:13 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 26 Sep 2002 16:32:13 -0500 Subject: Who knows somefunction? Message-ID: > > Hi Pythonistas! > > Is there a function in Python > for which > > something is (id(something)) > > returns invariably true? > > Gregor > Woo, this is dangerous, kinda like turning an arbitrary (*void) into whatever you like (well, you can). So, this function would be the equivalent of a type cast, only in Python. Nope, I don't like it. Why'dyawanna something like this, anyhow? :-) -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From fperez528 at yahoo.com Fri Sep 27 21:55:07 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 27 Sep 2002 19:55:07 -0600 Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <7nHk9.172208$pX1.6117207@news2.tin.it> Message-ID: Mike Rovner wrote: > > "Terry Reedy" wrote in message > news:t_3l9.334924$AR1.14880141 at bin2.nnrp.aus1.giganews.com... >> na=1; np=3; nl=1; ng=0 >> print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\ >> (na, na!=1 and 's' or '', np, np!=1 and 's' or '', nl, nl!=1 and 's' >> or '', ng, ng!=1 and 's' or '') >> >> Found: 1 apple, 3 plums, 1 lemon, and 0 grapes. >> >> Alternatives to this 'risky' construct: >> 1. forgo the nicety of correct English output >> 2. nest if/else four levels deep to choose correct variant of 16 print >> statements (ugh) >> 3. precalculate 4 suffixes and store in 4 temp vars with 4 if/else's >> (8 or 16 lines); >> though clearly superiour to 2), this is still tedious with some >> risk of typo error. >> > 4. Try: > use_s=('','s') > print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\ > (na, use_s[na!=1], np, use_s[np!=1], nl, use_s[nl!=1], ng, use_s[ng!=1]) Why not just a simple function? In [23]: plur=lambda s,n:'%s %s' % (n,s+('','s')[n!=1]) In [24]: plur('cat',0) Out[24]: '0 cats' In [25]: plur('cat',1) Out[25]: '1 cat' In [26]: plur('cat',9) Out[26]: '9 cats' In [27]: na=1; np=3; nl=1; ng=0 In [28]: print "Found %s, %s, %s, %s" % (plur('apple',na),plur('plum',np), ....: plur('lemon',nl),plur('grape',ng)) Found 1 apple, 3 plums, 1 lemon, 0 grapes If the list is big the above can easily be automated with a map or a list comprehension. Cheers, f. From cbbrowne at acm.org Thu Sep 5 16:24:18 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 5 Sep 2002 20:24:18 GMT Subject: Graham's spam filter References: <3D647B4B.28D9BF04@alcyone.com> <3D655AE6.A097AA25@alcyone.com> <3D770156.2E55864C@alcyone.com> <3D77AC75.B9B7F27@alcyone.com> Message-ID: Quoth Erik Max Francis : > Christopher Browne wrote: >> Have you considered simply replacing strings that appear to be >> base64-encoded with a token like "base64-text"? >> >> That allows the database to at least be aware that the spam >> commonly contains base64 data. > > Well, that really depends on what your goal is. Again, if you're > one of those people that has a very tight circle of email buddies > and so essentially any unsolicited email is by definition spam, then > you can tighten down your spam filter in all kinds of very powerful > ways. > > I, as I've mentioned before, receive unsolicited email from my Web > sites and various projects, and so unfortunately don't have the > luxury of doing this. So I need to support receiving email from > faraway lands and unknown email addresses as well as trying to > vigorously filter spam. > > Fact is, unfortunately, lots of people send legitimate email that is > MIME encoded. No, I am certainly _not_ defining "all unsolicited email" as being spam. Quite to the contrary, I receive quite a lot of interesting email from unexpected sources. Very little of it, statistically speaking, is heavily MIME encoded, mind you... The MIME encoded stuff does _not_ solely consist of "base64" text; it also has header information that at least _suggests_ file type info. A recent virus email contained: Content-Type: application/octet-stream; name=snoopy.exe Content-Transfer-Encoding: base64 Content-ID: another had: Content-Type: audio/x-wav; name=bgcolor.exe Content-Transfer-Encoding: base64 Content-ID: I get legitimate mail that contains base64 material; it _never_, in my experience, consists solely of base64 material. It always contains _some_ sort of commentary, and whether that commentary came as text or as HTML, it's quite nicely sufficient to distinguish the "unexpected resumes from Russia" from the email viruses. >> -> Supposing there is interesting text encoded (such as source code >> for a virus) inside the base64 stuff, it _would_ be useful to >> decode it; >> >> -> Supposing the base64 stuff is basically just a GIF/JPEG/PNG, or >> something else that doesn't contain "interesting text," you'll >> have not much of value from the decoding process. >> >> Making the "tokenizing" step a tad smarter (e.g. - recognizing "this >> is likely base 64" and collecting stats on numbers of lines of base64 >> material) requires minimal added effort, and I expect it would buy you >> _most_ of the benefits of decoding. > > Spammers are hitting upon the strategy, though, of sending emails in > which the body consists of nothing but a completely encoded base64 > MIME part. So in that case, the entire body of your message would > consist solely of your "base64encoded" token. So in the general > case of any kind of spam filter (not just limited to a Graham > filter), it's questionable how useful this will be, unless you plant > to always filter against that token, presuming it to always indicate > spam. I've been using naive Bayesian filtering for years; I don't assume that _any_ particular token indicates _any_ particular result. I'm not interested in the "rule-based" stuff, only in the schemes based on statistical analysis. And the body of the message would most certainly NOT consist solely of a "base64encoded" token. The body portion would consist of: - Various "Content-foo" tokens - The header information that these documents _do_ contain; they normally contain an HTML header. - Not "solely a base64encoded token," but rather some sort of count involving _many_ base64encoded tokens. The notion that it's "solely one token" is in your imagination, not in reality. There are _no_ "presumptions" being made here. What I'm saying, that apparently isn't being read, is that I expect that collecting stats on the numbers of "base64 lines" is likely to be _nearly_ as useful as decoding the contents, and that it's _certainly_ simpler and faster. If it _proves_ insufficient as a discriminator (please feel free to direct any nonsense about 'presuming anything to always indicate spam' to /dev/null), then it might prove necessary to _try_ to analyze the contents. _Trying_ to decode and analyze the contents may still prove a futile exercise. You won't get much useful material out of such common MIME contents as graphics, PDFs, ZIP files, and audio files, without going to even _more_ gratuitous lengths to analyze them that might very well make you vulnerable to DOS attacks directed against the mail filter itself. -- (reverse (concatenate 'string "gro.mca@" "enworbbc")) http://www.ntlug.org/~cbbrowne/nonrdbms.html "I will not send lard through the mail" ^ 100 -- Bart Simpson From mark.charsley at REMOVE_THIS.radioscape.com Wed Sep 11 07:04:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Wed, 11 Sep 2002 12:04 +0100 (BST) Subject: Embedded Python implementation References: Message-ID: In article , tagith1394 at hotmail.com (Evan) wrote: > Hello, > > I am currently trying to embed Python in an application I am writing, > and all is going well, except for one inexplicable bug.. > > When I pass a variable (pointer to a string) to PyRun_String, it will > always error on line 2, character 5.. regardless of what is actually on > the line in that spot (for that matter, even if there is no line 2).. When I had a problem like that it was because an error had occurred in a previous call into the python DLL, and hadn't been cleared. As a result my call to python also failed, but the error message I retrieved was to do with the prvious call. -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From tismer at tismer.com Sat Sep 21 00:22:08 2002 From: tismer at tismer.com (Christian Tismer) Date: Sat, 21 Sep 2002 06:22:08 +0200 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> Message-ID: <3D8BF3F0.4000204@tismer.com> Dan Bishop wrote: > Magnus Lyck? wrote in message news:<3D8B1537.4010803 at thinkware.se>... > >>ChrisBarker wrote: >> >>>The only reason I can see >>>to not writing your class in Python is performance, and unless you are >>>doing a lot of calculations, that is probably a non-issue. >> >>Performance issues might well matter in large financial >>systems, but that's not the only reason. > > > Please name one other real-world situation in which decimal arithmetic > is actually *needed*. There is no reason to argue about that. Decimal arithmetic is exact for most of the operations bankers require. They have been demanding for it since decades, and they will not drop it. Having "no rounding issue at all" is better than any consideration about neglectible errors, it cannot be beaten, since *they* understand it. Cannot be discussed. They pay the bill. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From fperez528 at yahoo.com Mon Sep 23 21:43:22 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 23 Sep 2002 19:43:22 -0600 Subject: e vs exp()? / financial applications References: Message-ID: Terry Reedy wrote: > Although w appears to be exactly represented, it must not be. Cute > example. > In this case it's not a problem of the exactness of w's representation, but the exactness of the intermediate results. It turns out that basic properties of common arithmetic operations, such as the associativity of addition, are NOT valid in floating point: (a+b)+c != a+(b+c) in a computer. It may appear to be true in many cases, but it is not in general, as the above example showed. A classic textbook example: In [29]: eps = 1e-16 In [30]: (1+eps)+eps Out[30]: 1.0 In [31]: 1+(eps+eps) Out[31]: 1.0000000000000002 Any decent text on numerical analysis discusses this at length. While for 'common' day to day things one can gloss over this, there are many instances where it will bite you hard. Cheers, f. From tdelaney at avaya.com Thu Sep 19 03:02:25 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 19 Sep 2002 17:02:25 +1000 Subject: Stackless Python, eventual merge? Message-ID: > From: martin at v.loewis.de [mailto:martin at v.loewis.de] > > It is better than that: it does not need to be "switched off". Even if > switched on (at build time), it won't start copying slices of the > stack. An application actively has to import one of the modules, and > to call a function in those modules, before you need to get nervous. The problem of course is if you import a module which itself uses stackless. Currently, there are limited ways in which simply importing a module can kill Python. This would add another way. Obviously all such modules should be documented, but ... I'm not saying I'm against Stackless - quite on the contrary. However, it is something which needs to be considered *very* carefully. At the very least, PyChecker should warn about Stackless (even if it never gets into the core ;) Tim Delaney From grabiller at 3dvf.net Sun Sep 8 06:45:32 2002 From: grabiller at 3dvf.net (Guy Rabiller) Date: Sun, 8 Sep 2002 12:45:32 +0200 Subject: untrusted dynamic module: win32api References: Message-ID: [Mark] > It appears that SoftImage is configuring ActiveScripting for "untrusted" > scripts - ie, SoftImage is requesting the scripting engine switch into > untrusted mode. Thus, you really need to ask SoftImage is the > application can be configured to not request restricted execution mode > of the language After a closer look, it seems that this has nothing to do with Softimage, but with MSIE. Even if I include ( for exemple ): in a simple html file, then launching it in MSIE, totaly outside from Softimage, it doesn't work, I still have the same error message. ( it works in VBScript and JScript ) I think this has to do with restricted execution mode, but I have no clue how to customize it for allowing the loading of 'untrusted dynamic modules'. Any help on this would be greatly apreciated. Guy. 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net "Mark Hammond" wrote in message news:OAwe9.5047$_l1.12416 at news-server.bigpond.net.au... > > Hi, > > > > I'm a Softimage|XSI user, a 3D graphic software that support ActiveX > > Scripting on win32 platforms. > > > > This software integrate a 'NetView', an integrated internet explorer. > > > > To be able to communicate between the NetView and XSI I have to create the > > XSI.Application object. > > > > Works fine with VBScript and JScript, however I'm running into a problem > > trying to make it work with Python. > > > > Basicaly I have to include in my html page the following code: > > > > > > > > But when I load this page into the NetView ( or even in an external > > brother ) I have this error message: > > > > 'ImportError: untrusted dynamic module: win32api' > > > > Is there any way to 'force' the import ? > > > > Sorry if this has been discussed earlier, I'm relatively new to Python. > > It appears that SoftImage is configuring ActiveScripting for "untrusted" > scripts - ie, SoftImage is requesting the scripting engine switch into > untrusted mode. Thus, you really need to ask SoftImage is the > application can be configured to not request restricted execution mode > of the language. > > Mark. > From lozinski at openstepnews.com Tue Sep 24 11:49:24 2002 From: lozinski at openstepnews.com (lozinski at openstepnews.com) Date: Tue, 24 Sep 2002 08:49:24 -0700 (PDT) Subject: Lots of European Zope Contractors Available Message-ID: <1020924084924.8727AAC/i.lozinski@maya> At: http://zope.jobmart.com/Resumes/ShowEuropeans Including 11 British Citizens who are python and Zope Developers. Please let me know which candidates look interesting, and I will go ahead and post their resumes on the public web site. The great thing about having a large number of candidates immediately available, is that you can select just the right person for your requirements. If you send me your phone number, I can call you to discuss the general Zope marketplace. And don't forget to check out my resume at: http://zope.jobmart.com/Resumes/1154/Resume Regards Chris 1-510-740-6486 lozinski at openstepnews.com lozinski at jobmart.com From spoermeg at voldelig.com Tue Sep 17 19:36:08 2002 From: spoermeg at voldelig.com (Terje Johan Abrahamsen) Date: Tue, 17 Sep 2002 18:36:08 -0500 Subject: Source code References: <37fh9.112911$pX1.4044383@news2.tin.it> <7xk7lml7px.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xk7lml7px.fsf at ruckus.brouhaha.com... > Alex Martelli writes: > > > You'll have to give your customers a sealed computer and no permission > > > to install additional software, or communicate with the internet, if > > > you want to reliably prevent them from analysing your program. > > > > Incidentally, the latter option can be feasible in certain situations: some > > key parts of your program's functionality might reside on a computer you > > control, accessible to the rest of the application (installed more > > traditionally on users-controlled computers) only as a black box via the > > net. XML-RPC, SOAP, and other distributed-computing approaches > > such as Corba, make implementing this particularly easy these days. > > It doesn't have to be via the net: you can literally deliver a sealed > computer to the customer, with the sealing enforced by contracts and > inspections (this is quite normal, e.g. some financial applications > are delivered as a rack-mount box that you install in your machine > room) or by tamper resistant hardware (for higher security > applications). For VERY high security, of course you can't let > hostile parties touch the hardware. Nonetheless, the pay TV industry > deploys millions of sealed computers (smart cards) every year to > customers, every single one of which is considered an attacker. While > that industry had spectacular early security failures, these days it's > a fairly solved problem and they limit losses to acceptable levels. > > It doesn't sound like the OP was asking for this type of solution though. Nope.... Then I assume I had been able to pay for a security consultant to do that part of the work. Not plundering to do it myself with variable success... From mgerrans at mindspring.com Thu Sep 26 01:31:01 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Wed, 25 Sep 2002 22:31:01 -0700 Subject: a python puzzle References: Message-ID: > Keeping medicines from the bloodstreams of the sick; food from the bellies of > the hungry; books from the hands of the uneducated; technology from the > underdeveloped; and putting advocates of freedom in prisons. Intellectual > property is to the 21st century what the slave trade was to the 16th. Good quote! (Although, unfortunately -- and perhaps more so, if it's a predictor for "intellectual property" -- slave trade persisted long past the 16th century). From bkc at Murkworks.com Tue Sep 24 13:21:14 2002 From: bkc at Murkworks.com (Brad Clements) Date: Tue, 24 Sep 2002 13:21:14 -0400 Subject: ANNOUNCE: wxPython 2.3.3.1 References: Message-ID: <3d909c63_6@goliath.newsgroups.com> Sorry this is OT. Robin, any news on wxEmbedded for Windows CE? The embedded version for CE hasn't made any (visible) progress on the wxWindows website, and I can't find an email address for the person/org claiming to do the CE port. -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From ods at strana.ru Thu Sep 26 12:37:01 2002 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 26 Sep 2002 20:37:01 +0400 (MSD) Subject: design question In-Reply-To: <1ha6pukqdqell8f31q1k7rtor2rv5ogjs0@4ax.com> Message-ID: On Thu, 26 Sep 2002, Gon?alo Rodrigues wrote: GR> class Wrapper1(object) GR> def __init__(self, ): GR> self.__wrap = Class1() GR> GR> GR> But then if I did the same with Wrapper2, it would be at GR> least quirky GR> since it inherits from Wrapper1 but it wraps Class1 GR> puzzled bewilderment> class Wrapper1(object): _wrapped_class = Class1 def __init__(self, ...): self._wrap = self._wrapped_class() ... class Wrapper2(Wrapper1): _wrapped_class = Class2 ... -- Denis S. Otkidach http://www.python.ru/ [ru] http://diveinto.python.ru/ [ru] From storedmails at gmx.net Mon Sep 23 09:11:00 2002 From: storedmails at gmx.net (beachboy) Date: 23 Sep 2002 06:11:00 -0700 Subject: Session handling Message-ID: Hi! Please can anyone help me. My problem: I'm trying to program a web application with python. This tool has to provide diffrent languages. The user has to choose the language at the beginning. So i have to save the information which language the user chooses. I think this is a perfect example for using sessions. The only problem is I've got no idea how to realise this in python. Please help me as soon as you can because I have to solve this problem very quickly. hoping to hear from you soon beachboy From mhammond at skippinet.com.au Tue Sep 17 06:59:22 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 17 Sep 2002 10:59:22 GMT Subject: Calling Python from C# - please help References: <6de16ac9.0209130508.5d1b56c6@posting.google.com> <0iCg9.2350$Ee4.6516@news-server.bigpond.net.au> <3D82FA5B.3050003@mxm.dk> Message-ID: Max M wrote: > Mark Hammond wrote: > >> I have no examples of this, but I should. I'm co-authoring a .NET >> book which is nearly out :) - > > > > That sounds great. I enjoyed the win32 book, and still use it as a > reference. Thanks. Me too - it is amazing how much I have forgotten since writing it ;) > Are you by any chance still developing Pyhton .NET, or has it completely > stopped? Pretty much stopped. No one is funding it, and no one has stepped up to the plate and offered to help. It is too much for me to do alone, especially on my own time. I'd love to pick it back up, but unfortunately, I really can't see who's interest it is in to fund this thing - Microsoft really have no further interest which IMO is quite reasonable - they have generously funded enough to prove that Python could work, but there is no reason they should further fund Python over any (and therefore every) other open source language, especially when they have their own commercial offerings. Maybe Python should place an ad in the .singles newsgroups looking for a sugar-daddy <0.1 wink> Mark. From mihan at foss.kharkov.ua Wed Sep 4 04:36:59 2002 From: mihan at foss.kharkov.ua (Mykhaylo Sorochan) Date: Wed, 4 Sep 2002 11:36:59 +0300 Subject: embedding python (Makefile creation) problem Message-ID: Hi! I have tryed to implement some examples from Very High Level Embedding from Python documentation but hadn't found examples or rules of Makefile creation. Can anybody point me to the answer or describe such Makefiles creation. I need Makefile for Unix(FreeBSD). Thanks. -- Regards, Mykhaylo Sorochan From mike at bindkey.com Tue Sep 3 18:44:13 2002 From: mike at bindkey.com (Mike Rovner) Date: Tue, 3 Sep 2002 15:44:13 -0700 Subject: Drawing graphs/newtorks with Python References: Message-ID: "Alexander Stepanov" wrote in message news:Pine.OSF.4.10.10209031748180.23796-100000 at wilde.oit.umass.edu... > > Hi Pythonians, > > I work on program which performs some calculations over graphs. > (shortest paths). I would like to draw an image/ps_document with > Python. Does anybody use some kind of modules to draw graphs? > I will appreciate if you can point me out to the source. Take a look on GraphViz http://www.research.att.com/sw/tools/graphviz/ or http://www.graphviz.org/ From gumuz at looze.net Wed Sep 11 04:58:54 2002 From: gumuz at looze.net (Gumuz) Date: Wed, 11 Sep 2002 10:58:54 +0200 Subject: blocking socket dilemma Message-ID: <3d7f046f$0$230$4d4ebb8e@news.nl.uu.net> Hi all, I am a little bit stuck with my design (again!). I have this server class, which creates a session object for every accepted incoming connection. The session object has a RequestHandler function which is then run in a new thread. all fine, but... This RequestHandler function actually does a infinite loop. The loop wil receive data and take some action and it will send data which is piled up in this session's queue. The problem that i'm having is that the loop will hang on socket.recv if the client is not sending anything. Ofcourse this is very obvious and logical, but i can't think of another way of constructing my design, so that this problem doesn't occur. I hope i've made my problem clear to you guys. thanx, gumuz From joec at mill.co.uk Mon Sep 2 13:05:53 2002 From: joec at mill.co.uk (Joe Connellan) Date: Mon, 02 Sep 2002 18:05:53 +0100 Subject: compiling extensions on linux References: <3D738D4E.35B6C712@mill.co.uk> <3D739730.DEB80478@mill.co.uk> Message-ID: <3D739A71.F8650187@mill.co.uk> of course ;) that fixed it - I've now put the c++ stuff back in and declaring it as an extern "C" function Cheers Joe "Martin v. L?wis" wrote: > Joe Connellan writes: > > > it does have a initmyextension declared - Here's a simple example of my > > problem - I've taken all c++ related stuff out so I can use gcc > > However, you are still compiling it as a C++ program, since it has the > .cpp extension. You either need to rename the file (to .c), or use the > -x c command line option. If there was C++ stuff to take out, you best > declare the function as extern "C". > > Regards, > Martin From erick_papadakis at REMOVEFORSPAM.yahoo.com Sun Sep 15 21:42:09 2002 From: erick_papadakis at REMOVEFORSPAM.yahoo.com (Erick) Date: Mon, 16 Sep 2002 10:42:09 +0900 Subject: can wxpython do this? References: <737aefee.0209151702.3f735252@posting.google.com> Message-ID: Thank you very much Lothar. > There is no problem to setup an installer easily that takes > Python,WXPysthon and whatever you need. It simply blowes up the > installer package size. Isn't this the way to distribute wxpython apps? Because most users will not have python installed on their machines, much less the wxpython libraries? Or is it that after compilation users do not need Python installed at all? > >for instance, can i minimize my application to a user's desktop's > >taskbar and have a right-click context menu on that taskbar entry? > I think its not comfortable but possible. Look at the API to find out. I searched the html help for "taskbar" and there is only one function for Win95/NT (wxTaskBarIcon). Looks like this feature is not yet supported? Actually I am interested -- is there any popular utility written in wxpython? One of those things that are downloadable from Download.com or something? > There is a really simple WxHTML Widget and at least a C++ version of a > wrapped IExplorer control. The wxHTML widget supports only some very basic HTML tags, but I guess that'll do for now. What I really wanted to know was if there is a way for me to connect to the Internet, make a call to a webserver as a browser would do, retrieve data and display it inside my application (with or without HTML...does not have to be HTML at all, actually). Perhaps wxSocket is what I am talking about. But I did not see anything in the "demo" that has much to do with sockets. Would anyone know an example of using sockets in wxpython? Thanks a lot for the reply, I am already drawn! .ep From gua81 at XXXyahoo.com Thu Sep 26 06:13:45 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Thu, 26 Sep 2002 20:13:45 +1000 Subject: Getting last char in string. References: Message-ID: then what does s[-1:] do? "Quinet, Joel" wrote in message news:mailman.1033027776.19152.python-list at python.org... > Here under an example: > > s = 'abcd' > print s[-1] > d > print s[-2] > c > > Joel > -----Original Message----- > From: CheapSkate [mailto:gua81 at XXXyahoo.com] > Sent: jeudi 26 septembre 2002 9:49 > To: python-list at python.org > Subject: Getting last char in string. > > > Hi, im writing a simple method that takes in a string input and check if the > last charcter is an '/' > then it will do A else do B > > my Q now is how to get the last char??? > > Thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list > From michaels at one.net Sun Sep 15 23:09:49 2002 From: michaels at one.net (Michael Schneider) Date: Sun, 15 Sep 2002 23:09:49 -0400 Subject: Stackless Python, eventual merge? References: Message-ID: <3D854B7D.1060209@one.net> David Abrahams wrote: >"Christian Tismer" wrote in message >news:mailman.1032107006.6411.python-list at python.org... > >>The changes to Python are also so small now, that >>it doesn't matter if it will be merged or not. >>Porting Stackless to a new Python is a matter of a few >>hours. You may rely on getting a Stackless version >>of any new Python version in almost no time. >> > >I think it still matters. You don't want people who need stackless' >capabilities to have to use a non-standard Python forever, do you? > I am a little confused by this. I use threads, but threads must be compiled in. This has been that the same since I downloaded my first python in '93 (Very good language Guido :-) Could someone please explain to a "confused" python user. Why the current version of stackless python would not be distributed like threads??? Thanks to all for a great language!!!!!!!!!!!!! Mike > >-- >----------------------------------------------------------- > David Abrahams * Boost Consulting >dave at boost-consulting.com * http://www.boost-consulting.com > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pyth at devel.trillke.net Mon Sep 2 06:45:05 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 2 Sep 2002 12:45:05 +0200 Subject: Why it is so dramatical? In-Reply-To: <200209021228.58453.b.maryniuk@forbis.lt>; from b.maryniuk@forbis.lt on Mon, Sep 02, 2002 at 12:28:58PM +0200 References: <200209021228.58453.b.maryniuk@forbis.lt> Message-ID: <20020902124505.J3893@prim.han.de> Bo M. Maryniuck wrote: > On Monday 02 September 2002 11:57, Duncan Booth wrote: > > None of this is specific to Python, the same issues arise in almost any > > programming language (although not always the same solutions). > Almost... Keep in mind, that here is the range 0-0xffffff, what is quite > bigger that 0-0xfff: > ----------------------8<--------------------------- > #!/usr/bin/perl > > $b = ''; > $data = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'; > for $a (0..0xffffff) { > $b += $data; > } That should result in a 1.3 GIGABYTE string. Watching the perl-process i see that perl doesn't use more than 1MB. So probably perl does some optimization for this in-fact meaningless code. It's much more interesting to look at real performance limitations instead of some theoretical pusing-the-limits loops. holger From max at alcyone.com Mon Sep 23 02:41:45 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 22 Sep 2002 23:41:45 -0700 Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <%8ci9.138477$5r1.5541622@bin5.nnrp.aus1.giganews.com> <3D8EB212.1000104@cygnus-software.com> Message-ID: <3D8EB7A9.F7CDE16@alcyone.com> Bruce Dawson wrote: > I find the (a and [b] or [c])[0] construct to obscure to be useful - > the > space it saves is wasted by the comment I have to put in to explain > it. Precisely. The purpose of a conditional expression is to compress a trivial if/else statement into an expression in a readable manner. While you can use short-circuiting operators like and, or and lambda expressions to get this effect, it defeats the readability purpose and so is essentially useless. The shorter, more readable forms, tend to be subject to corner cases having different behavior than a standard p ? a : b conditional expression. > It occurs to me that the bool() built in function allows for what is - > in my opinion - a cleaner solution. Easier for mortals to comprehend. Well, you could already use operator.truth for that. > Basically, construct a two entry list of the two items and then index > that with your expression, converted to bool. The bool function is > essential since there was previously no generic way of getting the > true/false value of an expression. I use this technique frequently enough, but this isn't really what a conditional expression does. A conditional expression only _evaluates_ one of its consequents, depending on the value of the test expression. The (a, b)[operator.truth(p)] evaluates both. This is fine in many cases, of course -- such as when you're selecting between two strings -- but it isn't the full power of a true conditional expression. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Many situations can be clarified by the passing of time. \__/ Theodore Isaac Rubin CSBuddy / http://www.alcyone.com/pyos/csbuddy/ A Counter-Strike server log file monitor in Python. From see_reply_address at something.invalid Sun Sep 29 21:01:28 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 30 Sep 2002 13:01:28 +1200 Subject: Larry Wall's comment on python... References: Message-ID: <3D97A268.6040603@something.invalid> sismex01 at hebmex.com wrote: >>Alan Daniels wrote: >> >>>Sometimes I wonder if Guido would have saved a lot of debate >>>by declaring, long ago, that Python code would never allow >>>tabs in it, period. Which may be a bit extreme, I'll admit. :-) > > Actually, it's the only universally-workable solution > to this "problem". This is not a workable solution, because there are some environments in which tabs-only is the only sane thing to use, e.g. BBEdit and many other code editors on Mac. Mandating either tabs-only or spaces-only would be fine, though. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From loewis at informatik.hu-berlin.de Tue Sep 24 09:53:14 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 24 Sep 2002 15:53:14 +0200 Subject: Python.Net ? References: Message-ID: "Achim Domma" writes: > a german IT magazin (iX) mentioned a .Net version of python, developed by > ActiveState. My last information was, that there will be no .Net version > with produces IL code, but only an extension for the new Visual Studio. > Am I missing something or is the article simply wrong? There is a product called VisualPython, which integrates with Microsoft Visual Studio .NET. Depending on what .NET is for you, this could be called a .NET version of Python (once Microsoft .NET Server is out, any software that works on it could be called "works with .NET"). But yes, this version does not produce MSIL, and does not interoperate with the .NET runtime. Regards, Martin From paul at boddie.net Mon Sep 23 04:14:23 2002 From: paul at boddie.net (Paul Boddie) Date: 23 Sep 2002 01:14:23 -0700 Subject: PyQt setup on Linux Mandrake 8.2 References: <3D8B4898.20808@nospam.attbi.com> <3d8e7141$1@news.nz.asiaonline.net> <3D8E74A4.7000404@nospam.attbi.com> Message-ID: <23891c90.0209230014.56a45933@posting.google.com> djw wrote in message news:<3D8E74A4.7000404 at nospam.attbi.com>... > Thanks to you and the others, I finally got this to work. My remaining > question/problem/puzzlement is what to do about the fact I now have two > Python 2.2 installs on my system. Don't worry about this: I run Red Hat 7.3 and have at least two Python installations present. It doesn't make any difference in practice, provided you know which one you're using. > Mandrake installed everything during > its setup into /usr and everything I built/installed went into > /usr/local. I was going to rip out the version that Mandrake layed down > in /usr and just use the /usr/local copy, but when I ran the package > manager and told it to uninstall all the various py* pieces, the list of > dependencies it wanted to also delete was scary (stuff like filesystem > modules). I'm sure that RPM and other package management systems look great on paper (although I'm not entirely convinced by RPM), but the more irritating problems with them seem to arise when the people who put the packages together decide to split them up into "runtime" and "devel", regardless of whether this makes any real sense, and then leave out "Python.h" or whatever other essential file might be required by any software that needs to make use of (for example) Python. I suppose you're really supposed to install an RPM of that software, prepared by the same person who made the original Python packages, if only because that person has the luxury of having built from source. > Unfortunately, when I try to install new py modules, they all > want to install into /usr instead of /usr/local, since /usr/bin/python > is ahead of /usr/local/bin/python on $PATH, causing sys.prefix to point > to /usr, I suppose. Solution: set your PATH appropriately for all users who want the new installation of Python. There shouldn't be any major danger of inadvertently using the wrong versions of other software, at least on Linux systems, because /usr/local is probably pretty empty after installing a mainstream Linux distribution - it's not like mixing up /usr/ccs and /usr/ucb on Solaris and then finding out that you're running some "other" version of your favourite tools. > So, this leaves me wondering... its not possible to install Mandrake > without Python (as evidenced by the dependencies), but the location it > is installed at is "wrong" by default - so, what is the "proper" way to > handle this situation? (It would seem nice to install Linux without > Python and compile and install it afterwards). Ignore the distribution's installations and install your own in /usr/local, which helpfully happens to be the default "prefix", and then complain to your distribution vendor. What then seems to happen, based on experiences made public with Red Hat, is that they then ignore those suggestions whilst issuing vague hints that their chosen Python strategy makes complete sense, and that the entire Python community is "missing something". > I can't tell from your > list of commands where python is located, but I assume its in /usr? It usually is. > Also, I noticed that the copy of python that was installed by the system > lacked Python.h, whereas the copy I compiled and installed had this > file. Are you supposed to "overlay" the system copy in /usr with the > extra files that things like sip/pyqt need (i.e., Python.h)? You're not supposed to do things like that, especially since there could always be versioning issues in doing so, but Python.h does at least seem to have the same contents regardless of how your own Python installation was configured. Paul From nospam at horvath.com Thu Sep 26 08:26:47 2002 From: nospam at horvath.com (Bob Horvath) Date: Thu, 26 Sep 2002 12:26:47 GMT Subject: combining mailbox and email modules References: Message-ID: Dennis Lee Bieber wrote: > Bob Horvath fed this fish to the penguins on Wednesday 25 September > 2002 11:14 pm: > > > >>... and here it the message... >> >> From mickey at verizon.net Tue Aug 20 10:03:52 2002 >>Return-Path: >>Delivered-To: bob at horvath.com > > > Is that indent on the "From ..." line really in the file, or just some > artifact of pasting it into your post? I just checked my Eudora .mbx > files and they don't show an indent on the "From ..." line > Doh! Sorry, cut and paste error. No, the space before the From is not there. From pknotz at sandia.gov Fri Sep 27 08:18:19 2002 From: pknotz at sandia.gov (Pat Notz) Date: 27 Sep 2002 05:18:19 -0700 Subject: well-formed xml References: Message-ID: <525eaba.0209270418.911d329@posting.google.com> You have to be careful of non-alphanumeric characters. Try replacing '&' with & I beleive there is an escape() function in one of the xml modules that will do that kind of escaping on strings so thay may safely be placed into XML. From bobx at linuxmail.org Thu Sep 12 17:07:44 2002 From: bobx at linuxmail.org (Bob X) Date: Thu, 12 Sep 2002 21:07:44 GMT Subject: [FEEDBACK] Is this script efficient...is there a better way? References: <4ZRf9.1782$Lg2.248733@news2.news.adelphia.net> <3hSf9.168947$l_4.98525@atlpnn01.usenetserver.com> <8PSf9.1796$Lg2.257378@news2.news.adelphia.net> <_oUf9.170870$l_4.126599@atlpnn01.usenetserver.com> Message-ID: Steve Holden wrote: > "Bob X" wrote ... > [ ... ] > >>Thank you very much...your shorter script did work. The keywords are all >>"normal" english words that would not have any special characters. I >>only added a re.IGNORECASE (since case doesn't matter to me) after a >>quick search of the python docs. >> > > Was there any significant difference in the timings for the two different > methods, and how does the number of different keywords affect the timings? > I haven't tested...is there an easy way to time it...besides my going "that one ran faster"? However, I had a chance to run your RE version today and it did very well. BTW..the line that looked like a debug statement was just a visual for me to see the script was actually doing something. I put in a counter that prints "lines written:", a where "a" is the counter. I do have one question on that. It writes each line sequentially like: lines written: 1 lines written: 2 lines written: 3 Can I just get it to do it in place? Where the numbers are just replaced instead of scrolling? Just a thought... Bob Bob From neilhart at attbi.nospam.com Mon Sep 2 14:52:21 2002 From: neilhart at attbi.nospam.com (Neil Everhart) Date: Mon, 02 Sep 2002 18:52:21 GMT Subject: Dead Man Timer? References: <3D728103.5060308@itamarst.org_NOSPAM> Message-ID: Itamar, Thank you for the suggestion. I will test the timeoutsocket.py code tomorrow on my target setup. I have incorporated it into a version of my script but can not really evaluated it until I am running in the terminal server environment. Neil. -- "Itamar Shtull-Trauring" wrote in message news:3D728103.5060308 at itamarst.org_NOSPAM... > 1. Use timeoutsocket.py - this lets you set timeouts on socket operations > (find it on http://py.vaults.ca). > > 2. Use an event driven networking architecture - don't know of any that have > telnet client support though. > > Option 1 is your easiest solution. > > -- > Itamar Shtull-Trauring http://itamarst.org/ > Available for Python, Twisted, Zope and Java consulting > From loewis at informatik.hu-berlin.de Mon Sep 23 05:47:56 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 23 Sep 2002 11:47:56 +0200 Subject: UpToDate SOAP-module ?? References: Message-ID: "Thomas Weholt" <2002 at weholt.org> writes: > I've looked around for a SOAP-module to use in a WebService-based > project, but the SOAP-implementations in python seem to be a bit ... > unstable ?? Some of them haven't been updated for a while etc. I'd say that the qualifications contradict: If the module is not changing, it seems it is "stable" - it may be buggy or incomplete, but I associate stability with lack of change, or constance of behaviour in the presence of change. > Any opinions, hints or ideas are welcome. Thoughts on ease of use, > list of features, comparisons etc. are also interesting. My personal recommendation is to ignore SOAP. Regards, Martin From aleax at aleax.it Wed Sep 25 10:54:24 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 14:54:24 GMT Subject: Newbie References Question References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> Message-ID: Guy Rabiller wrote: > Hi, > > let say I have: > i1 = 1 ... > Textualy, how if I want that p[0] refere to the 'i1' container, and not to There is no 'i1' CONTAINER. 'i1' is just a NAME. That's what variables are in Python -- they don't contain anything: they're like post-it labels, attached to an object or to another. > the refererence it contains ? > > What I want is that if now I set: > i1 = 4 > that automaticaly: > p -> [4,2] > and not keeping [1,2] There is no way to do exactly what you require. There may be ways to do roughly-equivalent things, if you help us help you by explaining your application context a bit more widely. Alex From peter at engcorp.com Mon Sep 2 14:43:59 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Sep 2002 14:43:59 -0400 Subject: RedHat 7.3 and Python2.2.1 References: <88bc63c6.0209020932.54723791@posting.google.com> Message-ID: <3D73B16F.76B355DB@engcorp.com> Doug Farrell wrote: > > I'm trying to install the latest version of Python > (python2-2.2.1-1.i386.rpm) from the www.python.org download page, and > I'm having problems. When I run > > rpm -i python2-2.2.1-1.i386.rpm > > I get all kinds of conflict messages like this: > > file /usr/bin/pydoc2 from install of python2-2.2.1-1 conflicts with > file from package python2-2.2-16 > > probably hundreds of them in fact. Can anyone tell me what is going on > here, as the www.python.org site says the RPM I'm using is for RH7.3, > which is what I'm using. If you can tell me what I'm doing wrong and > how to address this, that would be great too! My ultimate goal is to > also install wxPython for the python2.2.1 installation, so if anyone > has some 'heads up' on that, I'd appreciate it. Sounds like you already have a previous version of Python2.2 installed. You should probably be using the "-U" option to update instead of the "-i" option to install... or uninstall the previous one first. -Peter From from_deja at alandaniels.com Mon Sep 23 09:34:57 2002 From: from_deja at alandaniels.com (Alan Daniels) Date: 23 Sep 2002 06:34:57 -0700 Subject: Universally unpacking tuples References: <158d3913.0209222233.123a9675@posting.google.com> Message-ID: peter.bittner at gmx.net (Peter Bittner) wrote in message news:<158d3913.0209222233.123a9675 at posting.google.com>... > Hi there! > > I have problems universally unpacking tuples. I would like to take the > first element of a tuple and remove it (thus creating a new tuple with > one element less)... Just use the slice notation. A slice of a list is a new list, and a slice of a tuple is a new tuple. In the example below, where y is a tuple, the "y[1:]" means "a slice out of y, from element 1 all the way to the end". [Example...] y = (100, 200, 300, 400, 500) while len(y) > 0: (head, y) = (y[0], y[1:]) print head, y [This will print...] 100 (200, 300, 400, 500) 200 (300, 400, 500) 300 (400, 500) 400 (500,) 500 () From michael.weigend at fernuni-hagen.de Fri Sep 6 12:56:15 2002 From: michael.weigend at fernuni-hagen.de (Michael Weigend) Date: 6 Sep 2002 09:56:15 -0700 Subject: question: iso 14977 ebnf grammar for Python? Message-ID: <77977a28.0209060856.6974e6eb@posting.google.com> Hello! Is there a ebnf grammar for Python written according to the ISO 14977 standard somewhere in the www? Michael asks From tjreedy at udel.edu Wed Sep 18 01:18:20 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 18 Sep 2002 05:18:20 GMT Subject: Splitting a list of strings References: Message-ID: "Sean Ross" wrote in message news:am8pvo$dcn$1 at driftwood.ccs.carleton.ca... > Okay. Here is some representative sample data: > [snip] > @attribute 'cap-shape' { 'b', 'c', 'f', 'k', 's', 'x'} > [snip] > 'x','s','n','t','p','f','c','n','k','e','e','s','s','w','w','p','w','o ','p', > 'k','s','u','p' Unless you plan to exec parts of the lines as if they were Python code, I believe you would be better off without all the quotes. You could then split on ',' and have the 1-char strings you want.. Terry J. Reedy From bdesth at nospam.free.fr Sun Sep 8 23:21:23 2002 From: bdesth at nospam.free.fr (laotseu) Date: Sun, 08 Sep 2002 23:21:23 -0400 Subject: Python plugins References: Message-ID: <3D7C13B3.2070606@nospam.free.fr> Tobias Klausmann wrote: > Hi there, > > For an open source project that needs to be extensible by its > users, I would like to create a plugin architecture. Mind you, > I'm not trying to use Python as a plugin language only like XChat > or Gnumeric do. Let me illustrate: [snip] > But now I have two > problems: first, I have no idea how to call, say > pi.someplugin.dostuff(args) except constructing each and every > call as a string and exec() it - which is both error-prone and > awkward IMHO. Just a snippet without any other testing code or whatsoever... module[index] = __import__(module_name, globals(), locals(), []) (...) module[index].dostuff(args) HTH laotseu From fromclay at maxitec.co.za Wed Sep 4 03:42:49 2002 From: fromclay at maxitec.co.za (Morne) Date: Wed, 4 Sep 2002 09:42:49 +0200 Subject: help on log Message-ID: <009201c253e6$b4f47ba0$2500a8c0@maxitec.co.za> Could someone please help me with this? Im really new to any kind of programming .If posible would you be able to answer in detail. Thanx HERE IS WHAT I HAVE: import re import string secondsMatcher=re.compile("Connect time: (\d+) secs") def getStuff(file): closeline = 0 errorcount = 0 secondscount = 0 connectcount = 0 data_outcount = 0 data_incount = 0 ppplist = file.readlines() for line in ppplist: if string.find(line,"LayerUp") >= 0: print "found connect" connectline = string.split(line) connectcount = connectcount + 1 elif string.find(line,"ERROR") >= 0: print "found error" errorcount = errorcount + 1 elif string.find(line,"Connect time") >= 0: print "found close" connectSecs=secondsMatcher.search(line).group(1) print "Connected for",connectSecs closeline = string.split(line) secondscount = secondscount + string.atoi(connectSecs) def main(): f=open("C:/my documents/ppp.log","r") getStuff(f) return None if __name__=="__main__": main() THIS IS WHAT I NEED THE PROGRAM TO DO: I want the program to read the attached ppp.log file and give me the following type of report: PPP Log file summary for 5 Jul 2002 ----------------------------------- Jul 5 18:15:01 Connected to internet (IP 155.239.150.146) Jul 5 18:18:08 Closed connection. ( Connect time: 197 secs: 5091 octets in, 1864 octets out ) ----------------------------------- Successful connections: 5 Failed connections: 2 Total time online: 456 seconds Total data in: 66576 octets Total Data out: 66349 octets HERE IS part of the olg file seems noone wants to touch the Attachment(lol) > Jul 5 18:00:00 maxigate newsyslog[87300]: logfile turned over Jul 5 18:15:00 maxigate ppp[34607]: tun0: Phase: Connected to local client. Jul 5 18:15:00 maxigate ppp[34607]: tun0: Command: /var/run/internet: quit Jul 5 18:15:00 maxigate ppp[34607]: tun0: Phase: /var/run/internet: Client connection dropped. Jul 5 18:15:00 maxigate ppp[34607]: tun0: Phase: Connected to local client. Jul 5 18:15:00 maxigate ppp[34607]: tun0: Command: /var/run/internet: set timeout 180 Jul 5 18:15:00 maxigate ppp[34607]: tun0: Command: /var/run/internet: dial Jul 5 18:15:00 maxigate ppp[34607]: tun0: Phase: bundle: Establish Jul 5 18:15:00 maxigate ppp[34607]: tun0: Phase: deflink: closed -> opening Jul 5 18:15:00 maxigate ppp[34607]: tun0: Phase: deflink: Connected! Jul 5 18:15:00 maxigate ppp[34607]: tun0: Phase: deflink: opening -> dial Jul 5 18:15:00 maxigate ppp[34607]: tun0: Chat: Phone: 0860007249 Jul 5 18:15:00 maxigate ppp[34607]: tun0: Chat: deflink: Dial attempt 1 of 1 Jul 5 18:15:00 maxigate ppp[34607]: tun0: Phase: /var/run/internet: Client connection closed. Jul 5 18:15:00 maxigate ppp[34607]: tun0: Chat: Send: AT^M Jul 5 18:15:00 maxigate ppp[34607]: tun0: Chat: Expect(5): OK Jul 5 18:15:00 maxigate ppp[34607]: tun0: Chat: Received: AT^M^M Jul 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Received: OK^M Jul 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Send: ATE1Q0^M Jul 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Expect(5): OK Jul 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Received: ATE1Q0^M^M Jul 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Received: OK^M Jul 5 18:15:01 maxigate ppp[34607]: tun0: Chat: Send: ATx1DT0860007249^M Jul 5 18:15:03 maxigate ppp[34607]: tun0: Chat: Expect(40): CONNECT Jul 5 18:15:22 maxigate ppp[34607]: tun0: Chat: Received: ATx1DT0860007249^M^M Jul 5 18:15:22 maxigate ppp[34607]: tun0: Chat: Received: CONNECT 33600/ARQ/V34/LAPM/V42BIS^M Jul 5 18:15:22 maxigate ppp[34607]: tun0: Phase: deflink: dial -> carrier Jul 5 18:15:23 maxigate ppp[34607]: tun0: Phase: deflink: /dev/cuaa0: CD detected Jul 5 18:15:23 maxigate ppp[34607]: tun0: Phase: deflink: carrier -> login Jul 5 18:15:23 maxigate ppp[34607]: tun0: Phase: deflink: login -> lcp Jul 5 18:15:23 maxigate ppp[34607]: tun0: LCP: FSM: Using "deflink" as a transport Jul 5 18:15:23 maxigate ppp[34607]: tun0: LCP: deflink: State change Initial --> Closed Jul 5 18:15:23 maxigate ppp[34607]: tun0: LCP: deflink: State change Closed --> Stopped Jul 5 18:15:24 maxigate ppp[34607]: tun0: LCP: deflink: LayerStart Jul 5 18:15:24 maxigate ppp[34607]: tun0: LCP: deflink: SendConfigReq(179) state = Stopped Jul 5 18:15:24 maxigate ppp[34607]: tun0: LCP: ACFCOMP[2] Jul 5 18:15:24 maxigate ppp[34607]: tun0: LCP: PROTOCOMP[2] Jul 5 18:15:24 maxigate ppp[34607]: tun0: LCP: ACCMAP[6] 0x00000000 Jul 5 18:15:24 maxigate ppp[34607]: tun0: LCP: MRU[4] 1500 Jul 5 18:15:2 -------------- next part -------------- An HTML attachment was scrubbed... URL: From DGustafson at attbi.com Thu Sep 19 14:15:58 2002 From: DGustafson at attbi.com (Dave Gustafson) Date: Thu, 19 Sep 2002 18:15:58 GMT Subject: Creating a typelibrary for calling Python COM server from c# Message-ID: There was a thread recently that suggested creating a typelibrary in order to access a Python based COM server from C# (or .NET). Can anyone please suggest an easy way to create such a library??? From root at [127.0.0.1] Mon Sep 16 18:37:39 2002 From: root at [127.0.0.1] (nobody) Date: Tue, 17 Sep 2002 08:37:39 +1000 Subject: stdin on Win32 Message-ID: <3d865d34$0$22177$afc38c87@news.optusnet.com.au> This works on Linux, but not Win32. Win32 just gives me EOF.. # echo foo|test.py where test.py is: import sys print sys.stdin.readline() WTF? From gmuller at worldonline.nl Sun Sep 22 14:29:27 2002 From: gmuller at worldonline.nl (GerritM) Date: Sun, 22 Sep 2002 20:29:27 +0200 Subject: Smalltalk vs. Python and COM was Re: Byte Magazine and Smalltalk References: <3d87a686@tobjects.> <3d87dd7c$1@tobjects.> <20020918.115128.1605894428.1527@cybermesa.com> Message-ID: "Pino Gargiulo" schreef in bericht news:amkup0$qtb$1 at fe2.cs.interbusiness.it... <...snip...> > > Thanks for your advice and prompt reply! > > If I understand you correctly you are suggesting that Python is the way to > go > for COM m$ API rather than Smalltalk .. again Id like to hear suggestions > on which product. My dabbling experience is just with VWNC > > TNX again > > Pino > What is VWNC? What end level application do you want to support and/or build? The ActiveState distribution I suggested is a Python distribution ("batteries included") which allow you to do nearly everything. Additional packages can be found at many places a.o. in the vaults of Parnassus. regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From duncan at NOSPAMrcp.co.uk Tue Sep 24 05:07:31 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 24 Sep 2002 09:07:31 +0000 (UTC) Subject: list problem References: <3D8F9F5E.DC48B13F@pop.ntlworld.com> Message-ID: Thorsten Kampe wrote in news:amp6i1$7n9bi$1 at ID- 77524.news.dfncis.de: > * Anthony Tuininga >> If you have list comprehensions available, use >> >> [b for a in x for b in a] > > What about: > reduce(lambda x, y: x + y, a) ? > If you are going to use reduce, then you would be better off writing: import operator reduce(operator.add, x) -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From bruce-news at hartweg.us Mon Sep 30 00:58:14 2002 From: bruce-news at hartweg.us (Bruce Hartweg) Date: Mon, 30 Sep 2002 04:58:14 GMT Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> Message-ID: <3D97D9E8.5080008@hartweg.us> mike henley wrote: > "TGOS" wrote in message > news:pasepuc0r73mh5vlcsu1l7erl4e2b17qvi at 4ax.com... > > "other than the ones already present on a web-server", exactly! i want to be > ably to use whatever language, modules or applications i choose, and over > the year use others, freely. if i choose perl, php, or even python, ruby or > tcl, then i want to be able to do that. if i want to use mysql or something > else that i prefer, then i want to have the freedom to do that. i do not > wish to be restricted by the "ones already present on a web-server". i do > not want to end up in a catch 22 situation, should i choose a good deal on a > host, and then choose applications within the limits of what it allows me, > or choose applications, and try to find a host that'll provide a good deal. > The "freedom" to do all that is there, but freedom ain't neccessarily free. Besides, I think you are thinking too hard on this. If you want to run your own site off your own PC & aren't on-line all the time, then so be it. There are dynamic DNS services (even free ones!) and people can go to your page - if your not on-line they won't get there, if you are, they will. The auto-notification is mostly overkill, If they aren't around to see it what goo dis it, if they are around they can alsways just try. Also you could do a 2 tiered approach where you have much of your content on a real hosted site (free, or paid) and then have a link from there to you home machine for the sections you want to have all the goodies on - you could even auto-update that page when you connect or disconnect to only have the link when you are on-line. Bruce From jb at cascade-sys.com Tue Sep 17 01:11:14 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Mon, 16 Sep 2002 22:11:14 -0700 Subject: doh References: <3d83fa2c$0$24041@echo-01.iinet.net.au> <3d84a3ed$0$24051@echo-01.iinet.net.au> <3D8659FE.D406C4F8@pop.ntlworld.com> Message-ID: <3D86B972.9060209@cascade-sys.com> a.clarke11 wrote: >>A deer... >> >> A Female deer... ---jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From claird at starbase.neosoft.com Thu Sep 19 08:44:50 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 19 Sep 2002 07:44:50 -0500 Subject: linux python ideas References: <3D88E578.6010001@diespammerdieuselesspython.com> <23891c90.0209182329.52b55550@posting.google.com> Message-ID: <8D080F827517373B.5119372FF30E25F4.FCB4F73B5EFD9166@lp.airnews.net> In article <23891c90.0209182329.52b55550 at posting.google.com>, Paul Boddie wrote: . [several apt and accurate points] . . >Of course, stuff like "network programming" is fairly easy with other >languages, but unless Perl has spawned an interactive mode, for >example, you'll be showing people things they haven't seen before if >you show some experimentation at the command prompt. You might also . . . Has Perl spawned an interactive mode? Read -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From sholden at holdenweb.com Sat Sep 7 15:00:39 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 7 Sep 2002 15:00:39 -0400 Subject: Bind threads to addresses -- Windows & urllib? References: Message-ID: <_2se9.16902$l_4.8964@atlpnn01.usenetserver.com> "Nick Arnett" wrote ... > > > -- > Nick Arnett > Phone/fax: (408) 904-7198 > narnett at mccmedia.com > > > That's not gonna help you at all, because all threads will > > be capped by the interface's top throughput, or by your > > machine's processing power. > > You're making an incorrect assumption about the purpose of using multiple > addresses. It has nothing to do with my end of the connection; it is to > cope with servers that regard a reasonably well-behaved spider (in my > opinion, at least) as a denial-of-service attack. If the server operators > would reveal what they regard as well-behaved, I wouldn't have to resort to > this, but as one might expect, nobody wants to disclose the parameters of > their DOS defenses. I can't get the relevant sites to even respond to > inquries... and they don't even have a robots.txt file. > > On the other hand, the more I think about this, the less interested I am in > bothering, since it would surely be easy for a server to block a range of > addresses. > > I'm also working the other obvious solution, heuristics for the spider to > set its own speed so that it won't trigger defenses -- but it appears > there's something more than simple rules at the other end. The robot wars I > expected years ago have arrived... > > No lectures on what consists good robot behavior, please -- I've been > operating *the* list on that subject for years > (http://www.mccmedia.com/mailman/listinfo/robots) > Nick: Have you considered that it may simply be the lack of the usual headers produced by browser that causes the remote servers to reject your traffic? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From buzzard at urubu.freeserve.co.uk Tue Sep 10 14:47:42 2002 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 10 Sep 2002 19:47:42 +0100 Subject: Graph Layout Algorithms References: Message-ID: "Padraig Brady" wrote in message news:pSmf9.3468$cP3.6944 at news.iol.ie... > Duncan Smith wrote: > > Hello, > > Just wondering if anyone has implemented anything in Python. I > > need to lay out my graphs (directed acyclic / undirected / trees) in a > > reasonably clear way. So if anyone has already implemented anything, or if > > anyone has advice on appropriate algorithms, I'd be glad to hear about it. > > Cheers. > > > > Duncan > > Do you mean graphically represent or internally in data structures? Represent; the data structures are done (although might be rethought at some stage). What I'm after is an algorithm that will calculate suitable coordinates for the nodes based on indegree / outdegree etc. Currently I just arrange them in a circle, but that doesn't look too good. I suppose there might be cases where I'd like to show structures within the graphs as clearly as possible too (ancestral graphs / cliques / separators / maximal prime subgraphs). But some basic algorithms to get me started would be useful. I'll check out the links. Cheers. Duncan From bokr at oz.net Tue Sep 3 18:01:22 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Sep 2002 22:01:22 GMT Subject: efficient list merging References: Message-ID: On 3 Sep 2002 11:12:38 -0700, theoryboy at my-deja.com (Peter Saffrey) wrote: >I have two lists of lists of strings which I would like to merge >efficiently without repeats. I assume that each list currently >contains no repeats. At the moment, I have two possible >implementations: > They aren't implementations. Come back when you've at least tried to compile the code you're posting ;-/ Post a short example with data. That is the clearest way to show what you are trying to do. Also say something about how you got your lists of lists of strings. Regards, Bengt Richter From yka at mbnet.fi.invalid Sat Sep 7 16:48:55 2002 From: yka at mbnet.fi.invalid (yka) Date: Sat, 07 Sep 2002 20:48:55 GMT Subject: Larry Wall's comment on python... References: Message-ID: <1112946.EjPAhmYJ08@cartman> Mark McEahern wrote: >> Of course, most of my current code has one big block, main(), and I just >> cut-and-paste the rest. > > Your message brought me smiles, tears, and laughter--I haven't had that > much fun since watching Heehaw. > yes I'm astonished by this revelation too -- Haloo? From aleax at aleax.it Mon Sep 30 10:03:01 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 30 Sep 2002 14:03:01 GMT Subject: help with writing extension References: Message-ID: Eric Hagemann wrote: > I have been handcrafting an extension module creating a new type > > I am making use of the numeric methods (+,-,* etc) > > I solved the problem of the object interating with other types by working > through the __coerce__() function and have no issue with operations like > +2 but I am getting an error on 2-. As I understand, __coerce__ is not recommended for new code. You should, I believe, add Py_TPFLAGS_CHECKTYPES to your tp_flags slot, and be ready in your numeric functions to deal with types as they come. Sometimes coercion can be handier, but in general avoiding it is better. > In Beazley's book there are descriptions of functions like __radd__() when > defining a new type in python, but I cannot find reference to these > functions in C ? If you grep Python's C sources (2.2 or better), you'll find some such references. Slots nb_add of the PyNumberMethods structure to which slot tp_as_number of your PyTypeObject structure point supplies both __add__ and __radd__ (when you call PyType_Ready on your type, suitable wrappers on that slot are exposed with those two names). > I have checked the doc's (not to say that I did not miss something ;) ) I think you still need to complement existing docs with some little study of the Python sources when you want to design rich and complete extension types -- and I think that dealing with __radd__ etc in the right way is part of a "rich and complete" (rather than just a really minimal) extension type. I think this will still be true when my "Python in a Nutshell" is finally out, because the chapter on extending and embedding with C is limited to 40-50 pages (can't be more precise right now because the book's being edited and I'm not sure how many of my examples and details the editor will want to keep -- or if even more will be added), and doing complete justice to the subject would require about 10 times as much space. But I also think that asking here about such issues is just right! Best place to get help -- and this way the help gets archived (thanks to google groups and other archivers) and can be pointed to in the future (which alas doesn't work for other mailing lists such as python-help, nor, of course, for private mail:-). An example can help -- sorry if it's not very concise, but the PyTypeObject structure is so large that any examples of its use are also large, even though most fields are 0. Say I have a directory ~/extype with a setup.py file such as: from distutils.core import setup, Extension setup(name = "samp1", version = "1.0", description = "Sample extension type", maintainer = "Alex Martelli", maintainer_email = "aleaxit at yahoo.com", ext_modules = [ Extension('samp1', sources=['samp1.c']) ] ) and a samp1.c file such as: #include "Python.h" typedef struct { PyObject_HEAD } samp1; static void samp1_dealloc(PyObject *op) { op->ob_type->tp_free(op); } static PyObject * samp1_amethod(PyObject *self) { Py_INCREF(Py_None); return Py_None; } static PyObject * samp1_add(PyObject *self, PyObject *other) { PyObject* result = PyTuple_New(2); if(!result) return NULL; Py_INCREF(self); PyTuple_SET_ITEM(result, 0, self); Py_INCREF(other); PyTuple_SET_ITEM(result, 1, other); return result; } static PyMethodDef samp1_methods[] = { {"amethod", (PyCFunction)samp1_amethod, METH_NOARGS}, {NULL, NULL} /* sentinel */ }; static PyNumberMethods samp1_as_number = { samp1_add, }; static PyTypeObject samp1_t = { PyObject_HEAD_INIT(0) 0, "samp1", sizeof(samp1), 0, samp1_dealloc, 0, 0, 0, 0, /* tp_compare */ 0, /* tp_repr */ &samp1_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES, "sample extension type", 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ samp1_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ _PyObject_Del, /* tp_free */ }; static PyMethodDef no_methods[] = { {0} }; void initsamp1(void) { PyObject* self; PyType_Ready(&samp1_t); self = Py_InitModule("samp1", no_methods); PyObject_SetAttrString(self, "samp1", (PyObject*)&samp1_t); } Now of course running python setup.py in this dictionary builds and installs extension module samp1. Let's look at it in action: [alex at lancelot extype]$ python Python 2.2.1 (#2, Jul 15 2002, 17:32:26) [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import samp1 >>> examp = samp1.samp1() >>> examp + 'ciao!' (, 'ciao!') >>> 'salute...' + examp ('salute...', ) >>> See what's going on? Despite the (traditional) argument names, samp1_add is being called with the LEFT operand of + as the first argument ('self'), the RIGHT operand as the second argument ('other') -- your C code can test the types directly to do the right thing in both the __add__ and __radd__ cases...! Sure, you CAN make do with coercion (so have all Python extension types until about last year), but bypassing it makes things a bit clearer, I believe. If you do want coercion in some but nor all of your numeric-methods you can deal with it yourself -- call your own "coercion-like" function from your methods' code as and where appropriate. I do think it's simpler than having Python do it for you and sometimes having to "bypass" it, so to speak... this way you can still supply a function to be called when the user does an explicit coerce call, and yet have whatever precise behavior you want for all operators that look like numeric operators ("look like", because, for example, sequence concatenation isn't really numeric -- it just LOOKS LIKE it is, and has to live in PyNumberMethods, but that's not quite where one might like to place it...). Feel free to keep posting such questions to this list if there is anything unclear in the above, and/or if you need any more help! Alex From mike at bindkey.com Wed Sep 25 13:48:05 2002 From: mike at bindkey.com (Mike Rovner) Date: Wed, 25 Sep 2002 10:48:05 -0700 Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <%8ci9.138477$5r1.5541622@bin5.nnrp.aus1.giganews.com> <3D911FE1.1050801@something.invalid> Message-ID: "Greg Ewing" wrote in message news:3D911FE1.1050801 at something.invalid... > thp at cs.ucr.edu wrote: > > Personally, I rather like > > a if b else c > > but Guido doesn't like that either, unfortunately. > > Perhaps I'll slip it into Pyrex when no-one's looking...:-) It's not as readable as one think ;) I, personally, read this as 'take a if b is true else take c' which corresponds to 'b? a: c' in C. So, please, don't create ambiguity from nowhere. gratefully-plex-er-ly yours, Mike From timr at probo.com Fri Sep 27 00:53:57 2002 From: timr at probo.com (Tim Roberts) Date: Thu, 26 Sep 2002 21:53:57 -0700 Subject: problem with dictionaries within lists References: Message-ID: Grant Hallam wrote: > >#Compiled regular expressions >#Used in web parser >rcN = re.compile('Name') >rcL = re.compile('Location') >rcT = re.compile('Transit') >rcTN = re.compile('Technical_Knowledge') >rcLS = re.compile('Like_Site') >rcRT = re.compile('Resolve_Tech_Issues') >...many more deleted... On an unrelated note, I hope you won't mind if I comment on this part of your code. You would get better performance and less resource use out of this if you replaced these regular expression matches with simple list[0].find('XxxXxx') calls. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From marklists at mceahern.com Wed Sep 4 17:38:56 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 4 Sep 2002 16:38:56 -0500 Subject: str() of a tuple In-Reply-To: Message-ID: > I'm sure this is a FAQ[...] It is: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=slrnacjga3.2uv.huaiy u%40gauss.almadan.ibm.com > Is there a convenient way to print out a tuple of floats so that the > output is actually readable? Subclass tuple and do your own __str__: $ python >>> class mytuple(tuple): ... def __repr__(self): ... strings = [str(x) for x in self] ... s = ','.join(strings) ... return "(%s)" % s ... >>> t = mytuple((2, 0.4)) >>> t (2,0.4) >>> print (2, 0.4) (2, 0.40000000000000002) // m - From news at datatailors.com Thu Sep 19 10:55:01 2002 From: news at datatailors.com (Peter van Kampen) Date: Thu, 19 Sep 2002 16:55:01 +0200 Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> <108666F172046BF0.AFF78CED7027291C.080DCC403BC7489C@lp.airnews.net> Message-ID: In article <108666F172046BF0.AFF78CED7027291C.080DCC403BC7489C at lp.airnews.net>, Cameron Laird wrote: > In article , > Steve Holden wrote: >>"Nenad Propadovic" wrote ... > . > [much thoroughly > sensible advice] > . > . >>> The GUI has a part I consider complex: I have to present some statistics >>in >>> form of charts or graphs. >> >>The Python Image Library (PIL) is very good for creating graphics. You can >>create them "on the fly" in your web server and then serve back HTML >>documents with references to the created graphics. > . > It strikes me that Mr. Propadovic is tackling > several new techniques and technologies at once. > Given that, I have an alternative to suggest for > "some statistics in form of charts or graphs". > > There's a trick for making making simple bar > charts which requires no extra modules or pro- > gramming. It's so simple, in fact, that it makes > barcharting easy in shell or assembler or C. > > Apparently I've only documented it in Tcl http://wiki.tcl.tk/barchart > (see references > there, though, for Python hints). If you need > a sample dilation in Python, just say so here. > > Also, Mr. Propadovic: take Steve's advice to > heart. Even the CGI about which he writes need > not be as challenging as your comments suggest > you fear it to be. There's even a simpler method (for a browser-based app): CSS. The example below works with most (all?) modern (graphical) browsers (I checked with IE5.5, Opera 6.01 on Win2K and Mozilla 1.0.0 on linux). The vertical bars are a little harder but not much. I hope the HTML doesn't mess everyones clients up.


PterK From mhammond at skippinet.com.au Mon Sep 23 23:37:23 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 24 Sep 2002 03:37:23 GMT Subject: Python threading? References: Message-ID: Aahz wrote: > In article , > Robert Oschler wrote: > >>Also, what is a reasonable number of threads to expect to be able to run >>before context switching overhead becomes a problem (I'm using a PIII 500 >>Mhz with 512MB ram if that helps). > > > It depends. For pure Python-based computation, more than one thread > will cost you more than you gain. If it's almost pure I/O (file or > socket stuff), you might be able to use as many as a couple of hundred > threads. Mostly, you're probably best off somewhere between five and > thirty threads, depending on what you're doing. I would have thought that a brave call. If you are performing lots of IO and need many many connections, you are almost certainly better off using an "asynchronous" approach, much like asyncore. With a large number of threads (where "large" can be as low as single figures) the OS overhead of switching will be greater than your internal overhead of a more complicated design. A "one thread per connection" model is doomed from the start - therefore, in most applications, I would consider 5 threads a large number - particularly when all are actively doing something. OTOH, if you are willing to accept that your first version will accept a max of ~20 connections, the brain-power saved by using threads beats the additional OS overhead by a mile ;) Mark. From sadams123 at optushome.com.au Wed Sep 4 03:33:49 2002 From: sadams123 at optushome.com.au (Steven) Date: Wed, 4 Sep 2002 17:33:49 +1000 Subject: maximum number of threads? Message-ID: <3d75b761$0$26216$afc38c87@news.optusnet.com.au> Is there a maximum number of threads that can be running 'simultaneously' in Python 2.2 on Win2k/XP? I'm choosing between a select or threads based design, threads would be easier, but wasn't sure whether I'll exceed some maximum number of threads. Basically its a voice server, or rather a voice to text server, so information produced might be sporadic, or fairly continuous. An arbitrary number of subscribers subscribe to the system and get voice information sent out as it comes in (and if it matches the language the subscriber wants), threads make it simple since each subscription could be separate. Is there a maximum number of threads, and any opinions on whether the GIL and context switching in the interpreter is liable to make it unworkable (or a case of 'build and see')? TIA Steven From mstenner at phy.duke.edu Fri Sep 27 15:26:50 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Fri, 27 Sep 2002 15:26:50 -0400 Subject: watching mutables? In-Reply-To: ; from cliechti@gmx.net on Fri, Sep 27, 2002 at 08:48:10PM +0200 References: Message-ID: <20020927152650.A17611@phy.duke.edu> On Fri, Sep 27, 2002 at 08:48:10PM +0200, Chris Liechti wrote: > Thomas Heller wrote in > news:k7l7qpvf.fsf at ion-tof.com: > > Chris Liechti writes: > [triggered by *any* change of object m] > >> see EventObj: > >> http://oomadness.tuxfamily.org/p-pyobjtools.php > >> > > This is what I get when clicking on the download link: > > 404 Not Found > > works for me. I find that rather surprising since that file isn't there. Are you sure you clicked on the download link? For your convenience, I provide that link here: http://oomadness.tuxfamily.org/downloads/EventObj-0.2.tar.gz I am also interested in this module (curiosity, mostly) and would appreciate a working link if you have one. -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From james.kew at btinternet.com Thu Sep 26 04:00:21 2002 From: james.kew at btinternet.com (James Kew) Date: Thu, 26 Sep 2002 09:00:21 +0100 Subject: Getting last char in string. References: Message-ID: "CheapSkate" wrote in message news:amue3q$h59$1 at lust.ihug.co.nz... > Hi, im writing a simple method that takes in a string input and check if the > last charcter is an '/' > then it will do A else do B > > my Q now is how to get the last char??? if stuff[-1:] == '/': or if stuff.endswith('/'): -- James Kew james.kew at btinternet.com From ChandrS at telkom.co.za Thu Sep 5 10:24:08 2002 From: ChandrS at telkom.co.za (Sathish Chandrasekaran (S)) Date: Thu, 5 Sep 2002 16:24:08 +0200 Subject: What database should I use Message-ID: In that case MS-access will be better on the size issue. But on the other hand if u want ur application to be flexible and ease of use I would rather suggest FoxPro (though it's it considered obsolete now-a-days). Here Is A Test To Know Whether The Mission Of Your Life Is Over . If You Are Alive It Isn't . Sathish C Infra-Amdocs -----Original Message----- From: A [mailto:printers at sendme.cz] Sent: 05 September 2002 15:21 To: python-list at python.org; tutor at python.org; activepython at listserv.ActiveState.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: What database should I use Hello, I am going to program a small application (in Python and wxPython) which consists about 2000 - 3000 records . Can you please recommend which database is the best for that. I use Windows. Maybe MS Access or FoxPro or MySQL or better? I want to keep the program as small as possible. Thanks Ladislav _______________________________________________ ActivePython mailing list ActivePython at listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython From max at alcyone.com Thu Sep 19 17:35:39 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 19 Sep 2002 14:35:39 -0700 Subject: lists in dictonaries ? References: Message-ID: <3D8A432B.DBCB3EF5@alcyone.com> Manuel Hendel wrote: > Is it possible to put lists in dictionaries? I presume you mean as dictionary keys, since any Python object can be a dictionary value. Dictionary keys must be immutable objects (they must define a hash function); lists are not immutable, but tuples are. > And is it also possible > to put multiple lists in a dictionary for one key? I'm not sure what this means. Tuples can contain tuples as elements, so you could always make a higher-level tuple out of the tuples you want to has as "one key," if that's what you mean. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ People are taught to be racists. \__/ Jose Abad Fauxident / http://www.alcyone.com/pyos/fauxident/ A "faux" ident daemon in Python From gerhard.haering at gmx.de Sun Sep 1 22:37:58 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Mon, 2 Sep 2002 04:37:58 +0200 Subject: curses: AttributeError: initscr In-Reply-To: References: Message-ID: <20020902023758.GA5333@lilith.ghaering.test> * Cesar [2002-09-01 22:22 -0400]: > in the same directory where my script live, there was an old file named > curses.py. Then the instruction : "import curses" imported the bad one... You're not the first one to have this kind of problem. A way to debug such problems is to start Python with the option "-v" or even "-vv", which helps you track down where modules are really loaded from. -- Gerhard From alet at unice.fr Wed Sep 18 08:19:09 2002 From: alet at unice.fr (Jerome Alet) Date: Wed, 18 Sep 2002 14:19:09 +0200 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: <3D886F3D.9AE251F9@unice.fr> Lee Gray wrote: > > I'm a fairly new programmer with experience in ASP/VBScript/DHTML. > Other than small utilities, so far I've mostly written ASP apps to > talk to an Oracle database on HP/UX, with Windows NT/2000 clients, and > I've done maintenance work on VB and Oracle Forms apps. Perhaps this is really silly, but why don't you show Zope to your boss ? http://www.zope.org/ not really a GUI, though hth Jerome Alet From yuba at cyberback.com Sat Sep 21 14:33:33 2002 From: yuba at cyberback.com (Greg & Janet LINDSTROM) Date: Sat, 21 Sep 2002 13:33:33 -0500 Subject: mySQL and Python 2.2 Message-ID: <000801c2619d$64c3aba0$f8ffa8c0@lindstrom> Hello- I am trying to convert from gadfly to mySQL for my database needs on my Windows 98 box. I have installed mySQL and it works (I have created my tables and can manipulate them manually), and have downloaded mySQL-python-0.9.1, but when I python setup.py build, I get an error about cl.exe not existing (and, sure enough, it doesn't :-). I'm running Windows 98 with Activestate Python2.2. Any help you could supply (including code snippets of how to get connected to MySQL once I get it running) would be appreciated. --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From dag at animagicnet.no Fri Sep 20 04:37:43 2002 From: dag at animagicnet.no (Dag) Date: 20 Sep 2002 08:37:43 GMT Subject: finding last match in a file References: <87r8fplvq4.fsf@smtp.blueyonder.co.uk> Message-ID: In article <87r8fplvq4.fsf at smtp.blueyonder.co.uk>, Keith O'Connell wrote: > Dag writes: > >> I have a number of very large files where I have to find the last line >> which matches a certain experssion. Currently I'm simply opening the >> file and looping through it noteing each time a line matches and at the >> end of the loop I see which was the last match. However this is very >> slow and inefficient. Is there some way to read through the file >> backwards and simply find first match starting from the end of the file. >> The files are really too big to read the entire thing into memory. > > > Would you not be able to use grep with the "-n" option. It will list > all your matches with the lines numbered so you can see the last match > having the highest line number. If you then use wc on the file you will > get the total number of lines. Take one from the other and you can see > how far from the end your last match is. > > That seems to easy - Have I misunderstood you question? The problem is that greping through large files with a fairly complex regexp is taking far too long, esp. when I know that the last occurance is almost always within the last 100 lines. Dag From delaray at hotmail.com Mon Sep 16 19:00:02 2002 From: delaray at hotmail.com (Raymond de Lacaze) Date: Mon, 16 Sep 2002 23:00:02 GMT Subject: International Lisp Conference 2002 Message-ID: ========================================================== ASSOCIATION OF LISP USERS (ALU) INTERNATIONAL LISP CONFERENCE 2002 (ILC 2002) HOLIDAY INN - FINANCIAL DISTRICT SAN FRANCISCO, CALIFORNIA SUNDAY, OCT. 27TH - THURSDAY, OCT. 31ST =========================================================== CALL FOR PARTICIPATION =========================================================== Registration deadline: September 31st, 2002 NEW: Competitions 1. Dynamic Languages RoboCup Simulation League Competition 2. Chatterbot Competion Website: http://www.international-lisp-conference.org/ =========================================================== The Conference ------------------- The Asociation of Lisp Users (ALU) is proud to announce the International Lisp Conference 2002. The conference will take place at the Holiday Inn in San Francisco's Financial District from October 27th through October 31st. At the start of the 21st century we see the challenges ahead: Applications will be more dynamic than ever and will be part of the fibers of the Web, software and hardware robots will be our assistants, and biology will be source of both computational problems and programming metaphors. Applications will be customized to individuals who happen upon them, our needs and desires will be served by artificial beings, and our software may more accurately resemble a termite nest than Rube Goldberg inventions. Will our mainstream concepts, approaches, and languages hold up? Where might we turn for progress, inspiration, and technology? Was it right in front of us all along? The International Lisp Conference addresses these questions and more. This four-day conference will bring together a mesh of brilliant minds from a diverse international community that involves or borders the Lisp family of languages. The conference will be uniquely multi-themed in nature, and each day will paint a different theme. The themes are Lisp and Functional Languages, Web Applications, Robotics and Bioinformatics. We have gathered an impressive list of distinguished speakers from each of these communities that promise to deliver a captivating a stimulating conference experience. ============================================================== REGISTRATION Registration information is available at: http://www.international-lisp-conference.org/Overview/LC02-Registration.html ============================================================== MORE INFORMATION For more information, again, please visit the website: http://www.international-lisp-conference.org/ or contact Raymond de Lacaze at delaray at hotmail.com ================================================================ From emile at fenx.com Sun Sep 22 13:34:49 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 22 Sep 2002 10:34:49 -0700 Subject: Smalltalk vs. Python and COM was Re: Byte Magazine and Smalltalk References: <3d87a686@tobjects.> <3d87dd7c$1@tobjects.> <20020918.115128.1605894428.1527@cybermesa.com> Message-ID: GerritM: > but also described extensively in "Python programming on Win32" by Mark > Hammond and Andy Robinson, ISBN 1-56592-621-8. I am using the ActiveState > distribution, which is a complete distribution including this win32 stuff. > > In short highly recommended! > Seconded. If you've got the ActiveState distribution installed, take a look at PYTHONHOME\Lib\site-packages\win32com\HTML\QuickStartServerCom.html -- Emile van Sebille emile at fenx.com --------- From erict at millfilm.co.uk Tue Sep 17 04:32:08 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Tue, 17 Sep 2002 09:32:08 +0100 Subject: how to cast an instance id Message-ID: <3D86E888.90AF569@millfilm.co.uk> It there a way to create a new reference of an object from the string representation of its id? Thanks for any help. class foo: def info(self): print self a = foo() a.info() ccc = "newa = 0x%x" % id(a) exec(ccc) From h.g.normann at gmx.de Sat Sep 28 13:50:38 2002 From: h.g.normann at gmx.de (Hans - G. Normann) Date: Sat, 28 Sep 2002 19:50:38 +0200 Subject: how to create QLineEdit.focusOutEvents? References: Message-ID: Phil Thompson wrote: > > Sub-class QLineEdit and re-implement focusOutEvent() in your sub-class. > OK, nice to hear, but it is my first project. Normally im coding in Delphi. Who can give an very small example? from qt import * class Form1(QDialog): def __init__(self,parent = None,name = None,modal = 0,fl = 0): QDialog.__init__(self,parent,name,modal,fl) if name == None: self.setName('Form1') self.resize(216,77) self.setCaption(self.tr('Form1')) self.LineEdit1 = QLineEdit(self,'LineEdit1') self.LineEdit1.setGeometry(QRect(60,25,116,22)) #this shoul hav an focusOutEvent Hans From jepler at unpythonic.net Wed Sep 11 18:46:01 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Wed, 11 Sep 2002 17:46:01 -0500 Subject: [FEEDBACK] Is this script efficient...is there a better way? In-Reply-To: <200209111453.23751.shalehperry@attbi.com> References: <200209111453.23751.shalehperry@attbi.com> Message-ID: <20020911174559.A1555@unpythonic.net> On Wed, Sep 11, 2002 at 02:53:23PM -0700, Sean 'Shaleh' Perry wrote: > As a final comment you need to be aware that the more keywords you look for > the slower this will be. However there is not a way to get around that, it > is just something to keep in mind. With a good, simple Regular Expression like literal1|literal2|... the time spent searching one string for the compiled RE should be only proportional to the number of characters in the scanned string (It's just a big table of state transitions). This is more cycles per character than a simple comparison, but for some number of comparisons N you start to win. I hope that Python's implementation of REs has this property, but I'm not certain. Needing to support things like backrefs and lookahead-assertions blows this nice simple model of REs out of the water. Jeff From nmichael at yahoo.com Fri Sep 6 14:35:14 2002 From: nmichael at yahoo.com (Neophytos Michael) Date: 6 Sep 2002 11:35:14 -0700 Subject: Computing directory sizes problem Message-ID: Dear Python experts, I wrote the following function to compute the size of a directory (being new to python there maybe better ways to do this - if so please advice). It works quite well except when the directory in question contains files whose names that are not made up of ascii (english) characters (this typically happens on my machine for my non-english mp3 files). For those files os.path.isfile returns false and so their sizes are not added in the total sum. All this is on win 2k. Any help would be greatly appreciated. Thank you, Neophytos -------------------------------------------------------------------- import os; import os.path; def dirSize(p): def visit(arg, dirname, names): paths = map(lambda x: os.path.join(dirname, x), names); files = filter(os.path.isfile, paths); arg[0] += reduce(lambda x,f: x + os.path.getsize(f), files, 0); siz = [0]; os.path.walk(p, visit, siz); return siz[0]; -------------------------------------------------------------------- From loewis at informatik.hu-berlin.de Mon Sep 16 03:28:20 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 16 Sep 2002 09:28:20 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> Message-ID: Michael Schneider writes: > Could someone please explain to a "confused" python user. Why the > current version of stackless python would not be distributed like > threads??? Very easy: because nobody makes it so. That, in turn, is because nobody works on making it so. Christian (rightfully) points out that this is not his obligation: this is free software, he is not obliged to do anything - unless you pay him to do something. Nobody else is obliged to incorporate Stackless into Standard Python either. If you want this to happen, contribute. Regards, Martin From kkto at csis.hku.hk Sun Sep 8 09:39:30 2002 From: kkto at csis.hku.hk (Isaac To) Date: 08 Sep 2002 21:39:30 +0800 Subject: python program to watch a file - example. References: Message-ID: <7ielc48ust.fsf@enark.csis.hku.hk> >>>>> "Wayne" == Wayne R writes: Wayne> I am trying to write a python program that will run as a deamon Wayne> and watch a file for data to arrive and then wake up and perform Wayne> duties on that data. I found ways to make a python program run Wayne> as a deamon but I am at a loss to find anything related to Wayne> watching a file for data so that it can then process the data. I Wayne> didn't really want to do a sleep loop or something like, I am Wayne> sure there is a better way. Wayne> Any ideas or links to more info? See this: http://oss.sgi.com/projects/fam/ Basically, the established interface to access such functionalities in OS, if implemented, is the C++ library called FAM (File Alteration Monitor). Perhaps you have to write a module to make it accessible from within Python. Internally, IRIX use the /dev/imon device to provide such functionality. http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?imon+7 Linux has the fcntl called "F_NOTIFY" (see Documentation/dnotify.txt in your kernel source). Other OS probably has no interface to get it done, so you are back to a timed loop. Regards, Isaac. From jkraska at san.rr.com Sun Sep 29 12:34:35 2002 From: jkraska at san.rr.com (Courageous) Date: Sun, 29 Sep 2002 16:34:35 GMT Subject: What does Python fix? References: <87znu1rugt.fsf@pokey.henrik-motakef.de> Message-ID: >> No, I'm talking about how newbies tend to react when you tell them >> that block structure in Python is determined by indentation. > >What do newbies care? I'm sure if they have a problem with indentation for >blocks, they're going to have more trouble with remembering to put additional >punctuation either side of the blocks, in the right places... > >Unless, of course, your "newbie" is actually someone who has had the C-style >brace crap engraved on their mind before encountering Python... When he's referring to "newbies" he means people who already know how to program. Either that, or he's misinformed. Real newbies aren't baffled at all by using indentation for scope. C// From bokr at oz.net Fri Sep 6 16:30:38 2002 From: bokr at oz.net (Bengt Richter) Date: 6 Sep 2002 20:30:38 GMT Subject: Interrupting Python References: Message-ID: On Fri, 6 Sep 2002 13:26:27 -0400, "Bob Easton" wrote: >I have a script that can run, accessing network resources, for several days. >Since the script does not normally need keyed input, exception processing started by crond or such? >does not raise the keyboard exception until after the program ends normally. >I would like to be able to interrupt if from the keyboard, but have not >learned the trick. How can I do this? > Doesn't this work on your system? Or is all the time spent outside the python interpreter where the SIGINT signal might go elsewhere? Will Ctrl-Break do anything? Look into the signal module for ways to write your own handlers etc. man kill if you're on unix. [13:25] C:\pywk\pi>type catchctlc.py i=x=0 def foo(n): global i,x for i in xrange(n): x = i**100 if __name__ == '__main__': import sys try: foo(int(sys.argv[1])) # call your thing here instead except KeyboardInterrupt: print 'Interrupted by Ctrl-C' else: print 'Exited w/o interrupt' print 'FHOI, the last i**100 x value: %s**100 = %s' % (i, x) [13:32] C:\pywk\pi>catchctlc.py 1000 Exited w/o interrupt FHOI, the last i**100 x value: 999**100 = 904792147113709042032214606239950347800488416333 469929276204638572786486592967687651442293753075422163470827543775910358772483632664400945 560381166977421367930719070025493287934646681492648403959754575431541487824089366478208362 425806884425205853497846463239410463810703487931177116401063304949900001 --- here I hit Ctrl-C pretty quickly after starting the program: [13:32] C:\pywk\pi>catchctlc.py 1000 Interrupted by Ctrl-C FHOI, the last i**100 x value: 214**100 = 688589417268581026354513628323939985152292357234 549348854713726783654348445214825147860269910421564660573125261812017623244964892234617683 915075029738282499638533043036366826058088415904236592773165115757274885063575866471121351 34001 Regards, Bengt Richter From dsavitsk at e-coli.net Tue Sep 3 00:13:42 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Tue, 03 Sep 2002 04:13:42 GMT Subject: opening 'file open' dialog from console Message-ID: I would like to open a file open dialog from a console on windows (2000). I do this now using the line >>> from tkFileDialog import * >>> fileName = askopenfilename(filetypes=[(".txt", ".txt")], title="Select the file") but this opens a second window and leaves it there. what is the best way (tkinter or MFC) to do this w/o the second window? thanks, -doug From shalehperry at attbi.com Wed Sep 11 10:56:21 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 11 Sep 2002 07:56:21 -0700 Subject: deleting the first and the last character of a string In-Reply-To: <20020911105818.GC2054@partagas.as.de.cw.net> References: <20020911105818.GC2054@partagas.as.de.cw.net> Message-ID: <200209110756.21495.shalehperry@attbi.com> On Wednesday 11 September 2002 03:58, Manuel Hendel wrote: > I got a file with fields seperated by a "|". The problem is that there > is also a "|" at the beginning and at the end of each line although > there no fields in front or behind these "|". Now I want to delete > these two "|". Is there anything which says delete the first or last > character of a string? I checked the string module on the web, but I > couldn't find anything. > >>> s = '|f|o|o|' >>> s.strip('|') 'f|o|o' and of course the equivalent strip call from the string module. From pipa at rush.avalon.hr Mon Sep 23 03:31:01 2002 From: pipa at rush.avalon.hr (rush) Date: Mon, 23 Sep 2002 09:31:01 +0200 Subject: Smalltalk vs. Python and COM was Re: Byte Magazine and Smalltalk References: <3d87a686@tobjects.> <3d87dd7c$1@tobjects.> <20020918.115128.1605894428.1527@cybermesa.com> Message-ID: "Pino Gargiulo" wrote in message news:amkpk0$or2$1 at fe2.cs.interbusiness.it... > Anybody care to give some advice? I played around with DST but never looked > much at the existance of a COM wrapper/interface. Dolphin Smalltalk has nice interface to windows (and COM), and it is very comfortable to work with. rush www.rush.avalon.hr From max at alcyone.com Thu Sep 5 18:10:31 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 05 Sep 2002 15:10:31 -0700 Subject: Graham's spam filter References: <3D647B4B.28D9BF04@alcyone.com> <3D655AE6.A097AA25@alcyone.com> <3D770156.2E55864C@alcyone.com> <3D77AC75.B9B7F27@alcyone.com> Message-ID: <3D77D657.DE280373@alcyone.com> Christopher Browne wrote: > Quoth Erik Max Francis : > > > Spammers are hitting upon the strategy, though, of sending emails in > > which the body consists of nothing but a completely encoded base64 > > MIME part. So in that case, the entire body of your message would > > consist solely of your "base64encoded" token. So in the general > > case of any kind of spam filter (not just limited to a Graham ^ > > filter), it's questionable how useful this will be, unless you plant > > to always filter against that token, presuming it to always indicate > > spam. > > I've been using naive Bayesian filtering for years; I don't assume > that _any_ particular token indicates _any_ particular result. I thought I made it clear that I was discussing spam filters in general, not just Graham/Bayesian filters. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From gmcm at hypernet.com Sat Sep 21 12:09:42 2002 From: gmcm at hypernet.com (Gordon McMillan) Date: 21 Sep 2002 16:09:42 GMT Subject: Creating a standalone embedded Python app. References: Message-ID: Allen Unueco wrote: > I'm looking for a way to somehow bundle the Python modules that my > embedded application uses. I would like to be able to distribute an > executable file that would work without having Python installed on the > system. > > I would rather have everything in one file but having the modules in a > separate bundle (pickle?) would be workable. People have used Installer for this. http://www.mcmillan-inc.com/installer_dnld.html You'll need to dive under the covers. You'll need to figure out how to create an archive that has the modules you need, and you'll need to look at source/common/launch.c & fit that in with however you're starting Python. -- Gordon http://www.mcmillan-inc.com/ From Janssen at rz.uni-frankfurt.de Tue Sep 17 04:55:25 2002 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Tue, 17 Sep 2002 10:55:25 +0200 Subject: problems getting a single item out of a list References: Message-ID: <3d86ee83@nntp.server.uni-frankfurt.de> fields[2] for item with *index*-nr 2 Manuel Hendel wrote: > I try to get a single item out of a list, but after this, the single > item is stil a list item. > > domainfield = fields[3:4] > > I just want to get a new variable with a the value of the 3rd item of > the list fields. > > Can anyone help? > > Thanks, > Manuel > From chris.gonnerman at newcenturycomputers.net Thu Sep 19 08:13:05 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 19 Sep 2002 07:13:05 -0500 Subject: Larry Wall's comment on python... References: Message-ID: <006501c25fd5$ecc80740$0101010a@local> ----- Original Message ----- From: "Matt Gerrans" > One of the niftiest things about Python is you never have to > argue about whether you should put your curlies in the wrong > place, like this: > > void foo() { > //... > } > > ...or whether you should place them correctly, like this: > > void foo() > { > //... > } Them's fightin' words, son... :-) > It saves the world from a lot of unnecessary creation and > release of hot air (so Python has probably done more to help > reduce the greenhouse effect than any other software > technology!). I just like that I don't have to type the #!$&@!! things anymore. No smiley this time... I really hate typing curly after curly. It makes me wonder that anyone *likes* the freakin' things so much that they named a LANGUAGE after them. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From jarober at gosmalltalk.com Sun Sep 22 14:33:19 2002 From: jarober at gosmalltalk.com (James A. Robertson) Date: Sun, 22 Sep 2002 18:33:19 GMT Subject: Smalltalk vs. Python and COM was Re: Byte Magazine and Smalltalk References: <3d87a686@tobjects.> <3d87dd7c$1@tobjects.> <20020918.115128.1605894428.1527@cybermesa.com> Message-ID: VW does support being a COM server - we have customers using it that way. Load COMAll and look at the examples On Sun, 22 Sep 2002 19:30:57 +0200, "Pino Gargiulo" wrote: > >"GerritM" wrote in message >news:amkqfs$ldg$1 at reader1.tiscali.nl... >> Long long ago I worked in a large scale Objective-C project. Objective-C >> inherited many of its good characteristics from Smalltalk. Now I am using >> Python quite a lot. It has again a lot of the good (dynamic) >> characteristics, with on top an excellent set of predefined modules. One >of >> them are the win32 modules by Mark Hammond, documented on line of course, >> but also described extensively in "Python programming on Win32" by Mark >> Hammond and Andy Robinson, ISBN 1-56592-621-8. I am using the ActiveState >> distribution, which is a complete distribution including this win32 stuff. >> >> In short highly recommended! > >Gerrit > >Thanks for your advice and prompt reply! > >If I understand you correctly you are suggesting that Python is the way to >go >for COM m$ API rather than Smalltalk .. again Id like to hear suggestions >on which product. My dabbling experience is just with VWNC > >TNX again > >Pino > > > James Robertson Product Manager, Cincom Smalltalk From rm at no-mail.com Thu Sep 12 13:07:40 2002 From: rm at no-mail.com (Roy Marteen) Date: Fri, 13 Sep 2002 02:07:40 +0900 Subject: Larry Wall's comment on python... References: Message-ID: <20020913020740.2dae5bb6.rm@no-mail.com> On 07 Sep 2002 05:25:07 GMT Tim Daneliuk wrote: > Roy Smith wrote: > > > Writing for a machine which only has 256 bytes of RAM gives you a > > somewhat different outlook on programming :-) > > The Microchip PIC 16F84A chip I have been using as *68* bytes of RAM - > well RISC register file, really, but its the same thing - 32 bytes of > EEPROM, and a whopping 1K of flash memory for storing the program > itself. And yes, it does give you a whole different perpective on > programming... Well... it reminds me when I was young, and we had to program using ABACUS. It was really somewhat different outlook on programming. From aleax at aleax.it Fri Sep 20 05:20:57 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 09:20:57 GMT Subject: What the heck? open() requires an integer? References: Message-ID: Fausto Arinos de A. Barbuto wrote: > The open() function is returning me a strange error. > An attempt to create an output file with > > f = open("output.txt","w") > > yields the following error: > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: an integer is required > > That happens when I am using either Pythonwin or > IDLE 0.8, but not in interactive mode. In this latter > case I can open, write to and close a file OK. > > What's the matter? Thanks in advance! I'd be willing to bet that you did what you SHOULDN'T do, specifically a statement from somewhere import * before this point in your interactive session. I'd lay good odds that the 'somewhere' is os. Don't do it. "from ... import *" tramples all over your namespace: after you use it, how can you know WHAT function object is referred to by any given name? Well, if you "print open" you could be able to tell, at least in Python 2.2...: >>> print open >>> from os import * >>> print open >>> So, when you're calling open after "from os import *", you're really calling os.open -- and THAT one does indeed require an integer (as its second argument). A suggestion: forget all about the existence of statement "from" until you feel you have totally mastered Python. I think you'll have an easier time learning, using, and mastering Python, if you ALWAYS use the import statement when you need to do imports, rather than using from. (The "from ... import *" is the main issue, but there are others: e.g., built-in reload won't do what you expect if you've used statement from -- only if you've used statement import). Alex From erict at millfilm.co.uk Tue Sep 17 11:15:22 2002 From: erict at millfilm.co.uk (Eric Texier) Date: Tue, 17 Sep 2002 16:15:22 +0100 Subject: how to cast an instance id References: <3D86E888.90AF569@millfilm.co.uk> Message-ID: <3D87470A.CBD72239@millfilm.co.uk> "Gon?alo Rodrigues" wrote: > AFAIK there isn't - You probably have to go down the bowls of the C > implementation to do it. But why would you need such a contortionist's > act? Yes I know it sound a little bit twisted. > If you explain your problem maybe the people here in the list can > figure out a Pythonic way to do it. Here is why (simplification) I designed a generic class which is customizable through a python like scripting. Script let you instantiate, add, set/get attribute and much more... script example: taskName = "ExecBatch" # default name ARGUMENT : taskName = '%(taskName)s' taskRef = Fac.createInstance( "progCommand" ,taskName) print taskRef,"created",taskRef.getName() taskRef.Set(command = "someExe -batch") top.addChild(taskRef) Now, I would like to give the user some way to save preference, and for consistency I tought it will be nice to be able to have a script of the same kind: ataskid = 0 ARGUMENT : 'ataskid = 0x%(taskName)x' if id != 0: ataskRef = Fac.getInstance(id) if ataskRef != None: ataskRef.Set('whoToTell',value = ['someOne','someoneElse']) ataskRef.Set('sendEmail',value = 1) > > Best regards, > Gon?alo Rodrigues -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Tue Sep 10 03:00:16 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 10 Sep 2002 09:00:16 +0200 Subject: Python 2.3 References: <3d7cfc19_5@news.newsgroups.com> <3D7D7410.4070000@earthlink.net> Message-ID: Hans Nowak writes: > > There's a PEP, but it doesn't look like this will be in 2.3: > > http://www.python.org/peps/pep-0239.html > > I don't know what the status of this PEP is, BTW... it's not deferred > or rejected, which suggests this is still under consideration. Yes, it is. However, it is no target for Python 2.3, either - just look at the list of open issues. Contributions are welcome, but some of these issues are really tricky. Regards, Martin From pinard at iro.umontreal.ca Tue Sep 3 15:19:44 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Tue, 03 Sep 2002 15:19:44 -0400 Subject: efficient list merging In-Reply-To: (theoryboy@my-deja.com's message of "3 Sep 2002 11:12:38 -0700") References: Message-ID: [Peter Saffrey] > I have two lists of lists of strings which I would like to merge > efficiently without repeats. [...] Or is there a better way? I am not sure about the relative speed of everything, but I would be tempted to try: dict(zip(list1 + list2, [None] * (len(list1) + len(list2)))).keys() It seems to work: >>> list1 = list('abcdebxyz') >>> list2 = list('pqqr') >>> list1 ['a', 'b', 'c', 'd', 'e', 'b', 'x', 'y', 'z'] >>> list2 ['p', 'q', 'q', 'r'] >>> dict(zip(list1 + list2, [None] * (len(list1) + len(list2)))).keys() ['a', 'c', 'b', 'e', 'd', 'q', 'p', 'r', 'y', 'x', 'z'] -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From tjabo.kloppenburg at unix-ag.org Wed Sep 11 05:34:03 2002 From: tjabo.kloppenburg at unix-ag.org (Tjabo Kloppenburg) Date: Wed, 11 Sep 2002 11:34:03 +0200 Subject: ANN: lfm 0.9 In-Reply-To: <1031161776.1238.0.camel@lethe.infernus.org> References: <1031161776.1238.0.camel@lethe.infernus.org> Message-ID: <20020911113403.0d36d9c5.tjabo.kloppenburg@unix-ag.org> I?igo Serna wrote: IS> After 6 months since last release, I bring you a new version IS> (0.9) of lfm. Read more and download it in next link:... I tried it, but had some problems because lfm tried to use "python2" as interpreter in some files (the #!/usr/bin/env line). Normally I'ld expect a program to use the interpreter I use to call setup.py: "python2.2 setup.py build" I missed an uninstall feature aswell, because the files in /usr/bin were not easy to find (files copied with old file dates?). tk. -- Tjabo Kloppenburg --=- In 103.54 Tagen ist Weihnachten! -=-- -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ny_r_marquez at yahoo.com Tue Sep 10 10:18:00 2002 From: ny_r_marquez at yahoo.com (R.Marquez) Date: 10 Sep 2002 07:18:00 -0700 Subject: Windows/DOS: double clicking a .py file References: <3d7d6f26@news.sentex.net> Message-ID: <8a27e309.0209100618.46640eaa@posting.google.com> What I do is the following: try: something() except: print "Program encountered an error:" print sys.exc_type print sys.exc_value os.system("pause") -Ruben Peter Hansen wrote in message news:<3d7d6f26 at news.sentex.net>... > David LeBlanc wrote: > > cmd.exe will accept a flag telling it to stay open after something is run. > > You can create a shortcut along the lines of: > > > > cmd /K python myscript.py > [snip rest] > > Although, unfortunately for the OP who has users on Win98, cmd.exe does > not exist except in NT/2K/XP. > > -Peter From aahz at pythoncraft.com Thu Sep 12 12:20:11 2002 From: aahz at pythoncraft.com (Aahz) Date: 12 Sep 2002 12:20:11 -0400 Subject: class variable won't icrement! References: <3d8054ef$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: In article , Steve Holden wrote: >"Aahz" wrote in message >news:alq9hf$bn$1 at panix1.panix.com... >> In article , >> Eric Brunel wrote: >>> >>>I always found that inheritance of class attributes to instance attributes >>>was really misleading, and I even think it would be better if it were >>>simply removed from Python. IMHO, it would far more conform to the >>>"explicit is better than implicit" rule that is one of the basis of Python. >> >> If I think of it as "scope resolution" rather than "inheritance", I find >> that it makes more sense. It works exactly the same way as hiding a >> global with a local. > >Well, not quite exactly the same way. If a local hides a global >then there's no way to access the global without explicit use of a >namespace. Exactly! The only difference is that it's an error in a function to attempt to read a global and then later modify it (in the absence of the global statement). >A class variable is available by instance-qualified name up until the time >the instance variable with the same name is created, which is why statements >like > > self.var += 1 > >can be so confusing. Especially when you compare operations that give >different results for mutable and immutable objects. It might make sense to tighten the rules for modifying class variables, just the way this gives an error: x = 1 def foo(): print x x = x + 1 The mutable/immutable thing is exactly the same for functions and instances. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From kowald at molgen.mpg.de Tue Sep 3 04:40:29 2002 From: kowald at molgen.mpg.de (Axel Kowald) Date: Tue, 03 Sep 2002 10:40:29 +0200 Subject: string reading bug in ActiveState Python 2.2 ? Message-ID: <3D74757D.1010405@molgen.mpg.de> Hello, I'm using ActiveStates Python 2.2.1 under win2000 to read in the attached text file and it seems that python is only reading part of the string. After fp = open("bla.txt") z = fp.read() print len(z), z I see that only 11 of the 15 characters have been read. I know they are non-printable characters, but that shouldn't matter, should it ? Using another python on one of our unix machines everything works as expected and all 15 chars are read in. Is that there something special about windows that I should know, or is this a bug in ActiveStates Python ? Many thanks, Axel Kowald -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: bla.txt URL: From viking_kiwi at yahoo.com Fri Sep 6 14:25:55 2002 From: viking_kiwi at yahoo.com (Rod Stephenson) Date: 06 Sep 2002 20:25:55 +0200 Subject: Larry Wall's comment on python... Message-ID: Slashdot has a list of questions posed to Larry Wall (perl). When asked his thoughts on other scripting languages, he makes the following observation about python "Python is cool to look at small bits of, but I think the "outline" syntax breaks down with larger chunks of code. I'm with Aristotle on the structure of discourse--a story should have a beginning, and middle, and an end. So should blocks" I'm not quite sure what he's trying to get at here - I guess that for a long heavily indented chunk of code, you could lose track of the overall structure, but I don't write code this way. Any comments? From dsiroky at email.cz Sun Sep 29 09:30:10 2002 From: dsiroky at email.cz (David Siroky) Date: Sun, 29 Sep 2002 15:30:10 +0200 Subject: Graphics library Message-ID: Hi! I'd like to know, which library for creating images (like libgd) is "the best". I want to use it with Python. Thanx David From chironsw at swbell.net Wed Sep 18 16:58:16 2002 From: chironsw at swbell.net (Greg Goodman) Date: Wed, 18 Sep 2002 20:58:16 GMT Subject: Source code References: Message-ID: <3D88E8FC.C8D51FC@swbell.net> > If I am going to sell my programs, I do not want somebody else to take my > sourcecode, change a few things, and sell it If you copyright your work and release it under a restrictive license, then someone might pirate your work, but it would be illegal and you would have recourse through the courts. If you obfuscate and compile your work, then a determined pirate can *still* steal your work. Unless you copyright it and release it under a restrictive license, that "piracy" may not be illegal and you might have no effective recourse. In my estimation, the risk to your potential income will be reduced more by legitimate legal protections than by a technological barrier, particularly a weak one. (And, as has been noted before, virtually all the technological protections for software are weak.) Regards, Greg Goodman From lordmacro at hotmail.com Thu Sep 19 21:45:05 2002 From: lordmacro at hotmail.com (Tom Widrick) Date: Thu, 19 Sep 2002 20:45:05 -0500 Subject: implementing reduce protocol in C Message-ID: <3D8A7DA1.7090506@hotmail.com> I have an extension type I'm trying to implement the reduce protocol with. I have successfully gotten type instances to pickle but cannot unpickle them. I get the following error. newRoot = cPickle.loads(d) TypeError: ('argument list must be a tuple', , None) By following the instructions at http://www.python.org/doc/current/lib/node65.html I have the following C code. static PyObject * myobj_reduce(self) MyObject *self; { PyObject *args; PyObject *result; args = PyTuple_New(5); if(args == NULL) return NULL; PyTuple_SET_ITEM(args, 0, self->po_name); PyTuple_SET_ITEM(args, 1, self->po_parents); PyTuple_SET_ITEM(args, 2, self->po_children); PyTuple_SET_ITEM(args, 3, self->po_doc); PyTuple_SET_ITEM(args, 4, self->po_dict); result = Py_BuildValue("(OOO)", self->ob_type, Py_None, args); return result; }; The type constructor wouldn't have worked as a call to unpickle the object so I've used basicnew instead. static PyObject * myobj_basicnew() { MyObject *self; self = PyObject_New(MyObject, &MyObject_Type); return (PyObject *)self; } and a setstate method which doesn't matter because the previous error occurs before accessing it. What is it that I am missing? Tom From mhammond at skippinet.com.au Wed Sep 18 22:08:30 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Thu, 19 Sep 2002 02:08:30 GMT Subject: COM object registration References: <4J_h9.19439$Ee4.59690@news-server.bigpond.net.au> Message-ID: dsavitsk wrote: > "Mark Hammond" wrote in message > news:4J_h9.19439$Ee4.59690 at news-server.bigpond.net.au... > >>dsavitsk wrote: >> >>>>>>a = win32com.client.Dispatch('ecp.MODULE_REGISTER2') >>>>> >>>Traceback (most recent call last): >>> File "", line 1, in ? >>> File "C:\Python\win32com\client\__init__.py", line 92, in Dispatch >>> dispatch, userName = >>>dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) >>> File "C:\Python\win32com\client\dynamic.py", line 81, in >>>_GetGoodDispatchAndUserName >>> return (_GetGoodDispatch(IDispatch, clsctx), userName) >>> File "C:\Python\win32com\client\dynamic.py", line 72, in >> > _GetGoodDispatch > >>> IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, >>>pythoncom.IID_IDispatch) >>>com_error: (-2147467259, 'Unspecified error', None, None) >> >>It is likely that an exception is being encountered that we can get at >>pretty easy. >> >>Add a named param "debug=1" to all UseCommandLine calls. Then, on both >>machines, start Pythonwin and select the debug trace collector. Rerun >>your tests and see if any additional interesting exceptions are reported. >> >>Mark. >> > > > This is the traceback, but I'm afraid it doesn't mean much to me. It is the > error that I got when using a VB client and where I get the 'localserver' > notion. > > in _Invoke_ with 1000 0 2 () > in _Invoke_ with 1000 0 1 (u'MODULE_REGISTER2',) > Registered: ecp.MODULE_REGISTER2 (for debugging) > Object with win32trace dispatcher created (object=None) > Traceback (most recent call last): > File "C:\Python\win32com\server\dispatcher.py", line 27, in > _CreateInstance_ > self.policy._CreateInstance_(clsid, reqIID) > File "C:\Python\win32com\server\policy.py", line 199, in _CreateInstance_ > myob = call_func(classSpec) > File "C:\Python\win32com\server\policy.py", line 634, in call_func > return apply(resolve_func(spec), args) > File "C:\Python\win32com\server\policy.py", line 624, in resolve_func > return getattr(module, fname) > AttributeError: 'localserver' module has no attribute 'regmodule2' The problem is that for some reason, the registration expects localserver.py to have a class named 'regmodule2'. I'm afraid I am not too sure exactly what is going on here and dont have time to setup a similar test environment - but after registration, you should be able to look in the registry for the objects you registered. These will nominate the module and class names used by this class. See what you can track down there. Mark. From kokohh at hotmail.com Thu Sep 5 19:15:53 2002 From: kokohh at hotmail.com (koko) Date: Thu, 05 Sep 2002 23:15:53 GMT Subject: web crawler help? Message-ID: is there any sample for basic web crawler, that ask for a starting url and log the url and extract the hyperlinks? thx From emile at fenx.com Thu Sep 26 19:19:13 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 26 Sep 2002 16:19:13 -0700 Subject: Who knows somefunction? References: <664e469667.69667664e4@icomcast.net> <3D9382AF.5070800@aon.at> <20020926221714.GA11579@sferacarta.com> Message-ID: Marco Mariani > Now you can harm yourself. :-) > > Tested with python 2.2.1 > ;-) FWIW, against current cvs it crashes when you do: from pointer import pointer x = range(3) y = id(x) del x x1 = pointer(y) print x1 Where's Houdini when you need him... -- Emile van Sebille emile at fenx.com --------- From andrew.thompson at ashecastle.com Tue Sep 24 05:12:52 2002 From: andrew.thompson at ashecastle.com (Andrew Thompson) Date: Tue, 24 Sep 2002 10:12:52 +0100 Subject: instance creation In-Reply-To: <265e380f.0209240052.4c2988f3@posting.google.com> Message-ID: <014901c263aa$904f6e30$4802a8c0@blair> Apologies for ' type(arg1)==type(string)... should read type(arg1)==type('abc') ' -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of Paul MG Sent: 24 September 2002 09:52 To: python-list at python.org Subject: instance creation Hi I am dabbling with Python and have run into a bit of an oddness. I have a class Appointment, with fields Title and Details. I want to allow two means of construction: 1) Providing Title and Details strings explicitly, to create a new instance. 2) Providing an ID, which causes that Appointment to be loaded from a backing store. Now in C++ or smalltalk, I would do one of - Provide two constructors: def __init__(self, name, details): self.name = name self.details = details def __init__(self, id): load(id) def load(self, id): i = open("appointment"+str(id)) self = pickle.load(i) - Provide a class method (creation method) to instantiate: def create(id): i = open("appointment"+str(id)) return pickle.load(i) However, much of this seems not to work. - Having two constructors seems to be illegal - or at least the second overwrites the first. - Assigning to 'self' in the load method seems to really not work! - Putting the create() method outside of the class works fine - but I want it to be a class method on Appointment, goddammit!:) Is there no way to do this? Any help would be appreciated, basically i am looking for the python idiom to do this, as my C++ and Smalltalk idiom's clearly aren't in the grain of the language! Thanks very much Paul MG -- http://mail.python.org/mailman/listinfo/python-list From loewis at informatik.hu-berlin.de Thu Sep 12 06:12:45 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 12 Sep 2002 12:12:45 +0200 Subject: Pickling slotted instances References: Message-ID: Andrew McNamara writes: > Instances using __slots__ can't be pickled - is there a fundemental reason > why this is so, or is it simply yet to be implemented? See python.org/sf/520644 for a longer discussion. > At first glance, a __getstate__ for a slotted class could be as simple as: > > def __getstate__(self): > attrs = [getattr(self, attr, None) for attr in self.__slots__] > return self.__slots__, attrs > > What am I missing? That won't work: it won't access the slots of the base type. Also, you are missing a __setstate__ implementation. Regards, Martin From sismex01 at hebmex.com Mon Sep 9 10:54:11 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 9 Sep 2002 09:54:11 -0500 Subject: Larry Wall's comment on python... Message-ID: Hmmm... I've found that block-delimiting-chars become like a drug to the brain; you don't really think about them until they're not available anymore, then the pain (well, kinda) starts, and there's whines ("whyyyy can't I use such-and-such delimiters for my python programs pleeze???"), and all that. Once you wean your brain off block-delimiter-chars, you begin to code more freely, much happier. Really! Another drug which is taken in great amounts by C++ and Java programmers are "private:" and "protected:" and "friends:" stuff, really hideous and much more sneaky, because they first convince you that you *need* them in order to make good programs, and it takes a bit more effort to wean young minds off them. ;-) -gus -- Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From user at domain.invalid Sun Sep 29 17:30:17 2002 From: user at domain.invalid (user at domain.invalid) Date: Sun, 29 Sep 2002 21:30:17 GMT Subject: tkinter & serial port Message-ID: Please excuse this if it is a FAQ. I'm new with Python/Tkinter, but have written LOTS of X windows code. This may be the root of my problem. My program needs to talk over a serial port to a device AND update the display. I get about 10 lines of text every second or so. Under X Windows, I would simply open the serial device and add it to the select list which would then cause Xt to give me a callback whenever there is input available. I can set the I/O port to understand lines which makes the whole thing neat and clean. How do I do this or its moral equivalent under Python so that it runs without modification under both BSD and Windows? The closest that I've been able to figure out is to poll the serial device a few times per second. This is ugly, involves overhead and generally not up to the standard of Python -- clearly I don't yet 'see the light.' Suggestions? Pointers? Ideas? From just at xs4all.nl Mon Sep 9 11:06:29 2002 From: just at xs4all.nl (Just) Date: Mon, 09 Sep 2002 17:06:29 +0200 Subject: Windows/DOS: double clicking a .py file Message-ID: Sorry if this is a Windows FAQ, I'm a newbie to Windows, but not to Python. If I double-click a Python script (or use the start command in the dos prompt) a new dos prompt window is opened and my program is run. The window goes away when the program is done. However, the window _also_ goes away when the program raises an exception, making it virtually impossible to actually _see_ the exception... Is there a way to keep the dos prompt window in this case? A py2exe-fied version of the program shows the same behavior, which leads my users to report problems like "the output file is mysteriously truncated" instead of "I'm getting a traceback. Here, have a look."... Any suggestions? This is with Python 2.2.1 on Windows 98, but a report like above came also froma WinXP user. Just From jmdeschamps at cvm.qc.ca Thu Sep 19 16:55:06 2002 From: jmdeschamps at cvm.qc.ca (jmdeschamps) Date: 19 Sep 2002 13:55:06 -0700 Subject: Tkinter: scrolling the canvas items AND widgets Message-ID: <3d06fae9.0209191255.63def2eb@posting.google.com> I'm trying to use canvas as a scrollable region to make dynamic entry forms (variable number of Entry fields). I would like to be able to scroll down the canvas if the fields go outside the visible region using scrollbars :) This code lets me scroll the graphical items but the widgets stay put using PythonWin 2.2.1 on Windows 2000 ********* import Tkinter root = Tkinter.Tk() # Create widgets canvas = Tkinter.Canvas(root) canvas.pack(side=LEFT) # Vertical scroll bar verticalScrollbar = Tkinter.Scrollbar(root) verticalScrollbar.pack(side=LEFT,expand=1,fill=Y) # Configure root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) canvas.config( height = 300, scrollregion = (0, 0, 100, 1000), yscrollcommand=verticalScrollbar.set ) verticalScrollbar.config( orient=Tkinter.VERTICAL, command = canvas.yview) # Draw on canvas canvas.create_polygon(10, 10, 300, 50, 10, 100) #Add widgets for i in range(1): f=Entry(canvas) f.place(x=10,y=10) root.mainloop() **** end code ******* With this, I can scroll the polygon but not the Entry field ??? Thanks in advance, Jean-Marc From Michael.Sparks at rd.bbc.co.uk Thu Sep 12 12:18:01 2002 From: Michael.Sparks at rd.bbc.co.uk (Michael Sparks) Date: Thu, 12 Sep 2002 17:18:01 +0100 Subject: wrapping yield ? Message-ID: Hi, I'd like to be able to wrap "yield" in a function - is that possible, and if not (my eading of stuff I've seen so far says not) are there any plans to make it possible? Whilst it may seem odd, I'd like to be able to do this: def my_generator(arg): dostuff.... while(1): waitForSomethingCheckingPeriodically() processit where def waitForSomethingCheckingPeriodically(): found = 0 while(not found): x = checkTheThing() if foundRightThing(x): found = 1 else: yield "foo" return x The reason for wanting to wrap this up is due to the waitForSomethingCheckingPeriodically is a sequence of code that I'd like to have in several different generators. The problem of course here is that "my_generator" doesn't create a generator due to not containing a "yield" keyword, whereas waitForSomethingCheckingPeriodically generates a generator, even though I don't want it to be one... The context here is of a piece of network server code, and wanting to be able to enforce relinquishing of control in the pieces of code that perform reads/writes, as well as connection acceptance etc. (basically I want to wrap up the yield call into the piece of code that should yield control, rather than rely on the user of the code being relied upon to yield in the right places) Having read: http://www.python.org/peps/pep-0255.html I suspect that what I'd like to do here wouldn't work, and what I really want is something more like: def_generator my_generator(arg): ... def waitForSomethingCheckingPeriodically(): ... And have the keyword (or something other than "yield") indicate that the definition is a generator, since that would solve this completely - which I not has been ruled out in that document, and I'm hoping things may've changed since then :-) If this is the wrong place to ask this q - apologies, I'd appreciate being pointed in the right direction :-) Regards & thanks in advance, Michael. From james.kew at btinternet.com Thu Sep 26 18:00:46 2002 From: james.kew at btinternet.com (James Kew) Date: Thu, 26 Sep 2002 23:00:46 +0100 Subject: Searching for and sorting files by date and compiling stats in Windows References: Message-ID: "A. Dimsdale and A. Moser" wrote in message news:MOKk9.66578$U7.23791943 at twister.socal.rr.com... > How can I do the following in Python: > * Search through networked Windows drives for the string "~w*.tmp" (* meaning > wildcard of course) in the filename os.path.walk and match a regular expression against each file in names on each callback. > * Calculate how much disk space is taken up by Word temp files by date modified > (i.e., files with "~w*.tmp" as their filenames with date modified in 2001 on > drive G: on SDspam01 use 75 MB total, files with "~w*.tmp" as their filenames with date modified in August 2002 on drive H: on DCspam04 use 60 MB total, etc.) os.stat on each matching file. > * Optimally, automagickally put this data into an MS Excel spreadsheet file win32com.client, but that's the easy part; the difficult part is working out how to use Excel's automation interfaces to do what you want to do. Dumping the data into a CSV file might be a half-reasonable substitute. James From skoranda at uwm.edu Thu Sep 26 13:32:39 2002 From: skoranda at uwm.edu (Scott Koranda) Date: 26 Sep 2002 10:32:39 -0700 Subject: fcntl module on Linux and nonblocking I/O Message-ID: <7e9d8e38.0209260932.ed2c78@posting.google.com> Hello, I just installed python 2.2.1 on my RH 7.3 Linux box and noticed that the fcntl module does not appear to have O_NDELAY, FNDELAY, or anything that appears similar. Python 2.2.1 (#1, Sep 26 2002, 11:55:24) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import fcntl >>> dir(fcntl) ['DN_ACCESS', 'DN_ATTRIB', 'DN_CREATE', 'DN_DELETE', 'DN_MODIFY', 'DN_MULTISHOT', 'DN_RENAME', 'FD_CLOEXEC', 'F_DUPFD', 'F_EXLCK', 'F_GETFD', 'F_GETFL', 'F_GETLEASE', 'F_GETLK', 'F_GETLK64', 'F_GETOWN', 'F_GETSIG', 'F_NOTIFY', 'F_RDLCK', 'F_SETFD', 'F_SETFL', 'F_SETLEASE', 'F_SETLK', 'F_SETLK64', 'F_SETLKW', 'F_SETLKW64', 'F_SETOWN', 'F_SETSIG', 'F_SHLCK', 'F_UNLCK', 'F_WRLCK', 'LOCK_EX', 'LOCK_MAND', 'LOCK_NB', 'LOCK_READ', 'LOCK_RW', 'LOCK_SH', 'LOCK_UN', 'LOCK_WRITE', '__doc__', '__file__', '__name__', 'fcntl', 'flock', 'ioctl', 'lockf'] Without such a constant defined in the fcntl module how can I make a pipe non-blocking? Sincerely, Scott From bokr at oz.net Mon Sep 16 15:50:53 2002 From: bokr at oz.net (Bengt Richter) Date: 16 Sep 2002 19:50:53 GMT Subject: read() file?? References: Message-ID: On 11 Sep 2002 18:27:48 +0300, Erno Kuusela wrote: >In article , >jubafre at brturbo.com writes: > >| I have a file with assembler instruction and i want read the lines >| of the file and put in a list of string, this is easy to do, but i >| don?t want to consider the caracteres "/" and the othes after him. > >| file.asm: >| ADD D1 /coment1 >| LDA D2 /coment2 > >try something like... > >def read_asm(filename): > out = [] > for line in open(filename).readlines(): > out.append(line.split('/')[0]) out.append(line.split('/')[0].rstrip()) # so as to get ['ADD D1', ...] not ['ADD D1 ', ...] > return out > A nit ;-) Alternatively, if you have 2.2, >>> [x.split('/',1)[0].rstrip() for x in file('file.asm')] ['ADD D1', 'LDA D2'] where the file is >>> file('file.asm').readlines() ['ADD D1 /coment1\n', 'LDA D2 /coment2'] Oops. Well, the missing final \n didn't hurt. Regards, Bengt Richter From gmurali at cs.uchicago.edu Tue Sep 17 11:52:15 2002 From: gmurali at cs.uchicago.edu (Murali Krishnan Ganapathy) Date: 17 Sep 2002 08:52:15 -0700 Subject: Windows Registry Manipulation Message-ID: <83f35bd6.0209170752.64e8119a@posting.google.com> I have seen people in this news group asking about a higher level access to the windows registry. I have written one. If people are interested, I can post the code here. This uses _winreg, so does not provide some things like Checking Access Permissions on Registry keys. This is not object oriented. But it is easy to build an OO interface on top of this. Some sample code: import winreg # Add a new acronym to the database winreg.SetAcronym('WIN',r'MICR\Windows\CurrentVersion') # MICR automatically expands to HKLM\SOFTWARE\Microsoft # and HKLM expands to HKEY_LOCAL_MACHINE # change a value winreg.SetValue(r'WIN\Explorer\Advanced\DontPrettyPath',1) # This will prevent explorer from showing files like "ALLCAPS" as "Allcaps" - Murali From jepler at unpythonic.net Sat Sep 21 18:05:08 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sat, 21 Sep 2002 17:05:08 -0500 Subject: Math optimization In-Reply-To: <6T5j9.145247$pX1.5195840@news2.tin.it> References: <6T5j9.145247$pX1.5195840@news2.tin.it> Message-ID: <20020921170507.A1641@unpythonic.net> Did you bother benchmarking? I'd be surprised to see a huge difference, since the overhead of the bytecode loop should be much much greater than the cost of a single division operation. Except for 'if 0' and a special variable (__debug__?) which can be 0, there is no constant folding in the compilation step. You could fake this by using def f(a, factor=3*5/7/2): return a/factor instead of def f(factor): return factor/(3*5/7/2) (the value of default arguments is computed once, when the function is created) Jeff From aleax at aleax.it Mon Sep 16 03:41:04 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 16 Sep 2002 07:41:04 GMT Subject: possibly OT - delete char? References: <3pch9.10253$Ee4.26056@news-server.bigpond.net.au> Message-ID: :B nerdy wrote: > im making a console app. i wish to clear the line. ive got 2 ideas > > - does python have a clear line method to clear the current text of line? > - is there a character which deletes the previous printed character when > printed? There is no cross-platform way to control text-mode consoles, as far as I know. For Unix-like platforms, your best best is most likely to use curses. For Windows, the effbot's Console package, http://effbot.org/efflib/console/ . Alex From rob at diespammerdieuselesspython.com Tue Sep 17 10:34:18 2002 From: rob at diespammerdieuselesspython.com (Rob Andrews) Date: Tue, 17 Sep 2002 14:34:18 GMT Subject: Good book choice? References: Message-ID: <3D873E8F.7060501@diespammerdieuselesspython.com> > > This isn't directed at the book mentioned (which is why I didn't quote > its name in this rant), rather at all books which come with CDs. I hate > it when books come with CDs. I'm perfectly capable of downloading the > source code used in the book, and in fact I prefer to hand-type it while > reading from the book anyway, to make sure I see every part of the > code. When a book comes with a CD, it is cumbersome to read portably, > which is the whole advantage of books, unless you take the CD out. And > if I take the CD out, then there is no doubt that it will get lost, or I > will be unable to return the book if dissatisfied, etc. Plus, you can't > tell me that the inclusion of a CD and the envelope/publishing used to > include the CD doesn't add a few units of currency to the book's cost. > > Poke this opinion full of holes, but when I buy a book, I want a book, > not a software package. The book should be good enough to stand on its > own without the "bonus" material on CD. I think twice about buying a > book that comes with a CD, to tell you the truth. > All perfectly valid sentiments, of course. But for the village in Nepal lacking bandwidth because they are still six months away from having a phone line (not as far-fetched an example as it may seem), an entirely different set of considerations may be found. I find myself on the middle path on this issue, since I rarely have personal use for the CDs, but find that they do make it easier to distribute Python in my fits of zealous advocacy. I have bandwidth, but no burner, and some are more interested in hearing me out if they don't have to face a long (in some cases, expensive) download before they even get to see if they would be interested. Rob Andrews From markus.vonehr at ipm.fhg.de Mon Sep 9 11:35:46 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Mon, 09 Sep 2002 17:35:46 +0200 Subject: compile error on SWIG file References: <3D7C55EE.D9278B1C@ipm.fhg.de> <3D7CB26B.2040706@users.sourceforge.net> Message-ID: <3D7CBFD2.4E7DFD1F@ipm.fhg.de> Hi, I only extended the std_vector example from the distribution with one function, see example.i included (there are templates inside). When I run SWIG with -c++ option, the warnings disappear in fact. But the error from the compiler is the same... Thanks, Markus /* File : example.i */ %module example %{ #include "example.h" %} %include stl.i /* instantiate the required template specializations */ namespace std { %template(IntVector) vector; %template(DoubleVector) vector; } /* Let's just grab the original header file here */ %include "example.h" Lyle Johnson schrieb: > > Markus von Ehr wrote: > > > compiling my c-file generated from SWIG > > (swig -c -python -o mvelib.c mvelib.i) > > with a setup-file, I receive the error: > > > > c:\programme\vc98\include\eh.h(32) : fatal error C1189: #Error: "eh.h > > is only for C++!" > > > > Anybody knows what I have to change? > > Is it a C++ library that you're wrapping (sounds that way)? If so, you'd > want to run SWIG with the -c++ option to tell it that. From rpm1deleteme at frontiernet.net Fri Sep 27 19:58:09 2002 From: rpm1deleteme at frontiernet.net (RPM1) Date: Fri, 27 Sep 2002 19:58:09 -0400 Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> <20020926164641.1753ebbb.ckasso@sprynet.com> Message-ID: > Chris Kassopulo writes: > > >>On 26 Sep 2002 10:56:45 -0700 >>pknotz at sandia.gov (Pat Notz) wrote: >> >> >>>@ = "at" >>>! = "bang" >>>. = "dot" >>>* = "star" Well, since ! is not pronounced "exclamation", why should __ be pronounced "underscore"? How about just a "sh" sound, since it kind of means hidden? "sh" init "sh" == __init__ or even "sh" init == __init__ I need another beer. From max at alcyone.com Thu Sep 5 15:01:18 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 05 Sep 2002 12:01:18 -0700 Subject: Privacy and Inheritance References: Message-ID: <3D77A9FE.68176A7F@alcyone.com> Eric Brunel wrote: > I just meant that Python has no way of enforcing "protectedness", as > leading double underscores (kind of) enforce privateness. As you say, > using > a single leading underscore in protected attribute names is merely a > convention, even if it's a strong one: Python won't prevent any use of > the > attribute, neither from sub-classes, nor from the "outside world". > Anybody > not knowing the convention can use these attributes in any way without > any > problem. That's right. Python takes the approach that "We're all adults here," and presumes that people will behave. In many languages the concept of restricted access can be circumvented in varying ways with increasing levels of ugliness, so you can think of restricted access as really a hint (albeit a very strong one in those languages where it is very awkward). Python just leaves these things at the hint level (with the exception of double underscore name mangling, which is a fairly recent addition). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From merman at snafu.de Tue Sep 17 10:20:50 2002 From: merman at snafu.de (T. Kaufmann) Date: Tue, 17 Sep 2002 16:20:50 +0200 Subject: newbie-question: private attributes Message-ID: <3D873A42.1070400@snafu.de> Hello everybody, I know that Python has no modifiers like Java/ C++: keywords like private, public and so on. What is the difference between the two attributes in this class? class Test: def __init__(self): self.__var1 = 1 # I think this is a private attribute self._var2 = 2 # ... and this? Maybe protected? Thanks for help. o-o Thomas From grabiller at 3dvf.net Wed Sep 25 10:24:56 2002 From: grabiller at 3dvf.net (Guy Rabiller) Date: Wed, 25 Sep 2002 16:24:56 +0200 Subject: Newbie References Question Message-ID: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> Hi, let say I have: i1 = 1 i2 = 2 and p = [i1,i2] How can I have: p=[*i1,*i2] rather than p=[**i1,**i2] as it is curently ? ( Sorry for this nasty hybrid syntax ) Textualy, how if I want that p[0] refere to the 'i1' container, and not to the refererence it contains ? What I want is that if now I set: i1 = 4 that automaticaly: p -> [4,2] and not keeping [1,2] Thanks in advance. -- guy rabiller 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net From sholden at holdenweb.com Sun Sep 29 06:34:26 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 29 Sep 2002 06:34:26 -0400 Subject: Pythonwin (win32all build 148) on Python 2.2.1 on Win2K, bogus syntax e References: Message-ID: <8IAl9.5016$pD4.2297@fe05> "A. Dimsdale and A. Moser" wrote ... > A. Dimsdale Fetus A. Moser writes: > > >"Neil Hodgson" writes: > > >>Aaron Dimsdale and Alex Moser: > > >>> Pythonwin barfed on the quote marks marked by carets, returning: "Failed > >>to run script - > >>> syntax error - invalid syntax". > > >> Try turning on View | End-of-line markers to see if you have non-standard > >>line endings such as pure carriage returns, which cause just this sort of > >>error. On Windows, you want line endings to be carriage return + line feed. > > >> Neil > > [snip] > > Well, I went in and manually edited the EOLs on every code line in the file. > (Fun fun fun.) As it turns out, the cause of the problem is likely the > difference between DOS-style and Unix-style EOLs. Alex and I jointly own an > account on my Linux box at home, where we keep the latest version of the script. > Alex does most of the coding on our script, and I just do other stuff like > looking over the code when it slaps him, adding fixes and/or minor features, > etc. Well, since he does most of the coding, he had the script on his work comp > when we were at work on Tuesday, and I had him upload it to my Linux box so I > could grab it from my work box by FTP, and through the Win-to-Linux-to-Win > transfer the EOLs apparently got funkified. > Thanks again for the EOL tip. > For future reference, make sure you use ASCII mode for FTP transfers (of text files, nach). This gives the receiving system the chance to modify the line endings on the received file. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From bosahvremove at netscape.net Sat Sep 7 01:15:49 2002 From: bosahvremove at netscape.net (Bo) Date: Sat, 07 Sep 2002 05:15:49 GMT Subject: Zope Status? References: <3d78a657$1@news.sentex.net> Message-ID: Peter Hansen wrote in news:3d78a657$1 at news.sentex.net: > Very likely, going to http://dev.zope.org would answer these > questions. > > I looked there but it seems somewhat vague and out of date. ie. Project Plan The Zope 2.6 release is tentatively planned for Q2 2002. Once the ProposedFeatures have been solidified into a final feature set, we'll put a table here with status and links to project areas for the major components of the project. The site says they are gathering features for zope 2.6 and working on a vision statement for 2.7 which will use python 2.2. I'm just curious if some people involved in the code would share their progress\hopes. From whisper at oz.net Thu Sep 5 22:15:56 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 5 Sep 2002 19:15:56 -0700 Subject: newbie problem: use socke lib to retrieve one web page: In-Reply-To: Message-ID: And for real convenience, there's websucker.py in the tools/webchecker directory of the standard distro. David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Cameron Laird > Sent: Thursday, September 05, 2002 17:24 > To: python-list at python.org > Subject: Re: newbie problem: use socke lib to retrieve one web page: > > > In article , > Erik Price wrote: > > > >On Wednesday, September 4, 2002, at 11:53 PM, koko wrote: > > > >> I write this to retrieve one web page using socket lib. > . > . > . > >Works for me: > > > > >>> import socket > > >>> host = 'www.uic.edu' > > >>> port = 80 > > >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > >>> s.connect((host, port)) > > >>> header = """HEAD /home/events.shtml HTTP/1.0 > >... From: hh at uic.edu > >... User-Agent: test/1.0 > >... > >... """ > > >>> s.send(header) > >72 > > >>> data = s.recv(4096) > > >>> print data > >HTTP/1.1 200 OK > >Date: Thu, 05 Sep 2002 15:40:00 GMT > >Server: Apache/1.3.26 (Unix) PHP/4.1.2 mod_perl/1.27 mod_ssl/2.8.10 > >OpenSSL/0.9.6 > >Connection: close > >Content-Type: text/html > > > > > > >>> s.close() > > > > > >I used the HEAD method instead of GET for brevity. But GET works too. > . > . > . > To criticize code that's already giving satisfaction > is nearly beyond me. I'll point out, though, that > the original questioner might consider this alterna- > tive which has, I believe, evident advantages for > long-term maintenance: > from urllib import urlopen > > URL = "http://www.uic.edu" > page = urlopen(URL).read() > print page > Note that urllib is one of the batteries the standard > Python distribution includes. > > My summary: use higher-order facilities when applicable. > -- > > Cameron Laird > Business: http://www.Phaseit.net > Personal: http://starbase.neosoft.com/~claird/home.html > -- > http://mail.python.org/mailman/listinfo/python-list From kkuroda at crl.ucsd.edu Mon Sep 2 20:47:16 2002 From: kkuroda at crl.ucsd.edu (Kow Kuroda) Date: Mon, 2 Sep 2002 17:47:16 -0700 Subject: RedHat 7.3 and Python2.2.1 In-Reply-To: <3D73B16F.76B355DB@engcorp.com> Message-ID: On Monday, September 2, 2002, at 11:43 , Peter Hansen wrote: > Doug Farrell wrote: >> >> I'm trying to install the latest version of Python >> (python2-2.2.1-1.i386.rpm) from the www.python.org download page, and >> I'm having problems. When I run >> >> rpm -i python2-2.2.1-1.i386.rpm >> >> I get all kinds of conflict messages like this: >> >> file /usr/bin/pydoc2 from install of python2-2.2.1-1 conflicts with >> file from package python2-2.2-16 >> >> probably hundreds of them in fact. Can anyone tell me what is going on >> here, as the www.python.org site says the RPM I'm using is for RH7.3, >> which is what I'm using. If you can tell me what I'm doing wrong and >> how to address this, that would be great too! My ultimate goal is to >> also install wxPython for the python2.2.1 installation, so if anyone >> has some 'heads up' on that, I'd appreciate it. > > Sounds like you already have a previous version of Python2.2 installed. > You should probably be using the "-U" option to update instead of > the "-i" option to install... or uninstall the previous one first. I just wanted to make a comment on Peter's post. I think -U or --upgrade option works, but it's dangerious to uninstall Python 2.1, which is now part of Red Hat Linux 7.3, unlike in prevous releases where Python 1.5.2 or something is used for installation scripts. If you try to uninstall 2.1, you'll get a bunch of dependency errors and won't succeed. If you happen to be successful, it's pretty likely that you get messed up with the stability issues. If .i386.rpm doesn't install even with -U, the best way to upgrade Python 2 should be using a .src.rpm instead of an i386.rpm, as usuaul. It is explained in the rpm installation page of www.python.org. Cheers, Kow From mennosimons at gmx.net Tue Sep 24 15:01:44 2002 From: mennosimons at gmx.net (Ulli Stein) Date: Tue, 24 Sep 2002 21:01:44 +0200 Subject: hex numbers?? References: Message-ID: jubafre at brturbo.com wrote: >>>> y=hex(x) >>>> y > '0xa' >>>> type(y) > > > the hex() function put the hexadecimal number in a string type like this > '0xa', but the real hexadecimal number of 10 is 'a', why python puts a > '0x', and how i can get just the real hexadedcimal number, for example i > want to write in a file 10 in hexadecimal, but if i use hex(10) the result > is '0xa' as a string, is not the same as 'a'. > > '0xa' != 'a' > > x = [12,13,14] > y = ['0xc', '0xd', '0xe'] > > hex() create a list of string, how i can write in a file just the real > value of hexadecimal number? > > > Juliano Freitas > www.gebrasil.hpg.com.br With your nice Python strings: >>> "%x, %x, %x, %x"%(1,10,14,24234234) '1, a, e, 171c8fa' Have fun. From jimb417 at NO* Sat Sep 21 22:29:12 2002 From: jimb417 at NO* (Jim) Date: Sat, 21 Sep 2002 20:29:12 -0600 Subject: PyQt setup on Linux Mandrake 8.2 References: <3D8B4898.20808@nospam.attbi.com> <3D8BC2F4.8080107@nospam.attbi.com> Message-ID: dwelch wrote: >>>( snipped ) > > OK, I found and installed tmake. Now, SIP can't find some of the Qt > pieces it needs. So, I still don't understand the situation with Qt. Is > it really possible to install and run my applications that I write with > say Qt 3.0.5, when KDE on my system is using Qt 2.3.1? How does/would > KDE know which version to use? How will my apps know what version to > use? I am assuming there can only be one QTDIR active on a system at a > time... > > Thanks for the help, > > Don Hello Don, You can write and compile apps using Qt 3.0.5 or whatever and still use KDE and Qt 2.3.1. To compile apps with Qt 3.0.5, put this in your /etc/profile file: QTDIR=/usr/local/qt305 ( or wherever you put Qt ) PATH=$QTDIR/bin:$PATH MANPATH=$QTDIR/doc/man:$MANPATH LD_LIBRARY_PATH=$QTDIR/lib:$LD_LIBRARY_PATH export QTDIR PATH MANPATH LD_LIBRARY_PATH I've compiled several apps with 3.0.5 and they have all run on my KDE desktop ( I'm still using 2.2.2! ) Hope this helps, Jim -- Registered Linux User #269187 http://counter.li.org From lee100 at sport.rr.com Tue Sep 17 20:42:42 2002 From: lee100 at sport.rr.com (Lee Gray) Date: Wed, 18 Sep 2002 00:42:42 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: <6_Ph9.479711$q53.16315681@twister.austin.rr.com> Chris Liechti wrote: > lpgray at uop.com (Lee Gray) wrote in > news:96904b50.0209171305.6d65f574 at posting.google.com: >> My boss is pretty open-minded, but also needs to see something working >> to be convinced Python is even a viable platform (he had never heard >> of it). Otherwise, .Net is a given, whether it's any good or not, >> since corporate is MS all the way. > > with python you have to choice of diffrent GUI libs. if you consider > wxWindows you can play around with the wxPython demo application that > comes with the download. on the other hand when you support win32 only the > win32all package has support for all the windows APIs and it has some > samples that get installed. > > chris Well, our shop is win32 only, but on a personal level I'd like to be more flexible (I mostly use Linux at home). Isn't Tk still considered the "official" GUI lib? For a newbie, what's easier, Tk or wxWindows? Thanks, Lee From Oschler at earthlink.net Sun Sep 29 12:57:32 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 29 Sep 2002 16:57:32 GMT Subject: Linker can't find library (PyProlog setup) References: Message-ID: <0iGl9.14200$Lg2.4065036@news2.news.adelphia.net> "Robert Oschler" wrote in message news:mdGl9.14197$Lg2.4064162 at news2.news.adelphia.net... Ugh, forgot to point out that I am running those commands from within a script file. thx From edwardam at interlix.com Sun Sep 22 14:18:42 2002 From: edwardam at interlix.com (Edward Muller) Date: 22 Sep 2002 11:18:42 -0700 Subject: Python HTTPSConnection/HTTPResponse Problem References: <9abedeb.0209212200.5c669a50@posting.google.com> Message-ID: <9abedeb.0209221018.75721059@posting.google.com> It has ssl and I have to use version 2.1.3 because this is, in the end being done using Zope, which doesn't work with anything newer AFAIK. Gerhard H?ring wrote in message news:... > * Edward Muller [2002-09-21 23:00 -0700]: > > I am trying to use HTTPSConnection and HTTPResponse objects [...] > > Is your Python SSL-enabled? Check with: > > import socket > hasattr(socket, "ssl") > > Which version of Python are you using? Be sure to use at least version > 2.2, as it contains many SSL-related bugfixes. > > -- Gerhard From evan at 4-am.com Sat Sep 28 21:02:17 2002 From: evan at 4-am.com (Evan) Date: Sun, 29 Sep 2002 01:02:17 GMT Subject: Best way to create a class dynamically on the fly? References: Message-ID: <3D96511D.2040407@4-am.com> Robert Oschler wrote: > What is the best way to create a Python class dynamically at runtime? ALL Python classes are created dynamically at runtime. The following is not a declaration in the sense that you're accustomed to from C/C++, it is normal code executed when the containing file is run (or imported): class Foo: def meth1(self): return "I am a method" Your class definition can include whatever Python code you need, and it doesn't have to be at global module level: def makeFoo(x): class Foo: sharedValue = x * 2 if x > 2: def manymethod(self, i): return i + 3 else: def fewmethod(self, i): return i + 1 return Foo Foo = makeFoo(4) f1 = Foo() print f1.sharedValue, f1.manymethod(2) Cheers, Evan @ 4-am From gerhard.haering at opus-gmbh.net Thu Sep 12 02:52:37 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 12 Sep 2002 06:52:37 GMT Subject: [ANN] PySQLite 0.3.0 released Message-ID: NAME: pysqlite - Extension module for SQLite databases. DESCRIPTION: A Python-DB API 2.0 compliant extension module that connects to SQLite databases. SQLite is a powerful, embedded relational database in a compact C library. It supports a large subset of SQL92, multiple tables and indices, transactions, and triggers. It has a simple C/C++ interface requiring only three functions to perform queries. It has TCL bindings and an ODBC driver. Sources are uncopyrighted and can be used for any purpose. More information can be found at . USAGE: import sqlite conn = sqlite.connect("db") cursor = conn.cursor() SQL = """ select category, family, genus, species from calflora order by genus, species limit 10""" cursor.execute(SQL) for col in cursor.description: print "\t %12s - %3s bytes" % (col[0], repr(col[3])) row = cursor.fetchone() while row != None: print "%14s, %15s, %19s, %8s, %25s" % tuple(row) row = cursor.fetchone() SQL = "insert into calflora (family,genus,species) values(%s,%s,%s)" cursor.execute(SQL, ('greenus', 'weedus', 'maximus')) conn.close() HOMEPAGE: DOWNLOAD: Source and Windows binary downloads are available at AUTHORS: Gerhard H?ring Michael Owens William Trenker LICENSE: Python NOTES: PySQLite has been tested on FreeBSD, Linux, and Windows with both Python 2.1 and 2.2. The latest versions of SQLite (v. 2.6 and greater) are recommended. Version 0.3.0 fixed a lot of bugs, while also adding new features. Users of PySQLite are recommended to upgrade. The following are some of the changes and enhancements since the last release: - Squashed a few memory leaks. - Exposed the sqlite_exec, sqlite_last_insert_rowid and sqlite_changes functions of SQLite to Python as methods of the connection object. - Add support for Date types, if mxDateTime is available. - Support for optional DB-API extensions from PEP 0249 - Added files for creating a PySQLite Debian package. - setup.py: - Added Cygwin as platform that's supported by default - Added third example: program to dump a table in XML format. - Use bool type and custom bool converter for boolean fields. - Set cursor.rowcount appropriately after DML (insert/update/delete) statements. - Fixed a bug with the SQL-quoting of longs. - Inline documentation improvement. - Change invocation of ReferenceError to work with Python 2.1 - (really) implemented weak references from cursors to connections - Added new test suite. - Adapted test for threadsafety attribute. - Added checks with user-defined float and string functions. - Removed Connection.begin(). Transactions are now started implicitely. - Use DB-API quoting instead of manual Python quoting. - Use string methods instead of the string module. - Added checks for functions/aggreagates that raise exceptions or return None (NULL). - Added tests for proper commit/rollback behaviour. Added tests for autocommit feature. - Implemented autocommit feature. Renamed the parameter of Connection.__init__ from "filename" to "db". Commit and rollback now check if the connection is open at all. Started adapting the weak reference code from pyPgSQL to loosely couple cursors and connections. This is needed when you want to check if there are any open cursors for a given connection, for example. - Simplified version numbers, removed the check for equal version numbers in _sqlite and sqlite. This looked like overhead to me. The version number scheme is now only: major.minor.micro Set threadsafety to level 1. I believe we can guarantee than sharing the module among threads will do no harm. Sharing the connection would. From darin at naboo.to.org.no.spam.for.me Mon Sep 30 10:49:54 2002 From: darin at naboo.to.org.no.spam.for.me (Darin McBride) Date: Mon, 30 Sep 2002 14:49:54 GMT Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> Message-ID: mike henley wrote: > I wish i can just use my own computer, with whatever technologies I > choose, keeping my content that i build up over time safe here on my > own machine, but unless you have a broadband connection this is not > possible. You provide an interesting idea. The major downfall to the request comes right here. This type of technology already has no future. Maybe when the web was initially born, this would have had some sort of future where whoever invented a solution to your problem would be able to succeed (money if commercial, fame if open source). Now, however, with broadband connections becoming almost ubiquitous in North America, and gaining popularity in other parts of the world, there is little to be gained for the programmer who comes up with a solution to this - it's only a matter of time before always-on internet becomes a reality for anyone who wants it, and there will be no need for any other solution. -- To reply, please remove the obvious spam filter From jimb417 at NO* Sat Sep 7 22:06:30 2002 From: jimb417 at NO* (Jim) Date: Sat, 07 Sep 2002 20:06:30 -0600 Subject: PyQT picture display References: <3D799F42.2020903@SPAMnwinternet.com> Message-ID: Jim wrote: > As far as I can tell, nothing's wrong. It works fine > for me. Are you sure the jpg files actually exist and > the path to them is correct? The only thing I changed > in your program was the filenames for the image files. > > I used PyQt-3.3.2 with Qt 2.3.0 on Linux. > > (another) Jim The jpg files are in the same directory as the program. I'm using Qt 3.0.5 with PyQt 3.3.2 on Linux. I'm sure that JPEG support is compiled in the Qt library as I got this to work using C++. Does JPEG support need to be built in when compiling PyQt? if so, what must I do to accomplish this? Thanks, Jim -- Registered Linux User #269187 http://counter.li.org From oren-py-l at hishome.net Tue Sep 10 05:23:32 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Tue, 10 Sep 2002 05:23:32 -0400 Subject: dynamism In-Reply-To: References: <66715c02.0209091923.265fe77e@posting.google.com> Message-ID: <20020910092332.GA19346@hishome.net> On Mon, Sep 09, 2002 at 11:45:35PM -0400, Raymond Hettinger wrote: > >>> class BetterAttrDict(dict): > def __getattr__(self, key): > return dict.__getitem__(self, key) > > > >>> bad = BetterAttrDict({'a': 1, 'b':2}) > >>> bad.a > 1 > >>> bad.b > 2 class EvenBetterAttrDict(dict): def __init__(self, d={}, **kw): """ Initialize from a mapping or using keyword=value pairs """ dict.update(self, d) dict.update(self, kw) def __getattr__(self, key): """ Return dictionary items as members """ return dict.__getitem__(self, key) def __setattr__(self, key, value): """ Set dictionary items as members """ try: dict.__getattribute__(self, key) except AttributeError: dict.__setitem__(self, key, value) else: dict.__setattr__(self, key, value) def __delattr__(self, key): """ Delete dictionary items as members """ try: dict.__getattribute__(self, key) except AttributeError: dict.__delitem__(self, key) else: dict.__delattr__(self, key) def __repr__(self): """ Display as a constructor call with keyword arguments """ items = dict.items(self) items.sort() return "%s(%s)" % ( self.__class__.__name__, ", ".join( ["%s=%s" % (k,`v`) for k,v in items] ) ) def __members__(self): """ Support dir(), rlcompleter attribute completion """ return dict.keys(self) __members__ = property(__members__) >>> class person(EvenBetterAttrDict): pass ... >>> p = person(name='Oren', born=1971) >>> p person(born=1971, name='Oren') >>> p.likes ='Chocolate!' >>> p person(born=1971, likes='Chocolate!', name='Oren') >>> Overkill? perhaps. Oren From jhorneman at pobox.com Wed Sep 4 12:32:58 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: 4 Sep 2002 09:32:58 -0700 Subject: Which XML parser under Python can handle Unicode? References: <9ac02e81.0209030214.515d6c0@posting.google.com> Message-ID: <9ac02e81.0209040832.32e13bd6@posting.google.com> Many thanks for your advice. Jurie. From spoermeg at voldelig.com Fri Sep 20 15:59:06 2002 From: spoermeg at voldelig.com (Terje Johan Abrahamsen) Date: Fri, 20 Sep 2002 14:59:06 -0500 Subject: newbie seeks advise. References: <77c84db2.0209192137.51167ebb@posting.google.com> <77c84db2.0209200425.4c723344@posting.google.com> Message-ID: "akirasugiura" wrote in message news:77c84db2.0209200425.4c723344 at posting.google.com... > Thank you very much. I didn't know there is such a "max" function. > ("max" > is a function isn't it). I also tried "min" to find a smallest > number(lol) and it worked. "list(data)" also worked. Thanks again. As a fellow beginner, I will also advise you to check out the tutor list on the python.org site. It is great when learning the language.... From bumm3rm4n at yahoo.com Mon Sep 30 21:02:01 2002 From: bumm3rm4n at yahoo.com (bumm3rm4n at yahoo.com) Date: 30 Sep 2002 18:02:01 -0700 Subject: Can python be used to debug other languages? Message-ID: <4d1e3be8.0209301702.109d2b04@posting.google.com> I am doing research in school and I was just wondering if python can be used to debug other languages such as C++ and java. IF it does, can anybody give me an info how? From marklists at mceahern.com Thu Sep 26 14:07:46 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 26 Sep 2002 13:07:46 -0500 Subject: How do you pronounce "__" (double underscore)? In-Reply-To: <525eaba.0209260956.72bf6786@posting.google.com> Message-ID: http://groups.google.com/groups?selm=mailman.1024136779.31270.python-list%40 python.org From loewis at informatik.hu-berlin.de Tue Sep 17 16:42:50 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 17 Sep 2002 22:42:50 +0200 Subject: Instantiating and initialising C++ with embedded Python References: Message-ID: Morfeas writes: > 1. My main program is in C++, so I need to embed the python interpreter. Correct. > 2. I need to allow python access to my C++ classes, therefore I need to > extend the embedded interpreter. Correct. > a) a brief description of the whole process You need to provide two things: - modules that expose "core" functions of your API, - Python "types" that encapsulate your C++ objects. The Python interpreter has a global table of all available modules, Modules/config.c:_PyImport_Inittab. This table lists entry points for all "builtin" modules. You need to compose a table that has all the "standard" builtin modules you want to use in your scripts, plus any extension modules that you implement yourself. In addition, to wrap C++ objects, you need to define "type objects", which are structures that essentially contain function pointers to the "virtual method tables" of a Python type; associated with such a type is a C structure that defines the layout of actual instances of the type. > b) some code examples See Modules/xxmodule.c for an example of an extension module; I recommend to also read the "Embedding and Extending" tutorial. > c) suggestions about useful tools I'd recommend to write all the necessary code by hand. People will suggest various tools, specifically: - SWIG, which can generate wrappers around existing APIs, - CXX, which exposes the Python API in a C++-ish way, - Boost Python, to wrap C++ libraries. HTH, Martin From andy at reportlab.com Mon Sep 9 16:27:08 2002 From: andy at reportlab.com (Andy Robinson) Date: Mon, 09 Sep 2002 20:27:08 GMT Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> <3d765ce6_4@news.bluewin.ch> <3d767c4a$1_1@news.bluewin.ch> <3d774f40$1_1@news.bluewin.ch> <3d7779b0$1_3@news.bluewin.ch> Message-ID: > > [Loaded java.io.RandomAccessFile from C:\Program > Files\Java\j2re1.4.0_01\lib\rt.jar] > > [Loaded sun.reflect.GeneratedMethodAccessor20] > > FYI, ReportLab sat down to try our test suite under Jython this week, and got out-of-memory errors when running some fairly innocuous code with 1.4.0_01. We then tried with some earlier JVMs and it was fine. We sus[pect a bug in that JVM version. Andy Robinson ReportLab From maxm at mxm.dk Mon Sep 9 12:15:25 2002 From: maxm at mxm.dk (Max M) Date: Mon, 09 Sep 2002 18:15:25 +0200 Subject: PythonWin bug [very weird] References: Message-ID: <3D7CC91D.5000607@mxm.dk> dsavitsk wrote: > This is PythonWin 145 (patched for asp), Python 2.1.3, Win2k. I have no > means for testing other versions. > > The bug is that pressing the wrong sequence of buttons can render a file > unsaveable. To reproduce it: > 1. open a .py file > 2. make some changes > 3. press the X to close the file (not to close PythonWin) > 4. when asked to save (Yes, No, Cancel) press Cancel > 5. Save the file (File | Save) > 6. Any new edits to the file are unsaveable (the buton is grayed out). To do > so, you must copy the entire contents, close the file, re-open it, and paste > the clipboard. That is almost as good as when you write a top latin-1 character like '?' and you try to delete it via backspace and it only seems to delete one of two bytes making it up, and you end up with '?'. And sometimes if you try and save a file with one of those 'half' characters in it it simply deletes your source file :-/ So the only version left is the one in the open document, which you cannot save ... regards Max M From robin at execulink.com Mon Sep 16 08:30:48 2002 From: robin at execulink.com (robin at execulink.com) Date: Mon, 16 Sep 2002 08:30:48 -0400 Subject: threads or queue for this task References: Message-ID: "James J. Besemer" wrote: >On the other hand, you probably DO want to eliminate explicit sleeps >like this if you can. E.g., the sleeps force a delay if data arrives to >be processed during the sleep. That's what I was thinking. >If you are clever, proper design of LookForWork() can automatically >suspend the threads when they have nothing to do. I may sometimes be clever, and can no doubt cobble together code from reading the docs (which I have been doing so far), but what I don't know are some of the trade-offs of using certain constructs, or the optimal way to do things. That is much more difficult to glean without actual code examples. For example, I really don't know what "proper design" I should use in this case. Any sample code? > E.g., that's one of >the great features of using a Queue -- threads are put to sleep if they >read an empty queue and they are woken up automatically when something >it put into the queue. Similarly, if your thread is reading a Socket() >-- it'll sleep until data is available. Then you don't need the >explicit sleeps. The interface to Queue is deceptively simple. Are there constructs to avoid or performance trade-offs to different methods? Again, any explicit code (or at least explicit help as to which methods are preferable) would be appreciated. I am also put off by the description of the Queue Object, particularly methods like empty() which says: "Return 1 if the queue is empty, 0 otherwise. Because of multithreading semantics, this is not reliable." If it's not reliable, then what's the point of it existing? Why is it not reliable? (I imagine simply because the thread doing the checking could be superceded by the thread that implements the Queue in the time it takes for the method to return and be acted upon.) Is it just in certain cases that it's not reliable? How can one code if you don't reliably know when a Queue is empty or full? What this boils down to is: I'm sure I can do the job with the great help I've already received, but do not have the confidence to know if I'm doing the job the *right* way. -- robin From itamar at itamarst.org_NOSPAM Sun Sep 1 17:05:07 2002 From: itamar at itamarst.org_NOSPAM (Itamar Shtull-Trauring) Date: Sun, 01 Sep 2002 17:05:07 -0400 Subject: Dead Man Timer? References: Message-ID: <3D728103.5060308@itamarst.org_NOSPAM> 1. Use timeoutsocket.py - this lets you set timeouts on socket operations (find it on http://py.vaults.ca). 2. Use an event driven networking architecture - don't know of any that have telnet client support though. Option 1 is your easiest solution. -- Itamar Shtull-Trauring http://itamarst.org/ Available for Python, Twisted, Zope and Java consulting From gerhard.haering at opus-gmbh.net Tue Sep 3 04:45:52 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 3 Sep 2002 08:45:52 GMT Subject: Newbie's unsurmountable pb with IO stream trick References: <3D738EE2.3A8756D@engcorp.com> Message-ID: "Spendius" wrote: > Peter Hansen wrote in message... >> And what does not declaring variables have to do with the "global >> keyword issue" (whatever that is)? > I kept getting the error message # UnboundLocalError: local variable > 'cpt' referenced before assignment where I really didn't expect to get > such an error, and noticed in this forum a lot of guys who know Python > complain and talk themselves about a "mess" (my 'cpt' var. is a counter > incremented every time a method gets called and I must sometimes > re-initialize it to 0 inside an 'if' statement: merely IMPOSSIBLE). def setToZero(): global cpt cpt = 0 Merely impossible. >> If you have an SQL database to access, why not use one of the >> standard DBAPI modules to get to it? You might be doing a lot >> of extra work when you don't have to. > And why not ? Anyway SQL*Plus contains plenty of built-in commands > that allow you to format your output how you like: Probably still easier to do with Python code. > I'd like to keep that functionality. And let's say that I want to do that > for the sole purpose of learning the handling of IO streams in Python! The popen functions should be useful to interface SQL Plus. I just tried to do so, but didn't succeed. >> If you're just learning Python, you've taken on a fairly >> complicated and large task right at the beginning. Why not > I admit it. But I did *exactly* the same with Java (writing the app I'm > trying to port) but never got stuck into problems that blocking... Having to use multithreading in Java to get the desired behaviour doesn't sound too sexy for me. -- Gerhard From loewis at informatik.hu-berlin.de Wed Sep 4 14:40:58 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 04 Sep 2002 20:40:58 +0200 Subject: Memory fault - core dumped while compiling 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> <3D765A05.6030004@nospam.yahoo.com> Message-ID: Anton Graph writes: > Did not even take nearly as long for it to coredump. With optionless > configure build was going at least for a half an hour and this one > bailed out pretty much right away... Can you please try to run the resulting Python binary in a debugger (say, dbx), and report a backtrace? Thanks, Martin From gerhard.haering at opus-gmbh.net Mon Sep 16 09:27:46 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 16 Sep 2002 13:27:46 GMT Subject: "if x == None" raises "'NoneType' object is not callable" References: Message-ID: Luc Saffre wrote: > row = Row() > if row == None: # here it happens. > print "row instance is None!" To avoid this and similar problems in the future, test for None using the is operator, like: if row is None: print "row instance is None!" This way, row doesn't need to support comparison to None. The same holds true for all other singletons you have in your app. As an additional plus, 'is'-comparison is faster. -- Gerhard From wlfraed at ix.netcom.com Wed Sep 25 20:16:49 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Wed, 25 Sep 2002 17:16:49 -0700 Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> Message-ID: Jacob Hallen fed this fish to the penguins on Wednesday 25 September 2002 07:03 am: > > Exactly the point! My code is my work of art. Why should anybody be > allowed to change it? We don't allow people to go painting moustaches > on the Mona-Lisa, do we? > Ah, but if you can persuade the Louvre to /sell/ you the Mona Lisa, you are then perfectly free to do what you want with it. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From Padraig at Linux.ie Mon Sep 16 05:54:48 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Mon, 16 Sep 2002 09:54:48 GMT Subject: python performance References: <3D84E66F.6020701@linux.ie> Message-ID: Terry Reedy wrote: > "Padraig Brady" wrote in message > news:3D84E66F.6020701 at linux.ie... > >>I was wondering about the performance characteristics >>of python and ran a simple test. The 2 programs >>below are functionally equivalent and just read >>in fields into a list. file.fields contains >>720 fields in each of 405 lines of the form of >>repeating: oneoneone twotwo "thre e three" >> >>The time to run is shown above each program >>from which I've inferred the following: >> >>1. The function call version is (6.3%) faster because >> the cumulative cost of parsing the simpler expressions >> and function call overhead is smaller than parsing the >> 1 single complex expression? > > > Calling functions adds overhead. Running code within functions > reduces overhead for object access. Ah OK, this because it has to search a smaller namespace? Wouldn't compiling overcome this? I suppose python is too dynamic. > See end for third version to > test. results below. thanks! P?draig. >>Or the function is parsed >> only once and doesn't have to be reparsed. This would >> suggest that top level code is parsed for each iteration? > > > No. All code is parsed only once. See above and below. > > >>2. Anyway I thought that parsing affects would be removed by doing > > the > >> parsing only once, i.e. compiling the code to .pyc (I used >> py_compile.compile()). However this makes no difference at all? >> Surely compiling is not just for code obfuscation. > > > No. The one-time parsing of 10 lines of code is extremely fast. If > it were parsed over again for each line, then you would notice the > parsing time. > > > >>Note I did do the test several times and averaged the results. >>---------------------------- >>2.514s >>---------------------------- >>#!/usr/bin/env python2.2 >>import re >> >>reFieldFinder = re.compile('[^ "]+|"[^"]+"') #unquoted|quoted >>def getFields(line): >> fields = reFieldFinder.findall(line) >> return [field.replace('"', '') for field in fields] >> >>for line in open("file.fields").readlines(): >> listLine = getFields(line[:-1]) >> >>---------------------------- >>2.672s >>---------------------------- >>#!/usr/bin/env python2.2 >>import re >> >>reFieldFinder = re.compile('[^ "]+|"[^"]+"') #unquoted|quoted >>for line in open("file.fields").readlines(): >> listLine = [field.replace('"', '') for field in >>reFieldFinder.findall(line[:-1])] > > > Try one more test to run at function speed without repeated > getsfields(): > ---------------------------- 2.498s ---------------------------- > def mytest: > reFieldFinder = re.compile('[^ "]+|"[^"]+"') #unquoted|quoted > for line in open("file.fields").readlines(): > listLine = [field.replace('"', '') for field in > reFieldFinder.findall(line[:-1])] > > mytest() From jhalttun at pp.htv.fi Thu Sep 5 08:43:19 2002 From: jhalttun at pp.htv.fi (janne halttunen) Date: Thu, 05 Sep 2002 15:43:19 +0300 Subject: How to get os.popen subprocess PID? Message-ID: <3D775167.6060307@pp.htv.fi> Hi all, I have a subprocess opened with os.popen, producing undefined length of data. I want to read maybe some of this data and then get rid of the subprocess, not waiting until the end of data. I have thought of os.kill-ing the process. So far I haven't been able to determine how to get the pid of the subprocess, required by os.kill .. Any pointers? janne From see_reply_address at something.invalid Tue Sep 3 21:59:11 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 04 Sep 2002 13:59:11 +1200 Subject: ANN: Pyrex 0.4.4.1 Message-ID: It has been brought to my attention (several times!) that Plex was missing from the 0.4.4 release. This one fixes that. What is Pyrex? -------------- Pyrex is a new 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. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From dougz at cs.washington.edu Tue Sep 17 16:05:02 2002 From: dougz at cs.washington.edu (Douglas Zongker) Date: Tue, 17 Sep 2002 20:05:02 GMT Subject: subclassing tuple Message-ID: Is there any way to create a subclass of 'tuple' that has a customized constructor? I tried doing the obvious thing, but it doesn't work -- it seems the tuple initializer gets called *before* the one for my subclass. This: class Foo(tuple): def __init__( self, a ): print 'self is already:', self print 'argument is', repr(a) x = Foo('hello') produces: value is already set: ('h', 'e', 'l', 'l', 'o') argument is 'hello' I could do this with lists instead, but that means changing a lot of existing code that expects tuples (and I don't want these objects to be mutable!) Suggestions welcome. thanks, dz From tjlavoie at mb.sympatico.ca Tue Sep 24 00:26:03 2002 From: tjlavoie at mb.sympatico.ca (Tim Lavoie) Date: 23 Sep 2002 23:26:03 -0500 Subject: Outlook 2002 and Python References: Message-ID: <87ptv4f1yc.fsf@theasylum.dyndns.org> Well, two things. First, please do NOT post to newsgroups or mailing lists in HTML, particularly that emitted by Microsoft tools. Even if readable in Outlook, they're horrid to read otherwise, and will often be ignored by those who might help. I'd repeat it to show you what it looks like to everyone else, but others have suffered enough. Second, what do you want your plugin to do? Something useful on the client side I would guess, but you never said. Regardless of the language used, deciding what you would like to accomplish is always an excellent first step. -- I finally went to the eye doctor. I got contacts. I only need them to read, so I got flip-ups. -- Steven Wright From DGustafson at attbi.com Fri Sep 20 14:53:28 2002 From: DGustafson at attbi.com (Dave Gustafson) Date: Fri, 20 Sep 2002 18:53:28 GMT Subject: general thoughts References: <7xznuc2a4r.fsf@ruckus.brouhaha.com> Message-ID: > That sounds like either a "port" or a re-interpretation of the classic > "The Little Lisper". Yes, "The Little Schemer" is indeed a re-casting of "The Little Lisper" which I believe was first published in 1974... This is the 4th edition, 6th printing. Fun stuff, and certainly a decent way to get comfortable with some of the cool things that can be done in Python. > You should also of course have read "Structure And Interpretation of > Computer Programs" by Hal Abelson and Gerry Sussman: > > http://www-mitpress.mit.edu/sicp/ > > The complete text is on that website now! WOW and again backwards WOW the "purple book" is on-line! hadn't noticed that before... From robin at jessikat.fsnet.co.uk Sun Sep 1 05:23:23 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 1 Sep 2002 10:23:23 +0100 Subject: [Q] win32com/Excel References: Message-ID: In article , Rolf Marvin B?e Lindgren writes >I would like to emulate this Visual Basic statement from Python, using >Com: > > Range(Range("A1"), ActiveCell.SpecialCells(xlLastCell)).Select > >this statement selects the active worksheet (which is, incidentally, >not similar to UsedRange). > >any clues? > >thank you, from win32com.client import Dispatch from win32com.client import constants xl = Dispatch("Excel.Application") AB = xl.ActiveWorkbook AS = AB.ActiveSheet AW = xl.ActiveWindow R = AS.Range('A1',AW.ActiveCell.SpecialCells(constants.xlLastCell)) print AB.Name, AS.Name, R -- Robin Becker From gupsmail at ihatespam.shaw.ca Wed Sep 25 10:51:48 2002 From: gupsmail at ihatespam.shaw.ca (Grant Hallam) Date: Wed, 25 Sep 2002 14:51:48 GMT Subject: problem with dictionaries within lists References: Message-ID: I reset the dict keys to blank strings and it works now. added the following after webdatabaselist(dict.append) dict = {'Name': '','Location':'','Transit':'','Position':'','Technical_Knowledge':'','Like_Site':'','Resolve_Tech_Issues':'','Easy_Navigation':'','Publish_Comments':'','Answered_No':'','Find_Support':'','Find_Support_Other':'','Find_Information':'','Which_LEOnet_Site':'','Find_Information_Other':'','Visit_Again':'','Visited_Old_Site':'','Time_Spent':'','Comments':'','B1':''} and it works ok now. Seems like a bit of a hack, have to think of a better way later. On Wed, 25 Sep 2002 02:11:14 -0700, Alex Martelli wrote: > Grant Hallam wrote: > ... >> However, the list seems to get populated with the same dictionary > ... >> webdatabaselist.append(dict) > > Of course -- you ARE appending the same dict over ands over (AFAICT -- > you're probably using tabs for indentation, making your code hard to > comprehend for those who read news with KDE's KNode [or MS's OE] as tabs > don't show there... use spaces, NOT tabs...). > > Anyway, you probably need something like: > > webdatabaselist.append(dict.copy()) > dict = {} > > either might suffice, but generally you'll need to copy the current dict > AND make dict empty for the next leg of the loop, if I get the general > drift. If you do rebind name dict to {} for the next leg, then you > don't need the call to the copy method. > > > Alex From propadovic.nenad at debitel.net Wed Sep 18 20:00:56 2002 From: propadovic.nenad at debitel.net (Nenad Propadovic) Date: Thu, 19 Sep 2002 02:00:56 +0200 Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> Message-ID: <3d89121f@news.ivm.net> Another answer. WOW! > ----- Original Message ----- > From: "Steve Holden" > Well, assume in that case that you should write for a CGI environment: > it's > maybe not the absolute fastest way to go, but it's pretty portable, and so > you'll be able to make plans ahead of that particular decision being made > (or do you get to make it?), and you can accommodate almost any server in > this way. Whenever I read "CGI" I also read "a pain to maintain" some words later... ? It's a project with a (modest) possibility to turn into a product, so both portability and maintanability are issues. > > The Python Image Library (PIL) is very good for creating graphics. You can > create them "on the fly" in your web server and then serve back HTML > documents with references to the created graphics. That sounds good, too. I seem to have two solutions for that part allready :-) > > Seems to me that CGI under Apache, while probably not the most exciting > cxhoice, should handle your requirements quite well. On the other hand, Mark also meant CGI/Apache, writting Python/Apache, right? > > The Python DB API means you can choose from a wide range of relational > database back-ends. Fine. > Otherwise you get involved with writing Java applets you can send > the data to, and things can get ugly fast ;-) No thanks :) > > A pleasure. There's a book called "Python Web Programming" by some chap > called Holden that might give you some useful background ... > Oh, if I choose CGI you can bet I'll byu this guy Holden's book :) > > > P.S. I'm just introducing Python to my group at BMW (a completely different > > project, though), and I'll let you know if there are some bigger success stories. > > > > Let us know what we can do to help! Not much, really. I was not suposed to write Python, I just started doing it. I guess at some point they'll just notice half of the SW is in Python, anyway, so it will become a de facto standard. It's a creeping invasion :) . Oh by the way, I'm just about to go offline, it's 1:59 in the morning on my computer watch. Thanks again, folks. From tismer at tismer.com Sun Sep 15 12:22:23 2002 From: tismer at tismer.com (Christian Tismer) Date: Sun, 15 Sep 2002 18:22:23 +0200 Subject: Stackless Python, eventual merge? References: Message-ID: <3D84B3BF.1010309@tismer.com> Mark McEahern wrote: > [Robert Oschler] > >>[...] Do you think that it [stackless] eventually >>will be merged with the main Python code base? > > > Note which category PEP 219 is in: > > http://www.python.org/peps/ This is true (deferred/abandoned), but the PEP was written for the old, continuation based Stackless implementation. The new one is completely different and very easy to merge with Python. There exists no current PEP that deals with that. The changes to Python are also so small now, that it doesn't matter if it will be merged or not. Porting Stackless to a new Python is a matter of a few hours. You may rely on getting a Stackless version of any new Python version in almost no time. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From Oschler at earthlink.net Wed Sep 25 17:16:10 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Wed, 25 Sep 2002 21:16:10 GMT Subject: Can't suspend a thread? References: Message-ID: "Tim Roberts" wrote in message news:juj2puko63pmq5k4j4tm2eonoadvpup50d at 4ax.com... > aahz at pythoncraft.com (Aahz) wrote: > > > > It is worth pointing out that this "restriction" is not a Python thing; it > is an operating system thing. > -- > - Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. You mean a Linux/Python restriction? Windows can suspend threads so I assume that's what you mean. Note I'm not saying that you can't suspend threads on Linux (POSIX), I don't know if that's possible or not, I just know you can on Windows. thx From magnus at thinkware.se Tue Sep 17 14:56:38 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Tue, 17 Sep 2002 20:56:38 +0200 Subject: Beginners Question - use of variables References: <1031345108.547.165.camel@martin.kleinerdrache.org> Message-ID: <3D877AE6.40701@thinkware.se> > > my_list = [ > ['sean', 'perry', 25, '20020906'], > ['Martin', 'Klaffenboeck', 20, '20020826'], > ] > > for entry in my_list: > print entry[0], entry[2] # prints first string and the int A more Pythonish solution is to use a list of tuples, rather than a list of lists. Tuples are a better choice for data structures that look like records or structs. A tuple is not mutable, and it is more lightweight. I.e: my_list = [ ('sean', 'perry', 25, '20020906'), ('Martin', 'Klaffenboeck', 20, '20020826'), ] for entry in my_list: print entry[0], entry[2] # prints first string and the int The most memory compact storage type (in case you have very big lists) is probably achieved by using the struct module. See the library reference, section 4.3. From Justin9688 at yahoo.com Mon Sep 9 14:30:36 2002 From: Justin9688 at yahoo.com (Justin9688) Date: Mon, 9 Sep 2002 13:30:36 -0500 (PET) Subject: Ciencia y Tecnolog Message-ID: <20020909183036.0BEC99ACD1@smtp2.terra.com.pe> An HTML attachment was scrubbed... URL: -------------- next part -------------- -- Antivirus de Terra ha detectado un grave virus en "este mensaje". Con la finalidad de evitar su contagio, hemos procedido a borrar el virus -- ROWS.pif is removed from here because it contains a virus. Si tiene alguna consulta o comentario escr?banos a antivirus at terra.com.pe - Terra Networks Peru S.A. - -------------- next part -------------- A non-text attachment was scrubbed... Name: socinfo[1].jpg Type: application/octet-stream Size: 3884 bytes Desc: not available URL: From yka at mbnet.fi.invalid Sat Sep 7 16:46:22 2002 From: yka at mbnet.fi.invalid (yka) Date: Sat, 07 Sep 2002 20:46:22 GMT Subject: Larry Wall's comment on python... References: Message-ID: <1549197.0PZNOebDTH@cartman> Kow Kuroda wrote: > > Well, Python code may look awkward --- if not awk-like --- > if you don't know how to customize the tab width in your > editor of choice. For example, vi and emacs indent by 8 > characters by default, which I suspect is too wide for Python. > Some code with deep nesting wouldn't look very nice with > this default. > > Kow Well at vim :set ts=4 makes more fitting -- Haloo? From from_deja at alandaniels.com Fri Sep 20 13:18:50 2002 From: from_deja at alandaniels.com (Alan Daniels) Date: 20 Sep 2002 10:18:50 -0700 Subject: Larry Wall's comment on python... References: Message-ID: "Matt Gerrans" wrote in message news:... > I think "the pound-end operator" is the technical term (I'll have to defer > to Guido on that). "Pound-end operator"? Now *there's* an image... From see_reply_address at something.invalid Sun Sep 22 20:49:19 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 23 Sep 2002 12:49:19 +1200 Subject: Destructor never called ??? References: Message-ID: <3D8E650F.3030400@something.invalid> Thomas Heller wrote: > So what are the recommended practices if my program creates datastructures > containing cyclic references? > > - avoid using __del__ in these objects by cleaning them 'manually'? > - only using weak references to break these cycles? > > - and finally using the debugflags of the gc module to ensure everything > is cleaned correctly? If you really must have __del__ methods in cyclic data structures, you could examine the uncollectable- garbage list periodically and do something to break up the cycles. Once you've manually broken the cycle, normal refcounting will take care of the rest and the __del__s will be called. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From wlfraed at ix.netcom.com Sun Sep 29 19:08:32 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 29 Sep 2002 16:08:32 -0700 Subject: What does Python fix? References: <87ptuxub5x.fsf@pokey.henrik-motakef.de> <87znu1rugt.fsf@pokey.henrik-motakef.de> Message-ID: Henrik Motakef fed this fish to the penguins on Sunday 29 September 2002 02:55 am: > Courageous writes: > >> >Let's not forget that Python's syntax (most of all the significance >> >of whitespace) is considered strange at least by about all novices. >> >In both cases - significant whitespace and lots of irritating >> >superflous parentheses - people don't just get used to it, but tend >> >to like it after a while. >> >> I'm fairly sure that you meant to say "Lisp" where you said Python, >> right? > > No, I'm talking about how newbies tend to react when you tell them > that block structure in Python is determined by indentation. I suspect the confusion was the phrase "significant whitespace and lots of irritating superflous parentheses" -- keyword being AND Change that to OR: ... significant whitespace (python) OR lots of irritating superfluous parentheses (lisp) > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From bokr at oz.net Fri Sep 27 12:22:22 2002 From: bokr at oz.net (Bengt Richter) Date: 27 Sep 2002 16:22:22 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <7nHk9.172208$pX1.6117207@news2.tin.it> Message-ID: On Fri, 27 Sep 2002 07:23:53 GMT, Alex Martelli wrote: [...] >Terry Reedy wrote: > >> >> "Alex Martelli" wrote in message >> news:7nHk9.172208$pX1.6117207 at news2.tin.it... >>> The reason >>> zz = a and b or c >>> is not the same thing as >>> zz = a ? b : c >>> is that, when a is true and b is false, the former returns c, >>> while the latter returns b. >> >> In almost all the practical cases where I have thought about using >> this, b is *not* false or cannot become false, in which important and >> real case the two expressions *are* equivalent. > >A typical, frequent, practical case is classification, e.g.: > >"Append bleep to list truebleeps when bleep is true, append it >to list falsebleeps instead when false". > >If we had a ternary operator, a natural way of expression would be: > > (bleep?truebleeps:falsebleeps).append(bleep) > >Of course this would be a disaster with the and/or idiom instead: > > (bleep and truebleeps or falsebleeps).append(bleep) > >As list truebleeps starts out empty, thus false, this buggy code >would NEVER append anything to it. > >In this case, like in most others (but far from all!) we don't >need short-circuiting, so we can perfectly well code: > > (truebleeps, falsebleeps)[not bleep].append(bleep) > >This is now correct -- but still nowhere as clear as good old: It's correct given that truebleeps and falsebleeps are simple references with no possible side effects from use as above, but I think it's important to note that the side effect restriction makes it not semantically identical to > > if bleep: truebleeps.append(bleep) > else: falsebleeps.append(bleep) > when there is more to it than simple references. >which to me remains the canonical way to code this in Python. >Yes, it IS fractionally more verbose, but, so what? It's >immediately obvious, simple, and not clever. > E.g., if truebleeps and falsebleeps were properties, if bleep: objectHavingProperty.truebleeps.append(bleep) else: objectHavingProperty.falsebleeps.append(bleep) would not trigger potential side effects of respective property getter functions, whereas (objectHavingProperties.truebleeps, objectHavingProperties.falsebleeps)[not bleep].append(bleep) would. I think it worth repeating that short-circuiting was (ISTM) invented to allow expressions where the terms preceding others in left-right order **prevent evaluation** of succeeding terms as soon as they cannot affect the total boolean value, so we can e.g. avoid exceptions in writing things like if i>0 and i The ternary expression also has the feature of preventing evaluation of the non-selected term. Someone else brought this aspect up before, but I think it's important enough to repeat. >> I think this is an elegant hack, and so I shared it in response to the >> OP. Others think it ugly. So be it. > >It's _dangerous_ -- to use it, one always has to be fully aware >of the risk that subexpression b might be false. I think this >is a pitfall just waiting for the unwary to stumble. Not being >an aesthete, I consider that more important than issues of beauty. > I'd like pitfall-free beauty ;-) Regards, Bengt Richter From cliechti at gmx.net Fri Sep 27 14:48:10 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Sep 2002 20:48:10 +0200 Subject: watching mutables? References: Message-ID: Thomas Heller wrote in news:k7l7qpvf.fsf at ion-tof.com: > Chris Liechti writes: [triggered by *any* change of object m] >> see EventObj: >> http://oomadness.tuxfamily.org/p-pyobjtools.php >> > This is what I get when clicking on the download link: > 404 Not Found works for me. chris -- Chris From ralf_ahlbrink at web.de Sun Sep 22 14:55:58 2002 From: ralf_ahlbrink at web.de (RA) Date: Sun, 22 Sep 2002 20:55:58 +0200 Subject: PyQt setup on Linux Mandrake 8.2 References: <3D8B4898.20808@nospam.attbi.com> <3d8c9b92$0$182$9b622d9e@news.freenet.de> <3D8CA781.3010000@nospam.attbi.com> Message-ID: <3d8e123e$0$178$9b622d9e@news.freenet.de> On Sat, 21 Sep 2002 17:08:17 +0000, djw wrote: > >> Unfortunately, Mandrake is somewhat more perl than python biased. >> > > Do you mean there is more support/newer versions of Perl or is it more > of a philosophical thing: There are many ways vs. there is one way? I don't know if it is a philosophic issue. But nearly all configuration software is perl. And they use gtk as gui for those apps. So, don't expect a rapidly updated PyQt. > > >> If you know a bit about RPM, perhaps you, dwelch, can manage >> to update these packages (rpm -Uhv xx.src.rpm, a few changes ..., >> rpm -ba SPECS/sip.spec). >> Otherwise you could contact me. In about a week I've got time >> to do this. > > Uhhh... considering my extreme novice status on Linux and especially > RPMs (as witnessed by my problems), I don't think I am the right person > for this task. > Just an excerpt from sip.spec: %build mkdir -p $RPM_BUILD_ROOT%{_libdir}/python2.2/site-packages %{__python} build.py -q %{_libdir}/qt3 -b $RPM_BUILD_ROOT%{_bindir} \ -d $RPM_BUILD_ROOT%{_libdir}/python2.2/site-packages %make cd siplib %make staticlib If you don't want to build a RPM, you can nevertheless use the info from the .spec for your question about the qt issue. So try something like "python build.py -q /usr/lib/qt3" > >> The RPM stuff (or DEB) has got real advantages compared to >> "setup.exe". >> And if the offered versions are outdated, fetch the >> new source, learn from the (e.g.) sip.spec file somewhat about >> the compilation, and make a new package! >> > > Well, here I have to disagree (at least from a user's perspective). > Having come from over 10yrs of Windows development experience (including > writing Windows installers from scratch), I find RPM package management > (can't say about DEB format, never used it) to be very complex, > difficult, and it rarely works for me. I haven't got any experience with building Windows installers. So, I can't compare both procedures. And I don't know, how you felt at the beginning of your Windows installer exp. I meant the _end_ users comfort. Perhaps you know, what files get installed and which registry entries were set. But I believe (not sure) that you have to use some third party "auditing" software. With rpm or deb you've got a database for installed files. With linux you often use more than one version of a library. The packages should "know" which version they need. If you want to use another version (library or main package) you or someone else has to rebuild the package. Now I will stop with this (somewhat) offtopic stuff. > > Case in point is two systems I tried to install at work... one Mandrake > 8.x and one Windows 2000. The packages I was installing were Python > 2.2.1 with a bunch of extensions like MySQLdb and mxDateTime, MySQL 4.0, > Jabber x.xx (can't remember version) and an FTP daemon. The Windows box > was up and running in less than an hour after running a handful of > setup.exe-type programs, and the Linux box still wasn't fully installed > after two days of trying. I completely gave up trying to upgrade a copy > of MySQL 3.23 to 4.0 after every way I tried failed. In the end, the > system became corrupted that I had to re-install Linux (probably a real > Linux person would laugh at this, but after a while /usr/bin got so > filled with junk that I didn't know what I had anymore and wanted to > start over "clean"). It would be certainly better if you install self compiled stuff in /usr/local/ (or control the installation with rpm). > > Not to say that this sort of thing doesn't happen in Windows-land, but > setup.exe works on 99% of the packages I have tried 99% of the time. > Don't get me wrong, I really like Linux, but this is one area where I > believe that Linux still has a ways to go to "catch up" in the > ease-of-use department. > > Don Ralf. From jb at cascade-sys.com Mon Sep 16 14:50:16 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Mon, 16 Sep 2002 11:50:16 -0700 Subject: threads or queue for this task References: Message-ID: <3D8627E8.1010903@cascade-sys.com> robin at execulink.com wrote: >I may sometimes be clever, and can no doubt cobble together code from >reading the docs (which I have been doing so far), but what I don't >know are some of the trade-offs of using certain constructs, or the >optimal way to do things. That is much more difficult to glean without >actual code examples. > >For example, I really don't know what "proper design" I should use in >this case. Any sample code? > The following illustrates my understanding of what you're trying to do. import thread import Queue # three queues connect four threads CmdQ1 = Queue.Queue() CmdQ2 = Queue.Queue() CmdQ3 = Queue.Queue() # Reader thread reads commands from stdin and # dispatches to appropriate thread via queue def Reader(): while 1: line = stdin.readline() if not line: return if line[0] == '1': CmdQ1.put( line[1:]) elif line[0] == '2': CmdQ2.put( line[1:]) elif line[0] == '3': CmdQ3.put( line[1:]) else: continue # or signal error # Command threads process commands as they arrive via queue def Cmd1(): while 1: cmd = CmdQ1.get() process1( cmd ) def Cmd2(): while 1: cmd = CmdQ2.get() process2( cmd ) def Cmd3(): while 1: cmd = CmdQ3.get() process3( cmd ) def main(): thread.start_new_thread( Cmd1, ()) thread.start_new_thread( Cmd2, ()) thread.start_new_thread( Cmd3, ()) # reader thread runs in mainline Reader() Frankly, it doesn't get any simpler than this. With threads as nodes and Queues as pipes, you can create practically any data flow topology you wish. >The interface to Queue is deceptively simple. Are there constructs to >avoid or performance trade-offs to different methods? Again, any >explicit code (or at least explicit help as to which methods are >preferable) would be appreciated. > It's not deceptively simple. It's merely simple. Sometimes a Queue is simply a Queue. >I am also put off by the description of the Queue Object, particularly >methods like empty() which says: "Return 1 if the queue is empty, 0 >otherwise. Because of multithreading semantics, this is not reliable." > The answer is accurate when it is returned to you but due to the nature of multithreading semantics, the value also is subject to change without notice. So if you read it and see a 0 or a 1, this is a true historical fact but you can't rely on the value being true at arbitrary points in the future so you can't really base any decisions on it. This is a function that was trivial and natural for the class designer to implement. It probably IS used internal to the class in order to decide whether or not to suspend or resume a thread. But is of little practical value to the end user. Fageddabouit. >How can one code if you don't >reliably know when a Queue is empty or full? > Generally, Queues never get "full" and you generally don't care if they're empty. The import thing about Queues is that the reader thread will automatically be suspended when reading from an empty queue and furthermore it will automatically wake up when the queue becomes non empty. All you need from Queues is to create them and to get and put data. >What this boils down to is: I'm sure I can do the job with the great >help I've already received, but do not have the confidence to know if >I'm doing the job the *right* way. > If your code does what you want and doesn't take an unreasonable amount of time to run on your computer then that's 80% of the "*right*" way. I'll defer to others to argue the remaining 20%. There really aren't as many alternatives here as you seem to suspect. You probably should look for a book on concurrent sequential processes. Most of the paradigms and pitfalls are pretty standard and would be spelled out in the book. Unfortunately, I am at a loss to make a specific recommendation. Perhaps somebody else has an idea. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From SBrunning at trisystems.co.uk Tue Sep 3 09:19:29 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Tue, 3 Sep 2002 14:19:29 +0100 Subject: How to avoid freeing memory on exit? Message-ID: <31575A892FF6D1118F5800600846864DCBD710@intrepid> > os._exit > From: Gumuz [SMTP:gumuz at looze.net] > so what does 'one' underscore prefixing a methodname mean? Proceed with caution. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From wlfraed at ix.netcom.com Sat Sep 7 13:45:41 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 07 Sep 2002 10:45:41 -0700 Subject: Thinking of joining References: <3D7970DC.5115BCC8@earthlink.net> Message-ID: <50edla.pu2.ln@ix.netcom.com> dark fed this fish to the penguins on Friday 06 September 2002 08:18 pm: > I was just curious if it will do everything PERL will do, as i > dont care for how PERL reads. FORTRAN will /do/ everything perl does -- you just wouldn't want to have to write it... Assuming some linkage to OS system calls, an ability to do comparison, branching, and simple arithmetic, ALL languages are equivalent in capability -- they only differ expression (usually targeted to an application domain -- I'd hate to consider writing a satellite tracking program in perl... well, to be honest, I'd hate to write /anything/ in perl). -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From tdelaney at avaya.com Wed Sep 11 19:43:10 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 12 Sep 2002 09:43:10 +1000 Subject: I must be an idiot, please pity me! Message-ID: > From: newbie [mailto:sam at localhost.localdomain] > > Perhaps I wasn't clear, but I don't believe I mentioned anything not > functioning properly. I did say "All works fine". I don't have failing > code, I simply suspect (hope) the current implentation isn't > very good. > The pseudo code listed was what I was epecting python to > allow me to do, Pseudocode is useless for optimisation purposes. Python code is very similar to pseudocode - post your exact code if you want help. Tim Delaney From erikprice at mac.com Tue Sep 10 10:10:02 2002 From: erikprice at mac.com (Erik Price) Date: Tue, 10 Sep 2002 10:10:02 -0400 Subject: web crawler help? In-Reply-To: Message-ID: On Thursday, September 5, 2002, at 07:15 PM, koko wrote: > is there any sample for basic web crawler, that ask for a starting url > and > log the url and extract the hyperlinks? > thx If you just want to learn the basics of making a web crawler, there is a great tutorial on page 187 of "Python Web Programming" by Steve Holden. There are more fully-featured spiders available in Python, but this one presents the core principles nicely. Erik -- Erik Price (zombies roam) email: erikprice at mac.com jabber: erikprice at jabber.org From erno-news at erno.iki.fi Wed Sep 11 11:27:48 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 11 Sep 2002 18:27:48 +0300 Subject: read() file?? References: Message-ID: In article , jubafre at brturbo.com writes: | I have a file with assembler instruction and i want read the lines | of the file and put in a list of string, this is easy to do, but i | don?t want to consider the caracteres "/" and the othes after him. | file.asm: | ADD D1 /coment1 | LDA D2 /coment2 try something like... def read_asm(filename): out = [] for line in open(filename).readlines(): out.append(line.split('/')[0]) return out -- erno From quiteblack at yahoo.com Fri Sep 6 06:33:33 2002 From: quiteblack at yahoo.com (black) Date: 6 Sep 2002 03:33:33 -0700 Subject: how could we know which module is imported already ? Message-ID: <7153651c.0209060233.2a72caaa@posting.google.com> want to know how many and what the module is imported~ From bokr at oz.net Mon Sep 2 15:30:46 2002 From: bokr at oz.net (Bengt Richter) Date: 2 Sep 2002 19:30:46 GMT Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: On Sun, 01 Sep 2002 21:07:24 -0000, "A.M. Kuchling" wrote: >In article <3d725881.345921 at news.t-online.de>, Gerson Kurz wrote: >> in the match or find function. So basically, couldn't one come up with >> a *human readable* syntax for re, and compile that instead? Python > >Maybe Ka-Ping Yee's rxb? http://web.lfw.org/python/rxb15.py > >The problem with a new syntax is that no one else would be using it, so >you'd still need to learn the existing syntax for use with grep, vi, Perl, >&c. (It wouldn't surprise me if Perl 6's revised regexes run into this very >difficulty and don't gain much adoption.) > I agree about new syntax, but I wouldn't mind having a re.help(regexp) function for interactive use that would just explain in 'English' what the regexp expression stands for. It would be a nice easy double check on whether I wrote what I meant, and helpful for understanding someone else's magic. It shouldn't be that hard to do. Regards, Bengt Richter From peter at engcorp.com Wed Sep 18 19:00:09 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Sep 2002 19:00:09 -0400 Subject: Python-style license? References: Message-ID: <3d89056c$1@news.sentex.net> Michael Chermside wrote: > Michael Str?der wrote: > >> HI! >> >> In some Python modules there's only a note about a "Python-style >> license". Now I wonder what that means. Any clues? >> >> Ciao, Michael. >> > > http://www.python.org/2.2/license.html And more generally, they are generally talking about licenses with the characteristic of allowing one to use the software even for commercial purposes, provided appropriate attribution is made etc. Another way of looking at it is that they're gnot GNU licenses. -Peter From aleax at aleax.it Sat Sep 14 15:45:27 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 14 Sep 2002 19:45:27 GMT Subject: Converting a string to time - simple task but don't know how to do it! References: <7A6D2E53461F2BF2.AC83A3D5E1A01468.48CC780BD6530537@lp.airnews.net> Message-ID: Richard Kessler wrote: > I have a string returned from a database expressing the time i.e. > 2002-09-14 > 10:30:34. I need to compare this value to the current time to determine > the amount of time elapsed between the two. I get the current time using > time.time() but I cannot find a way to convert the string from the > database into a time value (seconds from epoch) to do the simple > subraction to find seconds elapsed. What you want is function strptime of module time. Unfortunately, up to Python 2.2 it's platform-dependent whether module time does supply function strptime or not (in Python 2.3, you'll be able to use that function on any platform). There are pure-Python implementations of strptime out on the net, e.g. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/56036 Alex From shalehperry at attbi.com Thu Sep 12 11:30:14 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 12 Sep 2002 08:30:14 -0700 Subject: "str.contains(part)" or alternatives? In-Reply-To: <6g2g9.295995$aA.51455@sccrnsc02> References: <6g2g9.295995$aA.51455@sccrnsc02> Message-ID: <200209120830.14264.shalehperry@attbi.com> On Thursday 12 September 2002 08:19, Pete Shinners wrote: > Delaney, Timothy wrote: > > In fact, this was the deciding factor in Guido changing his position on > > 'if s1 in s2'. A string has sequence-like behaviour (e.g. it is iterable, > > individual characters can be indexed), but also has its own behaviour > > (e.g. substring containment, all elements are single-character strings). > > does this mean we can also now do this? if so, nifty > > >>> 1,2,3 in range(10) > > 1 > > >>> 3,2,1 in range(10) > > 0 I hope not. 1,2,3 should evaluate to a tuple and the tuple (1,2,3) is not in [1,2,...,10]. From robin at jessikat.fsnet.co.uk Fri Sep 6 05:38:40 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 6 Sep 2002 10:38:40 +0100 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> <3d765ce6_4@news.bluewin.ch> <3d767c4a$1_1@news.bluewin.ch> <3d774f40$1_1@news.bluewin.ch> <3d7779b0$1_3@news.bluewin.ch> Message-ID: In article <3d7779b0$1_3 at news.bluewin.ch>, Samuele Pedroni writes ..... > >Have you tried with an older JVM? anyway is the code and minimal >instructions to reproduce the "disaster" >available ? > >regards. OK my colleague ran with sun jdk 1.3.1 and the test worked! So I guess the problem lies with Marius Gedminas' TTFont class vs 1.4.0_01 grrhhhhh! -- Robin Becker From peter at engcorp.com Wed Sep 18 00:57:15 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Sep 2002 00:57:15 -0400 Subject: Python comment stripper References: <16Nh9.248$Wc6.17087796@newssvr13.news.prodigy.com> Message-ID: <3d8807b1$1@news.sentex.net> Dennis Reinhardt wrote: > Does anyone have a Python source comment stripper or can anyone recommend a > parser that could be adapted for same? > > Why? ... well there is a better than 2:1 byte size reduction in both raw > and compressed .py files if comments are stripped. This doesn't seem like a good reason to me. Why not just use .pyc files all the time and be done with it? The only reason to use .py instead of .pyc if size is such an issue (and with 60GB drives cheap I can't imagine why it would be), is that you want to maintain access to the source to make changes. In other words, to maintain the code. And maintaining code that has the comments stripped seems pretty counterproductive, doesn't it? Or am I missing something? -Peter From eric.brunel at pragmadev.com Wed Sep 4 11:56:38 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Wed, 4 Sep 2002 17:56:38 +0200 Subject: efficient list merging References: Message-ID: Mark McEahern wrote: [snip] > Anyway, here's yet another approach: > > #! /usr/bin/env python > > lol1 = [['a'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j']] > lol2 = [['d', 'e', 'f'], ['k', 'l', 'm'], ['d'], ['f', 'g'], ['a']] > > def mergelists(*lists): > d = {} > for each_list in lists: > for item in each_list: > key = str(item) > if key not in d: > d[key] = item > ret = d.values() > ret.sort() > return ret > > mergelol = mergelists(lol1, lol2) > > expected = [['a'], ['a', 'b', 'c'], ['d'], ['d', 'e', 'f'], ['f', 'g'], > ['g', 'h', 'i', 'j'], ['k', 'l', 'm']] > > assert mergelol == expected > > // m To avoid explicit for loops, you may write: l = lol1 + lol2 mergelol = dict(zip(map(str, l), l)).values() mergelol.sort() # if needed... Maybe doing: mergelol = dict(zip(map(tuple, l), l)).values() can be a little faster: converting a list to a tuple *seems* easier than converting it to a string. But I may be wrong... Anyway, any method involving a dictionary will require to convert your lists to something else: list are mutable, and cannot be used as dictionary keys... -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From mgarcia at cole-switches.com Fri Sep 20 20:06:10 2002 From: mgarcia at cole-switches.com (Manuel M. Garcia) Date: 20 Sep 2002 17:06:10 -0700 Subject: What the heck? open() requires an integer? References: Message-ID: "Fausto Arinos de A. Barbuto" wrote in message news:... > Also, it is a good idea to learn more Python before > venturing to develop code. Or to adapt someone > else's source code, which was exactly the case. Please don't be too intimidated by Python. It is fairly typical to write a non-trivial Python program while learning the language. For example, it is surprising how straightforward the trickiest of OO programming is in Python. O'Reilly publishes two excellent books for people who wish to learn Python and write applications quickly: Programming Python, 2nd Edition, and Python Cookbook. Also the Python newsgroup is very friendly to people new to the language From sholden at holdenweb.com Wed Sep 18 18:49:03 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 18 Sep 2002 18:49:03 -0400 Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> Message-ID: "Nenad Propadovic" wrote ... > Hello pythonistas, > I'm about to write an application related to injury prevention in big > industrial companies. It's supposed to be intranet-based (because the admins > are reluctant to install it on x (where x>>1) clients). So: the client is a > web-browser. I still don't know whether I will get a server on my own, or > I'll have to fit into an unknown web server environment, both options being > realistic. Well, assume in that case that you should write for a CGI environment: it's maybe not the absolute fastest way to go, but it's pretty portable, and so you'll be able to make plans ahead of that particular decision being made (or do you get to make it?), and you can accommodate almost any server in this way. > By now it seems the logic of the application will be simple. It's going to > be a relational database with several tables, a modest number of users with > write priviledges, some more with read priviledges only. Performance is not > a big issue. Great. Almost any language could eat this part up for breakfast :-) > The GUI has a part I consider complex: I have to present some statistics in > form of charts or graphs. The Python Image Library (PIL) is very good for creating graphics. You can create them "on the fly" in your web server and then serve back HTML documents with references to the created graphics. If you need help, you can buy the professional PIL with a support contract, I believe. The guy who wrote that software shows every appearance of knowing what he's doing. > Now I've never done any web based application in my life, have a very > rudimentary knowledge of HTML, have been doing som database hacking (O.K., > engineering :-) ) with MS Access and Ingress/ Open Road, have once written a > socket-based combined telnet/ftp client. You probably have enough programming experience for the task, although you might need some help with the basics of the technologies. > So I kindly ask for knowledgeable opinions on the following question: > -which web/application server? I'm considering Zope (seams rather BIG when > you download & unpack it, and it seams all possible web applications have > been written for it) and twisted (smaller, seams lower lewel and somewhat > easier to learn), and I'm wondering if there is something else out there, > which is both powerfull and flexible and easy to learn and complete. Oh yes, > I have both a time constraint (mid november, having only my spare time for > the project), and don't want end up rewritting the stuff under another > system, because the chosen one isn't flexible enough. Database included > would be nice. Seems to me that CGI under Apache, while probably not the most exciting cxhoice, should handle your requirements quite well. You're corect about Zope: the learning curve is pretty high. Twisted is still a bit experimental, and because of its somewhat unconventional architecture and limited documentation that too might take a bit of learning. Both are excellent products, but your constraints seem to rule them out (unless you learn much faster than me). The Python DB API means you can choose from a wide range of relational database back-ends. > -I assume the simplest way to present a graph/chart kind of graphic is to > create a jpg/giff/tiff on the server side, and just show it on the client? Correct. Otherwise you get involved with writing Java applets you can send the data to, and things can get ugly fast ;-) > Thanks to everybody taking the time to read the message, and even more to > those who answer it :-) A pleasure. There's a book called "Python Web Programming" by some chap called Holden that might give you some useful background ... > P.S. I'm just introducing Python to my group at BMW (a completely different > project, though), and I'll let you know if there are some bigger success > stories. > Let us know what we can do to help! regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From mcfletch at rogers.com Wed Sep 25 00:31:01 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 25 Sep 2002 00:31:01 -0400 Subject: Removing all occurences of a character from a string. References: Message-ID: <3D913C05.3080706@rogers.com> Under later Python versions (such as 2.2.1), you can do the following: attr = [[item.replace("'","") for item in element] for element in attr] Which is rather elegant IMO. It also has the side-effect of _not_ rewriting the data in-place in your original list, instead just replacing that list when we are finished creating the new list, which may or may not be desirable for you. HTH, Mike PS: Always nice to hear from another Canadian Pythonista :) Sean Ross wrote: > Thank you Justin. > > How about this, then: > > I have a list of lists of these strings and I want to apply replace to each > string in the list of lists. > > So, say: > > attr = [ ["'gill-attachment'", "'a'", "'d'", "'f'", > "'n'"],["'gill-spacing'", "'c'", "'d'", "'w'"], ["'gill-size'", "'b'", > "'n'"]] > > I can do the following: > for i in xrange(0, len(attr)): > for j in xrange(0,len(attr[i])): > attr[i][j] = attr[i][j].replace("'","") > > to get what I want; which is: > [ ['gill-attachment', 'a', 'd', 'f', 'n'],['gill-spacing', 'c', 'd', 'w'], > ['gill-size', 'b', 'n']] > > Is there a nicer way to do this? > Sean ... From Oschler at earthlink.net Sat Sep 14 20:48:12 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 15 Sep 2002 00:48:12 GMT Subject: Stackless Python, eventual merge? Message-ID: I've been reading a lot of good things about Stackless Python, especially when it comes to speed and multi-threading. Do you think that it eventually will be merged with the main Python code base? I'm thinking of trying it out, but I'm worried about ending up with a heavy code fork that I'll end up regretting. thx From rsrchstr at hotmail.com Fri Sep 27 18:11:36 2002 From: rsrchstr at hotmail.com (mike henley) Date: 27 Sep 2002 15:11:36 -0700 Subject: windows xp command prompt Message-ID: <576c1752.0209271411.6d7bb4c4@posting.google.com> i have installed the activestate perl, python, tcl, and pragmatic programmer's ruby. when i go to the command prompt on windows xp and type perl for example... (or python, ruby... etc) i get the following message. 'perl' is not recognized as an internal or external command, operable program or batch file. in the control panel| system | advanced | environment variables | Path i have C:\ruby\bin;C:\Python22;C:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem does anyone know what i should do to fix this problem? (apart from the obvious of restarting the machine) From syver-en+usenet at online.no Fri Sep 20 19:56:56 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Fri, 20 Sep 2002 23:56:56 GMT Subject: Python Compiling References: Message-ID: "Terje Johan Abrahamsen" writes: > First of all, I am going to warn you. I will ask some stupid > questions. I > > haven't programmed too much, and don't really know how it all links > together. > > But, I guess my question boils down to, why is not Python a compiled > language? > > To my best knowledge, the computer understand 0s and 1s. So, any > programming language must be brought down to that. Maybe it helps to think of it this way. The interpreter is a compiled program. Python programs then, are a kind of meta program, a program that runs in another program. -- Vennlig hilsen Syver Enstad From loewis at informatik.hu-berlin.de Sun Sep 15 14:04:04 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 15 Sep 2002 20:04:04 +0200 Subject: Python11 References: Message-ID: "Jeff Sasmor" writes: > One hopes that Python11 won't be lost in the much larger OSCON.. There are also plans to have YAS (Yet Another Society) organize a Python-dedicated conference, at a much lower price than OSCON, at GWU (George Washington University). Plans for that are not final, either. Regards, Martin From loewis at informatik.hu-berlin.de Thu Sep 19 12:35:32 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 19 Sep 2002 18:35:32 +0200 Subject: Remarks to Python 2.3 References: <20020918222421.328088eb.use-net@schabi.de> <20020919152834.592eaa39.leafnode-usenet@schabi.de> Message-ID: Markus Schaber writes: > I'm not really shure whether my remarks are about "bugs" - I just wanted > to collect other opportunities here to help me decide whether one can > regard this as bugs or not, and eventually submit bug reports. There is always the potential danger that a newsgroup message gets ignored, and the poster gets the impression that nobody cares about the (potentially significant) problem. In these cases, it is a good idea to submit a bug report, because the tracking involved in the SF bug database guarantees that the report stays open until it has been considered. Of course, bug reports are only the right thing if the poster feels that Python behaves "bad", where "bad" means either incorrect, non-intuitive, or in an otherwise undesirable way. For a bug report, one should also research whether this is a well-known issue. Regards, Martin From michael at stroeder.com Tue Sep 24 05:47:55 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 24 Sep 2002 11:47:55 +0200 Subject: Sessionhandling References: Message-ID: Lutz Schroeer wrote: > langpref = os.environ['HTTP_ACCEPT_LANGUAGE'] > firstpref = 'en-ie' > try: > langs = string.split(langpref, ',') > firstpref = langs[0] > secondpref = langs[1] > thirdpref = langs[2] > except: > pass One might think about a more complete solution handling the weight: http://stroeder.com/pylib/PyWebLib/pydoc/pyweblib.helper.html#AcceptHeaderDict Most users do *not* configure their browsers anyway. Therefore it's almost useless to use HTTP_ACCEPT_LANGUAGE or similar env vars. Ciao, Michael. From rpm1deletethis at nospamfrontiernet.net Wed Sep 4 06:49:28 2002 From: rpm1deletethis at nospamfrontiernet.net (RPM1) Date: Wed, 4 Sep 2002 06:49:28 -0400 Subject: Why Python? References: Message-ID: "Benjamin" wrote in message news:uafbnugdli4c3f8ns6qr33mna5urdno78g at 4ax.com... > Hi guys (and girls) > I just begun to learn how to program. And I choosed Python for > doing that. surfing around the web i found an article about this > language, they said it's the ideal language for beginners to the > world of programming. and i admit it, the syntax is very clear making > the code very readable, i learn easily the concepts of programming > and i soon wrote some nice programs. but since i finished my > newbie-tutorial, i am wondering about one question: is it worth to go > deeper into python? i talked to a friend of mine, he told me that i > should try php.. > what should i do?? ^_^ in other words: what is python good for? > why should i continue with python? > thank you! > I think you should try coding in C. It's used everywhere for everything. It's faster than about any other language. Most other languages are written in C. C is highly marketable. But best of all... You'll learn to *really* appreciate other languages like Python, Java, ... If you really want to get a feel for a language, read a fairly large program that somebody else has written in that language, (not just little snippets). Patrick From henrik.motakef at web.de Sun Sep 29 05:55:14 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 29 Sep 2002 11:55:14 +0200 Subject: What does Python fix? References: <3d95fb09@news.vip.fi> <87ptuxub5x.fsf@pokey.henrik-motakef.de> Message-ID: <87znu1rugt.fsf@pokey.henrik-motakef.de> Courageous writes: > >Let's not forget that Python's syntax (most of all the significance of > >whitespace) is considered strange at least by about all novices. In > >both cases - significant whitespace and lots of irritating superflous > >parentheses - people don't just get used to it, but tend to like it > >after a while. > > I'm fairly sure that you meant to say "Lisp" where you said Python, > right? No, I'm talking about how newbies tend to react when you tell them that block structure in Python is determined by indentation. > It doesn't help that the number of big commercial Lisp compilers > can be counted on the fingers of, err, one finger. You must have funny fingers then, as the people working for Franz, Xanalys and Corman will love to explain. BTW, there aren't that many big commercial Python compilers out there, and that doesn't seem to be too big a problem for the Python users. :) Regards Henrik From haering_postgresql at gmx.de Thu Sep 5 19:11:34 2002 From: haering_postgresql at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Fri, 6 Sep 2002 01:11:34 +0200 Subject: What database should I use In-Reply-To: <3D77763F.23080.BFAFA3@localhost> References: <3D77763F.23080.BFAFA3@localhost> Message-ID: <20020905231134.GA1229@lilith.ghaering.test> * A [2002-09-05 15:20 +0200]: > Hello, > I am going to program a small application (in Python and wxPython) which consists about > 2000 - 3000 records . Can you please recommend which database is the best for that. I > use Windows. > Maybe MS Access or FoxPro or MySQL or better? > I want to keep the program as small as possible. PySQLite. It uses an embedded SQL engine (SQLite), which means you don't have to set up a separate server process. It only weights a hundred KB or so and has good SQL support (a lot better than MySQL, for example). http://pysqlite.sf.net/ -- Gerhard From tjreedy at udel.edu Fri Sep 20 19:36:46 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 20 Sep 2002 23:36:46 GMT Subject: e vs exp()? References: Message-ID: "Tim Peters" wrote in message news:mailman.1032550470.8080.python-list at python.org... > [Terry Reedy] > > ... > > On the hypothesis that x**y is calculated as exp(y*log(x)), > > Bad hypothesis. The implementation of a decent x**y function is one of the > most difficult tasks in a platform's math library.... >I've written such a beast without benefit of an extended hardware > precision; I wouldn't want to do it again . What was your basic approach? Power series? Rational function? Continued fraction? ??? http://functions.wolfram.com/ElementaryFunctions/Power/ gives 343 formulas (many only relevant to complex domain) but doesn't seem to indicate which Mathematica actually uses (trade secret I presume). Terry J. Reedy From vlindberg at verio.net Mon Sep 23 19:21:41 2002 From: vlindberg at verio.net (VanL) Date: Mon, 23 Sep 2002 17:21:41 -0600 Subject: Downloading huge files via urllib Message-ID: <3D8FA205.8090602@verio.net> Hello, For various reasons, I have to use https to download large (20+ MB) text files which I then parse. I set up a basic function to do this using urllib: response = urllib.urlretrieve(serverURL, 'run.log') However, I then get a MemoryError. Tracking down the source of the error, I see the offending function in httplib: def makefile(self, mode, bufsize=None): """Return a readable file-like object with data from socket. This method offers only partial support for the makefile interface of a real socket. It only supports modes 'r' and 'rb' and the bufsize argument is ignored. The returned object contains *all* of the file data """ I think the problem is that bufsize argument that is ignored. Does anyone know if this is correct, and what I can do about it? I would like to automate the process of downloading this file, but is it possible? Thanks, VanL From ckasso at sprynet.com Sun Sep 29 17:43:22 2002 From: ckasso at sprynet.com (Chris Kassopulo) Date: Sun, 29 Sep 2002 17:43:22 -0400 Subject: Running with arguments in IDLE? References: <3D90DB87.4797EA7@quartercase.com> Message-ID: <20020929174322.7013132b.ckasso@sprynet.com> On Tue, 24 Sep 2002 21:39:19 GMT joe sixpack wrote: > the arguments. What I don't know is how to run the script from > within IDLE and specify the argument to use when it is run. In > Pythonwin, 'RUN'ning a script brings up the dialog box in which > arguments may be specified. How is this done in IDLE? I just noticed this post. It's a few days old and I don't see any replies, so I'll try. According to the docs you can't run with arguments directly. You need a function that calls your script with arguments. See "Running a File" in: http://www.python.org/idle/doc/idle2.html Also, I don't think this is what you want but I'll mention it anyway. From a commandline you can run a script in idle with: python idle.py ascript.py arg1 arg2 ... Chris Kassopulo From h_schneider at marketmix.com Fri Sep 27 07:20:54 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Fri, 27 Sep 2002 13:20:54 +0200 Subject: py2exe Error creating NT Service Message-ID: Hi, got an error with py2exe when trying to create a Win32 service: . changing back to 'C:\WORK\Software\Python\xqmagent' creating dist\xqmagentwin\xqmagentwin.exe Traceback (most recent call last): File "C:\WORK\Software\Python\xqmagent\setup.py", line 10, in ? scripts=['xqmagentwin.py']) File "C:\usr\python\lib\distutils\core.py", line 138, in setup dist.run_commands() File "C:\usr\python\lib\distutils\dist.py", line 899, in run_commands self.run_command(cmd) File "C:\usr\python\lib\distutils\dist.py", line 919, in run_command cmd_obj.run() File "C:\usr\python\py2exe\build_exe.py", line 626, in run self.create_exe(exe_name, arcname, use_runw) File "C:\usr\python\py2exe\build_exe.py", line 823, in create_exe svc_name, svc_display_name, svc_deps = self.get_service_names() File "C:\usr\python\py2exe\build_exe.py", line 898, in get_service_names exec compile(open(self.script).read(), self.script, "exec") in mod.__dict__ File "", line 101 SyntaxError: invalid syntax The py2exe service sample compiles perfect on my machine, but this script here does not. There are no differences in the class derived from the service framework. Any ideas? All the best, Harald From peter at engcorp.com Tue Sep 17 08:27:26 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 17 Sep 2002 08:27:26 -0400 Subject: problems getting a single item out of a list References: <20020917071900.GB23629@partagas.as.de.cw.net> <200209170030.52964.shalehperry@attbi.com> Message-ID: <3d871fa0$1@news.sentex.net> Manuel Hendel wrote: > On Tue, Sep 17, 2002 at 12:30:52AM -0700, Sean 'Shaleh' Perry wrote: > >>just use fields[2] (you start counting at zero). > > > This worked fine: > > domainfield = fields[3] > > But the next problem is, that after a > > domainfield = string.split(fields[3]) > > domainfield seams to be a list item again. > > print domainfield > > ['142000'] Well, you don't show what fields[3] contained before the string.split, but in any case split() returns a list by definition, so what else did you expect? If you want to get the first item from the split list, just use domainfield[0] this time... -Peter From loewis at informatik.hu-berlin.de Thu Sep 5 10:45:32 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 05 Sep 2002 16:45:32 +0200 Subject: Why read-only nested scopes? References: <20020905.072837.159259470.2038@cybermesa.com> Message-ID: "Jay O'Connor" writes: > Why not simply disallow the using of a name already defined in an > enclosing scope? Similar to Smalltalk? That might break compatibility with existing code. Regards, Martin From timr at probo.com Fri Sep 27 01:16:03 2002 From: timr at probo.com (Tim Roberts) Date: Thu, 26 Sep 2002 22:16:03 -0700 Subject: Help - GUI programming question References: <3d93ca8b_4@goliath.newsgroups.com> Message-ID: <29q7pu86sh1rjs7k2p8js56pot9li42je6@4ax.com> wrote: >Quick question. The following yields the error: "makemenu takes only one >argument (2 given)". This should be simple - I'm just not seeing it! Can >anyone explain? The applicable code follows: I know! I know! What's the prize? >class WINMENU: > def makemenu(parent): Your makemenu DOES only expect one argument. You need to make room for the instance: def makemenu(self,parent): > menubar = Frame(parent) # win=top-level window > menubar.pack(side=TOP, fill=x) # set its menu option > (more code to build a menu.....) > >if __name__ == '__main__': > root = Tk() > root.title('GUI Menu') > smenu = WINMENU() > smenu.makemenu(root) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From BPettersen at NAREX.com Wed Sep 18 13:20:34 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 18 Sep 2002 11:20:34 -0600 Subject: Python comment stripper Message-ID: <60FB8BB7F0EFC7409B75EEEC13E20192012533FE@admin56.narex.com> > From: Dennis Reinhardt [mailto:DennisR at dair.com] > > Does anyone have a Python source comment stripper or can > anyone recommend a parser that could be adapted for same? > > Why? ... well there is a better than 2:1 byte size reduction > in both raw and compressed .py files if comments are > stripped. Results of analyzing dospath.py in : > > raw Kb compressed Kb > ---------- -------------------- > original 10.44 2.98 > 4 spaces -> 1 space 8.85 2.86 > + strip comments 4.65 1.34 One question: How big is your disk page size? -- bjorn From leipold at acm.org Thu Sep 26 12:39:17 2002 From: leipold at acm.org (Walt Leipold) Date: 26 Sep 2002 09:39:17 -0700 Subject: Strange change in xmlrpclib behavior Message-ID: <71f60588.0209260839.537943bb@posting.google.com> Late last year, I wrote an app (in Python 2.1) that acquires and logs serial data. It's a standalone app on a remote computer, but I wanted to send it an occasional command ("reset", "status?"), so I included an XML-RPC server handler in its main loop, and set its socket to nonblocking ("self.socket.setblocking(0)") so it wouldn't slow down data acquisition. The code worked for months. As of early last week, it no longer works. XML-RPC requests from a remote host (except occasionally for the very first one after the server starts) raises error 10035 in SocketServer.py ("cannot complete without blocking"). Requests to the server from localhost work normally. I've reduced the problem to 43 lines of server code and 18 lines of client code, attached below. It's been tested on six different machines, and all of them now misbehave. Other socket-based code (like the code that logs the serial data to yet another machine) still works. I don't *think* I'm going crazy, but I could swear this code used to work. Any ideas? (BTW, it's xmlrpclib v0.9.8, Win2000 SP2 and NT4 SP6.) ------------------------------------------------------------------ "No matter how thin you slice Walt Leipold it, it's still baloney." leipold at acm.org ------------------------------------------------------------------ aserver.py: =========== #!/usr/bin/python import SocketServer import xmlrpcserver import time class BozoServerHandler(xmlrpcserver.RequestHandler): def call(self,method,params): try: server_method = getattr(self,method) except: raise AttributeError,"No method named %s!" % (method,) return server_method(method, params) def status(self,method,args): global done,statcount,itercount now = time.time() statcount += 1 return time.strftime("%H:%M:%S -- ",time.localtime(now)) + \ "%d requests in %d iterations." % (statcount,itercount) def die(self,method,args): global done,statcount,itercount done = 1 return "Aaargh!" class bozoSocketServer(SocketServer.TCPServer): """A TCPServer with a non-blocking socket.""" # Use the 'server_close()' method to close this server. def __init__(self,addr,handler): SocketServer.TCPServer.__init__(self,addr,handler) self.socket.setblocking(0) server = bozoSocketServer(('',1234),BozoServerHandler) done = 0 statcount = 0 itercount = 0 while not done: time.sleep(0.1) # Between serial i/o requests... itercount += 1 # Handle a single XML-RPC request, if present. server.handle_request() server.server_close() aclient.py: =========== #!/usr/bin/python import sys import xmlrpclib import time if len(sys.argv) != 2: host = "localhost" else: host = sys.argv[1] s = xmlrpclib.Server("http://%s:1234" % (host,)) try: for i in xrange(0,100): print s.status() time.sleep(1.5) except KeyboardInterrupt: pass print s.die() From edwardam at interlix.com Sun Sep 22 17:43:50 2002 From: edwardam at interlix.com (Edward Muller) Date: 22 Sep 2002 14:43:50 -0700 Subject: Python HTTPSConnection/HTTPResponse Problem References: <9abedeb.0209212200.5c669a50@posting.google.com> Message-ID: <9abedeb.0209221343.74d27ad1@posting.google.com> I thought I had posted this already, sorry if it sorta doubles. I can't use python 2.2, the latest I can use is python 2.1 because in the end this will be done with zope and zope currently only supports python 2.1.3 and earlier. And yes, my python is SSL enabled. Gerhard H?ring wrote in message news:... > * Edward Muller [2002-09-21 23:00 -0700]: > > I am trying to use HTTPSConnection and HTTPResponse objects [...] > > Is your Python SSL-enabled? Check with: > > import socket > hasattr(socket, "ssl") > > Which version of Python are you using? Be sure to use at least version > 2.2, as it contains many SSL-related bugfixes. > > -- Gerhard From mertz at gnosis.cx Mon Sep 30 01:31:27 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Mon, 30 Sep 2002 01:31:27 -0400 Subject: ANN: Gnosis Utils 1.0.4 Message-ID: Subject: [Announce] Gnosis (XML) Utils 1.0.4 Date: Mon 09-30-2002 BACKGROUND: Gnosis Utilites contains a number of Python libraries, most (but not all) related to working with XML. These include: gnosis.xml.pickle (XML pickling of Python objects) gnosis.xml.objectify (Any XML to "native" Python objects) gnosis.xml.validity (Enforce validity constraints) gnosis.xml.indexer (XPATH indexing of XML documents) gnosis.indexer (Full-text indexing/searching) [...].convert.txt2html (Convert ASCII source files to HTML) gnosis.util.dtd2sql (DTD -> SQL 'CREATE TABLE' statements) gnosis.util.sql2dtd (SQL query -> DTD for query results) gnosis.util.xml2sql (XML -> SQL 'INSERT INTO' statements) gnosis.util.combinators (Combinatorial higher-order functions) gnosis.util.introspect (Introspect Python objects) ...and so much more! :-) ------------------------------------------------------------------------ This release contains a variety of minor bugfixes contributed by users: * gnosis.xml.validity accidentally left out of 1.0.3 distribution. * gnosis.introspect has minor improvements/corrections. * User contributed, but not really tested, improvements to gnosis.indexer. Let me know if this breaks something (it has to do with reindexing working correctly). * Cleanup of gnosis.xml.objectify bug introduced in 1.0.3 (problem was detecting file object rather than string or DOM). * Probably something else I forgot. It may be obtained at: http://gnosis.cx/download/Gnosis_Utils-1.0.4.tar.gz The current release is always available as: http://gnosis.cx/download/Gnosis_Utils-current.tar.gz Try it out, have fun, send feedback! David Mertz (mertz at gnosis.cx) From amitp at Xenon.Stanford.EDU Thu Sep 5 12:16:29 2002 From: amitp at Xenon.Stanford.EDU (Amit Patel) Date: 5 Sep 2002 16:16:29 GMT Subject: A Free Idea: Search Engine for Webpages References: <477762c2.0208260615.3790945@posting.google.com> <3D6AB55D.63D36207@engcorp.com> Message-ID: Peter Hansen wrote: | Dave Brueck wrote: | > | > What I find useful is Google's presentation of cached content (the one | > you get to by clicking a search result's 'Cached' link instead of the | > main link presented) because it highlights in a different color each | > word from your search. It gives you an easy way to quickly and | > visually scan a document searching for relevant content. I just scroll | > down the page looking for concentrations of pretty colors! ;-) | | I believe there is some kind of add-in for IE and maybe Netscape | and/or others which puts a little search field in your browser | toolbar and lets you search any given page in the same way, including | highlighting the search terms exactly as in the cached version. The Google Toolbar does this, but it's IE only. In addition to the highlighting, after you search, it shows the search words in the toolbar and you can click on them to jump to them on the page. There are other toolbars now that do the same sorts of things. Someday I'd like to implement this in Python -- not as a web server or browser client plugin, but as a proxy. I can parse the page as it's coming through and insert a navigation box at the top. It'd be handy to see the structure of the page (h1 - h6, but in a tree), the anchors, links to the words I last searched for. With DOM and CSS, you can do some fancy UI stuff to make the navigation box almost as nice as something that's embedded in your browser. And the most important feature: add a button to kill the colors on any page that uses dark blue links on a black background! - Amit -- -- Amit J Patel, Computer Science Department, Stanford University http://www-cs-students.stanford.edu/~amitp/ From robin at jessikat.fsnet.co.uk Sun Sep 1 04:46:37 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sun, 1 Sep 2002 09:46:37 +0100 Subject: ANN: New PEP Format: reStructuredText References: Message-ID: In article , Richard Jones writes >On Sun, 1 Sep 2002 12:22 am, Robin Becker wrote: >> . >> .... >> >> >But if it strictly stays limited to PEPs, the cost might be higher than >> >the benefits. It ought to aim some wider scope of applicability. >> >> Well I think I can say that if anyone brings the reStructuredText --> >> pythonpoint translator to reasonable fruition then it would appear as a >> working demo on www.reportlab.com ie paste in your text, get back your >> pdf slides. That would be a good advert for python and reportlab. > >This is done in the docutils sandbox under the richard/pythonpoint directory. >I had this working ages ago (back in March, I think) but hadn't updated it >when David merged the dps and restructuredtext projects to form the docutils >project. That's done now. > > > Richard > > So does this appear as a CGI somewhere or should I go ahead and make a working demo? -- Robin Becker From ben at remove.Stanford.EDU Tue Sep 10 19:03:40 2002 From: ben at remove.Stanford.EDU (Ben Escoto) Date: Tue, 10 Sep 2002 16:03:40 -0700 Subject: Large file support and stat vs stat64 in extension modules Message-ID: Hi, I'm writing an extension module in C and am having trouble statting files longer than 2GB, at least under linux (Redhat 7.2, intel). If I simply use the stat() system call, I get an EOVERFLOW error (OSError: [Errno 75] Value too large for defined data type). It seems that I should be using the newer stat64() call, but: 1. posixmodule.c appears just to use plain old stat(). I cannot figure out why I get errors and it works fine. Quite a mystery. 2. I don't know what #if defined's to put in to choose between stat and stat64 correctly. Does anyone know how to correctly stat a file within an extension module? Why does: struct stat st; res = stat("bigfile", &st) not work for me, but in posixmodule.c the same thing (apparently) is done and works fine? -- Ben Escoto From maurice at akst.tn.tudelft.nl Wed Sep 18 03:11:06 2002 From: maurice at akst.tn.tudelft.nl (Maurice van de Rijzen) Date: Wed, 18 Sep 2002 09:11:06 +0200 Subject: Getting data into an array in NumPy from an other object? Message-ID: Dear all, I've encountered a problem. In one object I've a function: class blah: ... ... def GetData(self): return self.data Now I want to put his data into an instance of Numeric.array. The broblem is that I cannot find and think of any way to do this. Does anyone knows a solution for this. Maurice From tjreedy at udel.edu Thu Sep 5 00:30:30 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 05 Sep 2002 04:30:30 GMT Subject: Python Source Code Documentation References: Message-ID: "Sean Ross" wrote in message news:al69st$n1f$1 at driftwood.ccs.carleton.ca... > Hi. I'm interested in trying to get an understanding of Python's source > code. If you mean the C source of the Python interpreter, you mostly are on your own. You can try groups.google to retrieve past posted discussions. Beyond that, the source is its documentation. You can probably learn quite a bit by spending an hour or two. TJR From hamish_lawson at yahoo.co.uk Mon Sep 23 12:48:48 2002 From: hamish_lawson at yahoo.co.uk (Hamish Lawson) Date: 23 Sep 2002 09:48:48 -0700 Subject: Will "Python in a Nutshell" be too short? References: Message-ID: <915a998f.0209230848.60cc1415@posting.google.com> Steve Holden wrote: > I wil be very surprised if Alex' book does not become the canonical > reference for the language, since his treatment is exceptionally thorough > and (even for him) more than usually precise. I had no doubts about this - I'm just a greedy so-and-so who wanted to have Alex's treatment over as wide a range of material as would fit into a book that could still qualify to be called a nutshell! I'm therefore delighted to learn from Alex that his book will in fact cover a good number of the most popular third-party libraries, and I'll therefore get to throw away a bunch of printed-out notes after all (which is what I meant when I hoped that "Python in a Nutshell" would be a one-stop reference). I know Alex wanted to keep the book to about 400 pages, but for me the 600 pages that the book has grown to is still nutshell enough and a small price to pay for the breadth of coverage. I'm looking forward to it. Hamish From lutz at lutz-horn.de Mon Sep 16 07:54:24 2002 From: lutz at lutz-horn.de (Lutz Horn) Date: 16 Sep 2002 13:54:24 +0200 Subject: Good book choice? References: Message-ID: eva_ag at eresmas.com (Eva) writes: > I am new to Python but an experienced programmer in Fortran95 (not > too object oriented). I am looking for a suited Python book. I'd > like it to have clear ideas about OO, as well as an straight > pointing into the core language. Take a look at "Dive Into Python - Python for experienced programmers"[1]. It's Free (as in speech) and goes straight to the point. Regards Lutz [1] http://diveintopython.org/ From sschwarzer at sschwarzer.net Fri Sep 27 16:29:31 2002 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Fri, 27 Sep 2002 22:29:31 +0200 Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> <3D934C5C.4000603@mxm.dk> <20020926.130938.1789366143.1524@cybermesa.com> Message-ID: <3D94BFAB.5060506@sschwarzer.net> Tim Hochberg wrote: > "Jay O'Connor" wrote: >>How about "underder"?? > > Or maybe "dunder"? I think, you shouldn't use two words which sound very similar when spoken. If you do this, you might run into problems when discussing code via voice (e. g. telephone). I like "under" vs. "under-under" most: It's short enough and even someone who hasn't heard it before, probably will guess what it means. Stefan From bokr at oz.net Mon Sep 2 15:07:07 2002 From: bokr at oz.net (Bengt Richter) Date: 2 Sep 2002 19:07:07 GMT Subject: Help with mod_python References: Message-ID: On Sat, 31 Aug 2002 12:54:09 -0400, "Joseph Youssef" wrote: >Hello, I've been trying to get python to work on apache, so I downloaded >mod_python, after I finished the setup process, I tried to test it just like >they indicated with the same code they showed but everytime I to run any >python file on the server, it always gives me this error: > >the file I ran here was called mptest.py > >----------------------------------------------- >Mod_python error: "PythonHandler mptest" > >Traceback (most recent call last): > > File "C:\PROGRAM FILES\PYTHON\lib\mod_python\apache.py", line 181, in >Dispatch > module = import_module(module_name, _req) > > File "C:\PROGRAM FILES\PYTHON\lib\mod_python\apache.py", line 332, in >import_module > f, p, d = imp.find_module(parts[i], path) > >ImportError: No module named mptest >---------------------------------------------- >I don't know how to fix it so if you know how then please help > Apache is probably running as a different user than you (e.g., maybe IUSR_XXX, where XXX is your computer name), so probably you have to move mptest.py to some directory (you may want to create one in the tree it already knows about for web stuff) where apache can find it, or tell it where to find stuff in your personal part of the disk (the latter is not a good idea security-wise). There could be other problems, but that would be my first guess. Regards, Bengt Richter From Roberto at lupi.an.it Mon Sep 23 02:42:35 2002 From: Roberto at lupi.an.it (Roberto Lupi) Date: Mon, 23 Sep 2002 06:42:35 GMT Subject: Universally unpacking tuples References: <158d3913.0209222233.123a9675@posting.google.com> Message-ID: In article <158d3913.0209222233.123a9675 at posting.google.com>, peter.bittner at gmx.net says... > The root of the problem is that I am forced to move from a > list-solution (iterating over the elements of a list) to a > tuple-solution (iterating over the elements of a tuple). So, what I am > trying to do with the above code is nothing more than migrating the > following list-oriented code to a tuple-thing: > > mylist = ['abc', '123', 'qwert', ...] > for i in range(len(mylist)): > elem = mylist[i] > print elem > > > Does anyone know a simple solution to this problem? mylist = ('abc', '123', 'qwert', ...) for i in range(len(mylist)): elem = mylist[i] print elem Or better: for x in mylist: print x -- Roberto Lupi From bada at skumbad.nu Sun Sep 22 10:36:59 2002 From: bada at skumbad.nu (harald) Date: Sun, 22 Sep 2002 14:36:59 GMT Subject: cursor positioning and color References: Message-ID: TuxTrax wrote: > Being new to python, I would like to know how one goes about such > tasks as precise cursor positioning and output to screen in color. > > For instance, If I want to print a character or line, at line 10, > column 18, in bright white on red, how would I accomplish this? > > Is there a python library specifically for setting up a text screen > to look and function the way you want it to, without having to use a GUI? > > The SLRN screen is a good example. Obviously, text positioning and coloring > commands are being utilized here, as well as such things as clearing > the screen and controlled scrolling. > > How would these things be done in python, and what reference material is > available on line? I couldn't find anything in the Python manual, so any > URL's would be appreciated well.. there's the curses module. it's a standard module so the docs are in the library reference.. or if you just want to do something simple, you can just use ansi escape codes directly, so to 'print a character or line, at line 10, column 18, in bright white on red', you could write print "\033[10;18H\033[37;41m" + string after a quick search on google i found this reference: http://www.dee.ufcg.edu.br/~rrbrandt/tools/ansi.html -- /harald bada at skumbad.nu http://bada.skumbad.nu/ makt leder till missbruk. From phr-n2002b at NOSPAMnightsong.com Mon Sep 30 00:42:21 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 29 Sep 2002 21:42:21 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xelbcgo56.fsf@ruckus.brouhaha.com> Message-ID: <7x65woks0i.fsf@ruckus.brouhaha.com> "Chris Gonnerman" writes: > > What do you mean by "right"? What do you mean by "all > > cases"? > > The original subject is *business* arithmetic. There is no > choice but to use decimal arithmetic if you want your math > results to match good-old-fashioned pen and paper math. No, I'm still not convinced. Is business arithmetic well-defined enough that you can never do the same calculation two ways and get different results? Example: bunches are three for a dollar. How much do you pay if you buy nine bananas? Answer #1: price_per_banana = 1.00 / 3 number_of_bananas = 9 total_price = number_of_bananas * price_per_banana print total_price Answer #2: price_per_bunch = 1.00 # three bananas number_of_bunches = 3 total_price = number_of_bunches * price_per_banana print total_price With floating point and rounding on output, you get the same answer both ways. With decimal arithmetic, you get $2.97 the first way and $3.00 the second way. For "business arithmetic" to always give the same answer, it has to forbid at least one of those methods of doing the problem. From borcis at removethis.infomaniak.andthis.ch Sat Sep 21 08:40:44 2002 From: borcis at removethis.infomaniak.andthis.ch (Boris) Date: Sat, 21 Sep 2002 14:40:44 +0200 Subject: filter(lambda W : W not in 'ILLITERATE','BULLSHIT') (Re : python expression) References: <3D86FF01.FE0CECC5@geneva-link.ch> <3d87069c.34652637@news.rcn.com> <3D871316.AA1E8FFC@geneva-link.ch> <3d882cd4.9181792@news.rcn.com> <3f74f974.0209180713.27889f74@posting.google.com> <3d88c258$0$707$5402220f@news.sunrise.ch> <3d89be92$0$707$5402220f@news.sunrise.ch> <3d89ee85$0$712$5402220f@news.sunrise.ch> <3d8b4498$0$717$5402220f@news.sunrise.ch> Message-ID: <3d8c6982$0$719$5402220f@news.sunrise.ch> Terry Reedy a ?crit dans le message : WSLi9.165658$z91.6788612 at bin3.nnrp.aus1.giganews.com... > > "Boris" > > > > filter(lambda W : W not in 'ILLITERATE','BULLSHIT') > > This somewhat-well-known and certainly well-worn programmer joke Well, *I* invented this formula myself soon after Mr Bush revealed to the world that "USA" is written in "CRUSADE" just like "US" is in "BUSH". Adding : "Either you are with US, or you are against US". It's not a joke, it's a comment on being called to participate to a folly that is given no other justification than allusions to kindergarten references that are specific to the US as a pretext to eg licking boots to the - militarily speaking - most powerful man in the world, and - intellectually speaking - most dangerous man in the world for a man in that position. The full form of it I have never published, and it is : filter(lambda I : I not in 'USA','CRUSADE' )==( 'C' + filter(lambda I : I not in 'U','RUDE') ) and ( filter(lambda W : W not in 'ILLITERATE','BULLSHIT')) Since I invented it, I know exactly how much I distributed it myself, and your I-am-expert-on-the-matter tone falls flat. I would rejoice on the implication that it has been more widely distributed that seems to stem from your words, except that, well, there is some ground for me to doubt your good faith on that point. Noticed BTW how the typhoon that recently befell Corea was called RUSA ? US, BUSH, BULLSHIT ; USA, RUSA, CRUSADE Speak of butterflies... > functional programming expression, borrowed from Lisp, etc, that > happens to have been written this time with Python syntax in > preference to the Lisp or other FP syntax that could have been used > instead. (A good choice for presentation to non-programmers, but > that's another issue.) It has nothing to do with Python in > particular. That's about as precise as saying the following other semi-joke of mine is base-dependent : "12 ? - 12 is the least integer symbolizing the natural integers by itself. Its successor is 123" You know as well as I do that although it's clear that the computation implied by filter(lambda W : W not in "ILLITERATE","BULLSHIT") can be easily translated to another language, its more direct reading highly depends on a layout and details of sequence behavior that python provides and for which it is not a priori clear that immediate equivalents are available in other programming languages. > One could just as well justify cross-posting to lisp and That would be true if the equivalent lisp one-liner existed, and *I* know I never wrote a translation. Why don't you prove what you say by providing one ? But in any case you are probably right on one point : the right way to advertise the thing is to open a competition for translations into other programming languages. Then we could actually measure the material ground of your easy assertions. > other functional programming groups, but please don't. > > > > and should never have been added. > > > > That's a dogmatic opinion that I believe lacking in justification. > > I base my opinion (which I still hold) on the complete lack of any > particular relevance to Python, the computer programming language I notice that you carefully avoided adressing my point on this matter. What I pointed out in the message you fake responding to [in a way, if I may say so, itself depicted in spirit by my formula] is that the irony in filter(lambda W : W not in "ILLITERATE","BULLSHIT") is much enhanced when having the technical details of python (such as is responsibility of experts) put aside in the same manner that the detailed machinery of Prolog (as experts come to intuit it) is put aside when contemplating the first-order logic reading of the Prolog code. Now you answer "us" with a batch of non-sensical Lisp context. Yes, sure, lambda and filter are found in lisp. The real question is whether lisp allows to write it down in a form that doesn't give away that the implementation operates from a differently structured parse tree. Thus with minimal uncamouflaged clutter between ILLITERATE and BULLSHIT : no best inquisition rule. > and > the presence of very un-Pythonic ugliness Ah, you are an aesthetician of pythonicity - will you deny the title as ugly, pythonically speaking ? But then, what's your competence to formulate such assertions ? Okay, say we'd look into the virtues and vices of Python as a programming language to describe cool and simple algorithms fit to form the flesh of the code in a file of Python featuring ten lines such as : from battle.devices.russianRoulette import QuantumRussianRoulette Class DieteticWar(War) : def __init__(self,Democracy,Tyrant) : assert self.casusBelli.provided(Tyrant), RelevanceException assert self.ultimatum.provided(Democracy), CenturyException What about it ? Perhaps Dylan is better, perhaps not. The real question is how much time do we have before the time bandits get it their way no it's more clearly that UN has to check grammatical well-formedness of any ultimatum Mr Bush submits in the name of furthering the UN's own intentions. Grammatical well formedness of ultimata implies that simply saying "I will enter war against you in N days" in camouflaged language doesn't cut it. Such a language is not an ultimatum, it's a war ruse directed against the more naive public. Since it is in no way the UN's role to promote war ruses, the UN should simply force US ultimata to obey ISO 9000-type standards certification procedures. I-ll-be-back-unless-nazis-kill-me-in-the-meantime-ly yours, Boris -- "W is a mass-creating boson. Mass makes gravity. What do superstrings say ?" From peter at engcorp.com Fri Sep 13 21:28:32 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 13 Sep 2002 21:28:32 -0400 Subject: transform list of int in a list of string?? References: Message-ID: <3d8290af$1@news.sentex.net> jubafre at brturbo.com wrote: > my program have other modules imported, like re and sre and i put a convertion int to str but doesn?t work > t=str(x[i]) > Traceback (most recent call last): > File "C:\Documents and Settings\jubafre\Desktop\montador\teste.py", line 78, in ? > t=str(x[i]) > TypeError: 'list' object is not callable This error is most likely because you created a list object bound to the name "str". Do *not* use "str" or other such reserved names as variable names if you want to preserve your sanity. :-) > Why i can?t transform a int number in string in my program??? > I tryed with import string, and can?t too, > but if i start a new python shell it works, why?? Because when you restarted Python the new session did not have the variable called "str". >>>>x=[1,2,3,4,] >>>>s=[] >>>>for i in range(len(x)): > t=str(x[i]) > s.append(t) >>>>print s > ['1', '2', '3', '4'] By the way, although this code works, it is not at all what we would call "Pythonic". It looks like code from some other language translated to Python. For example, in Python you don't need to (and rarely want to) use index variables to iterate through a list like that: you can directly iterate on the list items like this: >>> x = [1, 2, 3, 4] >>> s = [] >>> for item in x: ... s.append(str(item)) ... >>> print s ['1', '2', '3', '4'] Note though that there are two tools for doing this kind of thing much more easily, as shown in the postings by Skip Montanaro or Erik Max Francis. The "map" method is older but has advantages in certain circumstances, while the other method is called a "list comprehension" and can be both more readable and faster, again depending on circumstances. In general, there are a lot of Python idioms which work in a similar fashion, going in ways traditional languages have not. They're well worth watching for and learning. (But your code has one strong point in its favour, for a newbie: it works! :-) -Peter From bdesth at nospam.free.fr Mon Sep 16 22:12:50 2002 From: bdesth at nospam.free.fr (laotseu) Date: Mon, 16 Sep 2002 22:12:50 -0400 Subject: Book for win32? References: Message-ID: <3D868FA2.4040503@nospam.free.fr> Syver Enstad wrote: > Thomas Guettler writes: > > >>Hi! >> >>I am interested in book about Python on win32. >> >>I found one from o'reilly: "Python on win32" >> >>Are there better books or alternatives? >> >>I am *not* looking for a python introduction, I am >>programming more than one year with python, but up to >>now mostly on unix. >> >>Now I am intersted in win32 stuff: >> - Opening a file-dialog >> - COM >> - Accessing the registry >> - Maybe GUI Programming > > > Then you can't go wrong with the o'reilly book. It is a most excellent > tome for precisely the subjects that you outline there. > > Be aware that the book is written for Python 1.5 so a couple of > things, like the need to convert unicode strings passed in by COM > objects are outdated. As you already have been programming python for > over year this shouldn't be a problem. > > I'd just add one advice : if you're not familiar with the w32 API, go and get yourself a good reference of it ! (I think you can get the win32 API ref on borland's site, with the free version of bcc55). Laotseu From ajs at ix.netcom.com Thu Sep 19 14:27:25 2002 From: ajs at ix.netcom.com (Arthur) Date: Thu, 19 Sep 2002 14:27:25 -0400 Subject: Python sequences by reference - how to make clear Message-ID: <00d001c2600a$348dc180$9865fea9@arthur> >Yes, this is fully in accordance with how the Python language should behave: > Res += [rec] inserts references to list object rec, > which are further modified... (he should use copy(rec) instead). Yes, this issue in various guises bit me for some time after I began using Python (self.-taught, as a fist programming language). It had always seemed to me that if there were a copy operator, or (perferably, to me) that the functionality of the copy module were in the language core as a built_in, that I would have been on clearer notice that there was something fundamental in this area to which I needed to pay attention and become attuned. In looking into it I did find some discussion of the issue on python-list. Interestingly it was also math/Numeric folk who seemed to be rasing the question then and advocating something along the lines of a built_in operator for copying. I however think that the issue is quite real for anyone coming to Python without the benefit of either a programming background or a formal structure within which they are being taught the language. I have felt strongly that others have been too quick to advocate changes to the language to address "special needs" cases. And that the special needs cases of the novice have been over-emphasized in discussions, in general. And I have confirmed to myself in the work I have been doing recently, which is specifcally addressed to the non-programmer, that those "special needs" can most often be quite adequately addressed by the right interface design, using Python's out of the box capabilities.. I admittedly have little understanding of the full implications of a suggestion to make the copy module capabilities built_in. But I do believe, all things else being equal (which I suspect they are not), it would be quite helpful. Art From gumuz at looze.net Thu Sep 12 04:54:40 2002 From: gumuz at looze.net (Gumuz) Date: Thu, 12 Sep 2002 10:54:40 +0200 Subject: class variable won't icrement! Message-ID: <3d8054ef$0$234$4d4ebb8e@news.nl.uu.net> Hello everyone, I have something very strange and i can not understand it. probably, it's not _that_ strange : ) I have this simple class which registers itself on a class variable in the following code: ---------------------------------------------------------------------------- ------ class test: dict = {} id = 1 def __init__(self, name): self.dict[name] = self self.id = self.id + 1 def show(self): print "class variable dict element count: ", str(len(self.dict)) print "class variable id: ", self.id ---------------------------------------------------------------------------- -------- now, look at the following: >>> john = test("john") >>> frank = test("frank") >>> bill = test("bill") >>> bill.show() class variable dict element count: 3 class variable id: 2 >>> frank.show() class variable dict element count: 3 class variable id: 2 The dict variable acts fine, maintaining it's content throughout every instance of the class. The id variable however, seems to be only incremented within the instance. In the end this variable should've been 4. Could someone explain this to me? Is there something about class variables whta i should know? many thanx, Guyon From gerhard.haering at gmx.de Fri Sep 13 15:03:52 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 13 Sep 2002 19:03:52 GMT Subject: Problem with HTTPS request References: Message-ID: Christian Reyes wrote in comp.lang.python: > I'm on Win 98. > i don't have a development env in which to build the python socket module. > was hopoing someone could point me to somewhere i could find a premade one. > > Thanks though, > if you could point me to a site or two, that'd be great' Please don't top-post. http://www.cs.tut.fi/~jkorpela/usenet/brox.html http://www.uwasa.fi/~ts/http/quote.html > Jeremy Hylton wrote in message > news:b0f083db.0209130558.2aa60398 at posting.google.com... >> "Christian Reyes" wrote in message > news:... ^^ Broken quoting. >> > [...] Note: HTTPS support is only available if the socket module was compiled > with ^^ Broken quoting again. Please throw away that OE crapware or fix it using Morver or whatever. Now to answer your question: I've compiled a socket.pyd for Python 2.2.x with SSL support. You can download it at my homepage: http://www.cs.fhm.edu/~ifw00065/pyssl/ -- Gerhard From gua81 at XXXyahoo.com Fri Sep 27 04:46:29 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Fri, 27 Sep 2002 18:46:29 +1000 Subject: Making directory in cgi! References: Message-ID: and one more thing...... what's going to happen if let say, the directory simpsons already exist inside homer. What will happen to the files inside simpsons??? Thanks. "CheapSkate" wrote in message news:an15gg$s3h$1 at lust.ihug.co.nz... > HI, > let say my createdir.cgi is in > /bug/ger/createdir.cgi > and doing ls in /bug/ger/ will list out > . > .. > (file)createdir.cgi > (dir)homer > how do I create directory inside homer? > like homer/simpsons/ > ??? > what are the library that I need to import? > Thanks...... > (I know this is a simple Q, so please excuse me... im a newbiee) From donn at u.washington.edu Wed Sep 11 12:04:47 2002 From: donn at u.washington.edu (Donn Cave) Date: 11 Sep 2002 16:04:47 GMT Subject: blocking socket dilemma References: <3d7f046f$0$230$4d4ebb8e@news.nl.uu.net> Message-ID: Quoth "Gumuz" : | I am a little bit stuck with my design (again!). | | I have this server class, which creates a session object for every accepted | incoming connection. The session object has a RequestHandler function which | is then run in a new thread. | | all fine, but... | | This RequestHandler function actually does a infinite loop. The loop wil | receive data and take some action and it will send data which is piled up in | this session's queue. The problem that i'm having is that the loop will hang | on socket.recv if the client is not sending anything. Ofcourse this is very | obvious and logical, but i can't think of another way of constructing my | design, so that this problem doesn't occur. If it helps, you can use select.select() to determine whether the device has more input ready, immediately or with a timeout at your discretion. Donn Cave, donn at u.washington.edu From andrewm at object-craft.com.au Wed Sep 18 01:08:48 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Wed, 18 Sep 2002 15:08:48 +1000 Subject: How to make a C extension module backwards compatible? In-Reply-To: Message from martin@v.loewis.de (Martin v. Loewis) of "18 Sep 2002 06:47:43 +0200." References: Message-ID: <20020918050848.1CB6E3C21B@coffee.object-craft.com.au> >> Is there any community wisdom on how to make a C extension module that >> implements a new-style class (type?) backwards compatible (albeit, >> at the cost of some functionality)? >> >> Put another way, how *should* I make a class implemented in C behave >> like a new-style class when installed with python 2.2 and above, and >> like an old style class when installed with older pythons? > >What properties of a new-style class are you interested in? If you >implement a plain type, it will work on all Python versions, no need >to change anything for Python 2.2. That's a good question - this is more of a learning exercise than a project with a real need. I guess the most useful attribute would be sub-classing. We have an existing module that implements a fast csv parser[1] - if it's easy to make it's "parser" class able to be sub-classed, it would be worth doing it (I guess the socket module is a decent example). [1] http://www.object-craft.com.au/projects/csv/ -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From tjreedy at udel.edu Thu Sep 12 09:36:08 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 12 Sep 2002 13:36:08 GMT Subject: [ANN] PySQLite 0.3.0 released References: Message-ID: "Gerhard H?ring" wrote in message news:slrnao0e6p.23c.gerhard.haering at haering.opus-gmbh.net... > A Python-DB API 2.0 compliant extension module that connects to > SQLite databases. ... > row = cursor.fetchone() > > while row != None: > print "%14s, %15s, %19s, %8s, %25s" % tuple(row) > row = cursor.fetchone() Does anyone know whether there are any plans to update the Python-DB API to the new iterator protocols, so that the above could be written more simply something like for row in cursor: print "%14s, %15s, %19s, %8s, %25s" % tuple(row) ? Terry J. Reedy From kingprad at mail.com Mon Sep 9 10:52:10 2002 From: kingprad at mail.com (Carl) Date: 9 Sep 2002 07:52:10 -0700 Subject: web crawler help? References: Message-ID: <668b76ce.0209090652.4b074a1b@posting.google.com> I just wanted to say also that a lot of sites have a robots.txt file in the root directory with a list of pages the crawler shouldn't troll through. it's polite to honor it if you're grabbing tons of pages from a server. Probably fine to ignore if you're not using a lot of server time and only doing a few simple tasks. From timr at probo.com Sat Sep 14 01:58:43 2002 From: timr at probo.com (Tim Roberts) Date: Fri, 13 Sep 2002 22:58:43 -0700 Subject: Question regarding mysqldb module and variable table names References: <45ac92e5.0209131920.23b1c22a@posting.google.com> Message-ID: ezcoder at mailcity.com (Glenn Scott) wrote: > >I want to change it so that the "mytable" value in this example is a >variable rather than a constant. So the code would look like this: > > c.execute("""INSERT INTO %s \ > SET playerkey=%s, link=%s, snippet=%s, time_created=%s, \ > last_seen=%s, relevancy=%s, doc_title=%s """, \ > (infoTable, playerKey, urlLink, snippetText, >self.getCurrentTime(), self.getCurrentTime(),\ > noOfMentions, re.escape(str(self.doc_title))) ) > >But this doesn't work...for whatever reason, using "%s" in an >assignment SET variable works, but as a table name it doesn't. > >I suppose I can use the "%" string formatter at the end of the >triplq-quotes to fix this problem, but I'll have to jump through other >hoops to deal with oddness with my data that is taken care of for me >by using the "," alternative. Not at all. This should work: c.execute("""INSERT INTO %s \ SET playerkey=%%s, link=%%s, snippet=%%s, time_created=%%s, \ last_seen=%%s, relevancy=%%s, doc_title=%%s """ % infoTable, \ (playerKey, urlLink, snippetText, self.getCurrentTime(), self.getCurrentTime(),\ noOfMentions, re.escape(str(self.doc_title))) ) Do you realize you do not need to escape the ends of lines when you use triple quotes, nor outside the quotes when you are within parentheses? c.execute("""INSERT INTO %s SET playerkey=%%s, link=%%s, snippet=%%s, time_created=%%s, last_seen=%%s, relevancy=%%s, doc_title=%%s """ % infoTable, (playerKey, urlLink, snippetText, self.getCurrentTime(), self.getCurrentTime(), noOfMentions, re.escape(str(self.doc_title))) ) If ''' are triple quotes, aren't """ sextuple quotes? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From pedronis at bluewin.ch Wed Sep 18 03:19:23 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Wed, 18 Sep 2002 09:19:23 +0200 Subject: Calling Python from C# - please help References: <6de16ac9.0209130508.5d1b56c6@posting.google.com> <0iCg9.2350$Ee4.6516@news-server.bigpond.net.au> <3D82FA5B.3050003@mxm.dk> <3%Dh9.15217$Ee4.45118@news-server.bigpond.net.au> <3d877db8_5@news.bluewin.ch> Message-ID: <3d882a59_4@news.bluewin.ch> Mark Hammond wrote in message IpSh9.17251$Ee4.52376 at news-server.bigpond.net.au... > Samuele Pedroni wrote: > > > How were you going to support eval and exec? > > The compiler itself is written in CPython. The intention was to get the > compiler good enough to compile itself - then we will have a .NET > compiler able to be built into the Python runtime. exec and eval would > leverage this. > > > For the moment the unload granularity of .NET is AppDomains only and only > > upon explicit request, and types/modules/assemblies are not garbage > > collected but simply live as much as the AppDomain, > > App Domains can be dynamically created tho, which may help. that's also the workaround MS proposes to the people that encounter the issue. But > > that's OK for static languages, or environments with a clear run/design time > > distinction (one can setup an AppDomain and tear it down for each > > run-cycle), or for running scripts in isolation but not if one wants IL/JIT > > speed for a enviroment that allows for redefinitions and eval, ... > > > > In Jython we create Java bytecode and dynamically load classes for all the > > code, also eval code because in Java classes are elegible for garbage > > collection. > > > > In .NET it seems one needs a pure interpreter that does not compile to IL > > for exec and eval support, and that seems what JScript does for jsc compiled > > code containing eval, that means the script is compiled but the evaluated > > code is only interpreted, > > Im not really convinced of that. Reflection::Emit has IL generation > capabilities purely for "dynamic" code - the example used in their docs > is that regex engines could compile down to IL on-the-fly. Indeed, that's also what they allow for their regex impl, but if one reads the fine points about regex http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/htm l/cpconcompilationreuse.asp "However, generated MSIL cannot be unloaded. The only way to unload code is to unload an entire application domain ..." ... Out of mem danger. > > otherwise a long running process using eval could go out of memory. > > > > That's something people wanting to write a feature complete impl of Pyhton > > for .NET should consider or wait MS to implement a more > > dynamic-environment-friendly unload policy. > > Yes, I see your point, but AppDomains are really quite powerful. I > believe there are no restrictions between cross domain calls. but that means Remoting ... > Managing > the lifetime of the dynamically created domains may be an issue though. I fear yes, also given that the reload unit of Python is a module, one would need one AppDomain for each module,exec unit etc produced code and then a way to manage the lifetime of all this distributed-across-AppDoms stuff. A lot of headaches for what externally seems just a very shortsighted design decision on their part. Otherwise, as I said, there's the interpreter route, which is JScript eval approach... regards. From jb at yahoo.de Thu Sep 26 00:36:25 2002 From: jb at yahoo.de (JB) Date: Thu, 26 Sep 2002 06:36:25 +0200 Subject: Python on a Novell server Message-ID: <3d928cb5_6@news.newsgroups.com> We have a Novell net at our school and are trying to install Python 2.2 on a Novell server. This does not work at the moment as we get the error message "python.dll not found" at the moment. Is it possible to install Python a a server or has it to be installed locally on each workstation? -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From loewis at informatik.hu-berlin.de Sun Sep 15 14:01:53 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 15 Sep 2002 20:01:53 +0200 Subject: Python11 References: Message-ID: "Kevin Altis" writes: > Is Portland, OR the official location, I didn't think that had been decided > yet? Might indeed still be undecided. I found it on the O'Reilly page (somewhere), so I'd consider it semi-official. Regards, Martin From chrisabraham at yahoo.com Thu Sep 26 14:19:23 2002 From: chrisabraham at yahoo.com (Chris Abraham) Date: Thu, 26 Sep 2002 11:19:23 -0700 (PDT) Subject: Dedicated Server Recommendations? In-Reply-To: Message-ID: <20020926181923.18596.qmail@web20703.mail.yahoo.com> Hey all: I would like to ask you all if you could recommend some inexpensive-but-good dedicated server hosts that I could hire to run Zope/Pyhton-CGI/PHP4/MySQL/PostgreSQL/IMAP? I always prefer to ask Open Source people for this kind of thing because in general, pricepoint is very important. Thanks in Advance! Chris ===== -- chris abraham +1 202-452-7442 tel po box 15163 washington, dc 20003-0163 +1 202-478-0276 fax From padraig at linux.ie Sun Sep 15 15:57:27 2002 From: padraig at linux.ie (Padraig Brady) Date: Sun, 15 Sep 2002 19:57:27 GMT Subject: python performance Message-ID: <3D84E66F.6020701@linux.ie> I was wondering about the performance characteristics of python and ran a simple test. The 2 programs below are functionally equivalent and just read in fields into a list. file.fields contains 720 fields in each of 405 lines of the form of repeating: oneoneone twotwo "thre e three" The time to run is shown above each program from which I've inferred the following: 1. The function call version is (6.3%) faster because the cumulative cost of parsing the simpler expressions and function call overhead is smaller than parsing the 1 single complex expression? Or the function is parsed only once and doesn't have to be reparsed. This would suggest that top level code is parsed for each iteration? 2. Anyway I thought that parsing affects would be removed by doing the parsing only once, i.e. compiling the code to .pyc (I used py_compile.compile()). However this makes no difference at all? Surely compiling is not just for code obfuscation. Note I did do the test several times and averaged the results. cheers, P?draig. ---------------------------- 2.514s ---------------------------- #!/usr/bin/env python2.2 import re reFieldFinder = re.compile('[^ "]+|"[^"]+"') #unquoted|quoted def getFields(line): fields = reFieldFinder.findall(line) return [field.replace('"', '') for field in fields] for line in open("file.fields").readlines(): listLine = getFields(line[:-1]) ---------------------------- 2.672s ---------------------------- #!/usr/bin/env python2.2 import re reFieldFinder = re.compile('[^ "]+|"[^"]+"') #unquoted|quoted for line in open("file.fields").readlines(): listLine = [field.replace('"', '') for field in reFieldFinder.findall(line[:-1])] From dsavitsk at e-coli.net Wed Sep 18 02:53:41 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Wed, 18 Sep 2002 06:53:41 GMT Subject: Win32COM & Detaching from automation servers References: Message-ID: "Brian" wrote in message news:ef3269df.0209171441.2d6f8e59 at posting.google.com... > I've searched this newsgroup for an answer to my problem, but haven't > come up with anything. (Perhaps the solution is obvious and I'm just > not seeing the forest for the trees...) > > I want to write a Python program on Windows which will use the > automation interface for Excel. What I want it to do is launch Excel, > open a template, stuff data into it (based on command line parameters > to the Python app), detach from Excel and exit, leaving Excel open. > > I know how to do everything except for the detach part. Any help is > much appreciated. I don't know the real answer (or if there is one other than it seems to work from Word and not from Excel), but one solution might be to save the generated file, close it, and call WinExec() or its ilk to reopen the file visibly. -doug From peter at engcorp.com Mon Sep 9 08:01:36 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 09 Sep 2002 08:01:36 -0400 Subject: Larry Wall's comment on python... References: Message-ID: <3d7c8d8a@news.sentex.net> Brian Slesinsky wrote: > significant. Long-term Python programmers tend to forget how weird it > is to some newcomers to end a function or class just by *stopping*. I don't forget how weird it was to me as a newcomer. I also remember, however, that about fifteen minutes after writing *real* code with it, I realized it was not weird at all, but very sensible and readable. > I also think there would be a certain satisfaction in having a proper > ending, even for folks who are entirely comfortable with Python's > indentation. It's like "Q.E.D." at the end of a proof, or "The End" > at the end of children's book, or signing a message even though the > "From" header line makes it entirely redundant. There's some truth in that. I often end my files with a line that reads "# EOF", which helps me not try to scroll down to find more code, and when I print the file (rare) I can be sure I've found the last page of code. On the other hand, I always put "// EOF" in my C++ and Java code, and /* EOF */ in my C code, so this bit has nothing to do with block structures. And I'd regard a strong desire to do something similar after every single block as an unnatural compulsion. Therapy would be a good next step for people with this problem. <0.87 wink> -Peter From mhuening at zedat.fu-berlin.de Fri Sep 13 02:44:39 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 13 Sep 2002 06:44:39 GMT Subject: [Tutor] Paradox table References: Message-ID: montana wrote in news:mailman.1031848942.4346.python-list at python.org: > Is there a good example on how to use a CSV parser in Python? > You could try one of these modules: http://tratt.net/laurie/python/asv/ http://www.object-craft.com.au/projects/csv/ Hope this helps, Matthias From Oschler at earthlink.net Mon Sep 2 08:24:21 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Mon, 2 Sep 2002 08:24:21 -0400 Subject: Must have Python modules? References: <_THc9.42153$vY2.1039887@e3500-atl2.usenetserver.com> Message-ID: "Gerhard H?ring" wrote in message news:slrnan6k4s.eg.gerhard.haering at haering.opus-gmbh.net... > Robert Oschler wrote: > > What do you want to hear? Everyone's list of favourite Python extensions? > There's likely is more than one for most of us. My favourite is the "this" > module. > Gerhard, In C++, which has thousands of libraries, snippets, etc. there were only a few that I personally used religiously. For example, the Boost Smart Pointer library. In Delphi the Jedi libray is a must-have library with a very broad coverage of functions. Most programmers I talk to, regardless of the language, have a few libraries or [beans/components/plug-ins] which they have fallen in love with and use in almost every, if not every, project. It is that uber-list I want to hear about. I went to freshmeat.net and there are over 695 Python entries. Scanning every project and then figuring out how useful they are would be fun but probably not very productive. In python I already have two that I'm very find of, Secret Labs RegExp module and the xml.dom module. (And the wonderful WingIDE environment for Python development!) I want to know what the other favorites are "out there". thx From bruce_deletethis_dawson at cygnus-software.com Thu Sep 26 02:09:25 2002 From: bruce_deletethis_dawson at cygnus-software.com (Bruce Dawson) Date: Thu, 26 Sep 2002 06:09:25 GMT Subject: SET_LINENO Message-ID: <3D92A46E.2030706@cygnus-software.com> Executive summary: Has the SET_LINENO removal been tested with the HAP debugger, and wouldn't a breakpoint instruction give much larger benefits? As a partial author of the HAP Python Debugger (available on source forge) I read about the imminent removal of SET_LINENO with some worry. It *sounds* like it has been done in such way to not cause debugger problems, but I'm curious if anyone has tested HAP with 2.3. Also, it sounds like the reason for removing SET_LINENO was to improve the performance of Python scripts. However one of the posts on this topic (can't find it now) suggested that the hoped for improvements had not actually materialized. It seems to me (from the sidelines/peanut gallery/wherever) that the biggest performance problems in the SET_LINENO area are when debugging, not when running free, and that therefore this optimization is targeting the lesser problem. The need to check for breakpoints at each line has always made Python debugging performance poor at best. Technically the performance under the debugger doesn't matter, and yet sometimes it does. Having just helped complete a Python based sports game for PC, where real-time performance was critical, I can say that the slowdown in HAP was definitely annoying. So, wouldn't a break-point opcode be a more substantial improvement than removing SET_LINENO? Just bringing up that old topic again to see if it gets any more traction :-) Bruce Dawson Humongous Entertainment P.S. For reference I include the canonical? link to the SET_LINENO discussion. http://mail.python.org/pipermail/python-dev/2000-July/007652.html P.P.S. A breakpoint instruction would also be a boon for asserts - I'd love to be able to stop on the assert when running under a debugger, to see what is wrong before the stack frame unwinds. From ehagemann at comcast.net Tue Sep 24 21:47:05 2002 From: ehagemann at comcast.net (Eric Hagemann) Date: Wed, 25 Sep 2002 01:47:05 GMT Subject: help with print function in extension Message-ID: I'm handcrafting an extension in C If have defined both a str() and a repr() function and when I execute either repr(obj), or str(obj) I get what I expect however if I execute 'print obj' I get the following error Traceback (most recent call last): File "", line 1, in ? SystemError: error return without exception set although 'print str(obj)' works like I think it should Am I mistaken in thinking that 'print str(obj)' should be the same as 'print obj' Cheers From cliechti at gmx.net Fri Sep 27 17:51:14 2002 From: cliechti at gmx.net (Chris Liechti) Date: 27 Sep 2002 23:51:14 +0200 Subject: Better terminal for windows? References: <3D94B037.2020202@motorola.com> Message-ID: Fernando P?rez wrote in news:an2ivs$8fg$1 at peabody.colorado.edu: > The other problem is that the windows terminal doesn't properly honor > ANSI color escapes. I tried a lot to get ipython's coloring to work > under windows and finally gave up in disgust. Why is it that MS can't > be bothered to _ever_ follow the simplest standards? > > So some of ipython's nicest functionality (full support for tab > completion for both objects and files, and color-enhanced > information, tracebacks and even syntax highlighted source info) are > gone under Windows. > > If you know of a way to fix this, patches are welcome :) well there is ansi.sys. if that driver is loaded the terminal undestands ansi escapes. long ago i used it under win95. it's still there in win2k but don't know how to use it. it the old days you needed to load it in config.sys. chris -- Chris From ckasso at sprynet.com Thu Sep 26 16:46:41 2002 From: ckasso at sprynet.com (Chris Kassopulo) Date: Thu, 26 Sep 2002 16:46:41 -0400 Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> Message-ID: <20020926164641.1753ebbb.ckasso@sprynet.com> On 26 Sep 2002 10:56:45 -0700 pknotz at sandia.gov (Pat Notz) wrote: > @ = "at" > ! = "bang" > . = "dot" > * = "star" > > Is there a short (one or two syllable) pronounciation for "__" (double > underscore). "Underscore underscore" and "double underscore" are kind > of long. Somthing like "splat"? Anyone? > How about: _ = "un" __ = "dun" Chris Kassopulo From tjreedy at udel.edu Fri Sep 20 17:56:53 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 20 Sep 2002 21:56:53 GMT Subject: e vs exp()? References: <3a838998.0209191933.1f22e977@posting.google.com> Message-ID: "Fernando P?rez" wrote in message news:amflhl$3eb$1 at peabody.colorado.edu... > Buckshot wrote: > > > Can anyone here explain why I'm getting different results from > > e**2 and exp(2)? Which is more accurate? > > > > Python 2.2 (#1, Mar 27 2002, 14:56:58) > > [GCC 2.95.3 20010315 (release)] on sunos5 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> from math import * > >>>> e**2 > > 7.3890560989306522 > >>>> exp(2) > > 7.3890560989306504 > > As someone already told you, exp(2) gives a more accurate answer. The reason > is, I think, the following: e**2 simply squares e, Thanks. That seems to solve the particular problem posed: >>> e*e 7.3890560989306495 >>> e**2 7.3890560989306495 >>> pow(e,2) 7.3890560989306495 >>> exp(2) 7.3890560989306504 Perhaps x**int is special-cased. But following must have a different explanation: >>> e**2.1 8.1661699125676499 >>> pow(e,2.1) 8.1661699125676499 >>> exp(2.1) 8.1661699125676517 At least two of us expected x**y == pow(x,y) == exp(y*log(x)) (a standard method, and the only one I could find in Abrahamowitz and Stegun, Handbook of Mathematical Functions) but there must be a more direct method being used at least in some C libraries now. Terry J. Reedy From tjreedy at udel.edu Mon Sep 23 21:34:58 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Sep 2002 01:34:58 GMT Subject: e vs exp()? / financial applications References: Message-ID: <6jPj9.161531$216.5939317@bin4.nnrp.aus1.giganews.com> "Andrew Thompson" wrote in message news:mailman.1032801271.6597.python-list at python.org... > One must be aware of the representational issues and accuracy of > arithmetic within a datatype when using numerical types. This is not so > much a Python issue as one of representing the real number line with > float types. ... > W=0.89 / 4 > 1+w+w+w+w > w+w+w+w+1 > > which are both *different* according to the == operator, but for the > purposes of numerical accuracy are identical. Since 'W' != 'w' in Python, both give a NameError unless w defined elsewise 8<). However... >>> w=.89/4 >>> w 0.2225 >>> 1+w+w+w+w 1.8899999999999997 >>> w+w+w+w+1 1.8900000000000001 Although w appears to be exactly represented, it must not be. Cute example. Terry J. Reedy From gvdbogae at vub.ac.be Tue Sep 3 06:28:59 2002 From: gvdbogae at vub.ac.be (Geert-Jan Van den Bogaerde) Date: 03 Sep 2002 12:28:59 +0200 Subject: code doesn't work: question In-Reply-To: <1551859543.20020903130305@is.lg.ua> References: <1551859543.20020903130305@is.lg.ua> Message-ID: <1031048940.915.34.camel@gandalf> On Tue, 2002-09-03 at 12:03, Ruslan Spivak wrote: > Hello python-list user, > > I want somebody to explain me why next code doesn't work: > > var = 5 > > if (tmp = var) == 5: # this is the error line > print "ok" > else: > print "error" Python doesn't allow assignment inside expressions, the rationale (from the Python tutorial at http://www.python.org/doc/current/tut/node7.html - section 5.5 last sentence): """ Note that in Python, unlike C, assignment cannot occur inside expressions. C programmers may grumble about this, but it avoids a common class of problems encountered in C programs: typing = in an expression when == was intended. """ Given the number of times I've personally made this mistake, I'd agree with Python's rationale for leaving this out. As to what to use instead: >>> var = tmp = 5 >>> if tmp == 5: >>> print "ok" >>> else: >>> print "error" Best regards, Geert-Jan Van den Bogaerde From richie at entrian.com Fri Sep 13 04:02:11 2002 From: richie at entrian.com (Richie Hindle) Date: 13 Sep 2002 01:02:11 -0700 Subject: "str"(expr)"str" interpolation syntax References: Message-ID: <8a6ba1da.0209130002.37ede06a@posting.google.com> > Maybe something very simple along the lines of: > > subst("A template string - here: % it goes\n", foo, > "Also multiple values: %, %\n", bar, quux, > "Quoting percent (%) sings probably not needed...\n", '%') > > could be useful... Yes it smells like perl formats but the > intelacing of pictures/values is really near optimal IMHO. Guido's time machine strikes again: >>> foo, bar, quux = 1, 2, '3' >>> print ("A template string - here: %s it goes\n" % foo + ... "Also multiple values: %s, %s\n" % ( bar, quux ) + ... "Quoting percent (%s) sings probably not needed...\n" % '%') A template string - here: 1 it goes Also multiple values: 2, 3 Quoting percent (%) sings probably not needed... -- Richie Hindle richie at entrian.com From tg5027 at citlink.net Wed Sep 18 17:35:32 2002 From: tg5027 at citlink.net (terry) Date: Wed, 18 Sep 2002 17:35:32 -0400 Subject: monetary applications (et al) Message-ID: >>>>> Chris wrote: Well, sure. This is obviously a stupid way to go about...That's what object oriented programming is all about. What you need to do is create a currency class that behaves like it should, and then use it everywhere you want currency. >>>>> I do admit to being OO inhibited, so maybe you could take it from this short piece code and execution results, and, provide a brief description of what you would put into this money class that would eliminate this error message, while maintaining the code simplicity. ------------------------------------------------- class money: def __init__(self,name): self.name = name unitprice = money(100) qty = 2 amount = qty * unitprice terry at terry:~> python money.py Traceback (most recent call last): File "money.py", line 7, in ? amount = qty * unitprice TypeError: unsupported operand type(s) for *: 'int' and 'instance' ------------------------------------------------- Support for mixed number types in expressions involving this money class must come from somewhere - where? And, it must be capable of determing and setting amount to be of class money to be consistent with the rest of Python's complexity hierarchy for the handling of numbers. The rest of the problem is that the above is a trivial calculation. What happens to your recommendation when faced with an additional number type? taxrate = 0.06 amount = qty * unitprice + (qty*unitprice)*taxrate As I see it, if Python had an intrinsic number type of 'money', the logic for determing the results of the above calculation would be easily determined and consistent with expectations, as in VB. Thanks for your time, terry From jggramlich at yahoo.com Wed Sep 4 12:23:28 2002 From: jggramlich at yahoo.com (Joshua Gramlich) Date: 4 Sep 2002 09:23:28 -0700 Subject: PyListObject & C Modules References: Message-ID: Thank you for your replies, here is what I have so far: ############################code block############################# #include "Python.h" #include PyObject* get_first_elem(PyObject *unused, PyObject *args) { PyObject *list; PyObject *first; PyObject *result; if(!PyArg_ParseTuple("!0", &list)) return NULL; if(!PyList_Check(list)) { PyErr_SetString(PyExc_TypeError, "get_first_elem expects a list"); return NULL; } if(PyList_Size(list) == 0){ PyErr_SetString(PyExc_ValueError, "empty lists not allowed"); return NULL; } first = PyList_GetItem(list, 0); if (first == NULL) return NULL; result = PyList_New(1); if (!result) return NULL; Py_ADDREF(first); if (PyList_SetItem(result, 0, first) != 0) { Py_DECREF(first); Py_DECREF(result); result = NULL; } return result; } #################################################################### Now, when I compile that, I get: make gcc -I/fnal/ups/prd/python/v2_1/SunOS+5/include/python2.1/ -c slist.c slist.c: In function `get_first_elem': slist.c:10: warning: passing arg 1 of `PyArg_ParseTuple' from incompatible pointer type slist.c:10: warning: passing arg 2 of `PyArg_ParseTuple' from incompatible pointer type gcc -G slist.o -o slist.so [d0ora3 ~/work/grid_query/test]$ python hello.py Traceback (most recent call last): File "hello.py", line 2, in ? import slist ImportError: ld.so.1: python: fatal: relocation error: file ./slist.so: symbol Py_ADDREF: referenced symbol not found [d0ora3 ~/work/grid_query/test]$ Commenting PyADDREF out of the code causes the shared object not to build at all. My hello.py looks like this: import slist stuff = [2, 3, 8, 23] print(slist.get_first_elem(stuff)) From warkid at storm.ru Tue Sep 3 04:53:54 2002 From: warkid at storm.ru (Kerim Borchaev) Date: Tue, 3 Sep 2002 12:53:54 +0400 Subject: Python to surpass C performance by 2030 In-Reply-To: References: Message-ID: <12537.020903@storm.ru> Hello Dan, Tuesday, September 03, 2002, 11:03:14 AM, you wrote: DB> Erno Kuusela wrote in message news:... >> just for fun i ran pystone under python versions since 1.5.2 to >> current cvs. here are the results: >> >> [benchmark results snipped] >> >> since 1.5.2 is about 4 years old, the improvement per year is about >> 13.2% on average. if we assume that 1.5.2 is 50 times slower than >> C (probably conservative?), then at 13.2% per year since 1998 it >> will add up to 53x improvement in 32 years. >> >> i wonder if this would be a good application for the time machine... >> >> learn python today, and in 28 years you will have a job writing >> the speed-critical parts of c programs in python :) DB> Before that could ever happen, the Python interpreter would have to be DB> written in something other than C. Yes. It should be written in Python: http://psyco.sourceforge.net/plans.html Best regards, Kerim mailto:warkid at storm.ru From hancock at anansispaceworks.com Thu Sep 26 16:02:01 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 26 Sep 2002 13:02:01 -0700 Subject: Lambdaizing Python Code Message-ID: <3D9367B9.844BF599@anansispaceworks.com> From: gerson.kurz at t-online.de (Gerson Kurz) > A really usefull study ... NOT. > http://p-nand-q.com/e/quicksort_lambda.html > also known as "making Guido regret he put lambda in THE BEST > PROGRAMMING LANGUAGE IN THE WORLD(TM)". AAAAAUUUUURRRRGGGHHHHH!!!! That was scary. ;-D Paraphrasing "Ghostbusters" -- "Okay, guys, important safety tip: avoid lambda." From: Fernando P?rez > Why not just a simple function? > In [23]: plur=lambda s,n:'%s %s' % (n,s+('','s')[n!=1]) > In [24]: plur('cat',0) > Out[24]: '0 cats' > In [25]: plur('cat',1) > Out[25]: '1 cat' > In [26]: plur('cat',9) > Out[26]: '9 cats' > In [27]: na=1; np=3; nl=1; ng=0 > In [28]: print "Found %s, %s, %s, %s" % (plur('apple',na),plur('plum',np), > ....: plur('lemon',nl),plur('grape',ng)) > Found 1 apple, 3 plums, 1 lemon, 0 grapes > > If the list is big the above can easily be automated with a map or a list > comprehension. Not that I want to sign up for the style police or anything, but ... Would respectfully like to point out that this could as well be represented: def plur(word, number): if number > 1: word = word + 's' return '%d %s' % (number, word) and would, IMHO, be much more obvious in function to the reader. Nothing says you have to use "lambda" just because you might use a map or list comprehension. IMHO, if you need to assign lambda to a variable, you probably want to use a named function anyway. (Basically, it's semantically identical to do so, (I think) -- except that you remove the expression limitation, which makes for more intuitive code. It occurs to me that the plur() function is a very good idea, especially since it is possibly multi-lingual (e.g. in Russian, Swahili, and Japanese the pluralization rules are completely different -- Russian typically inflects with an "i" ending, Swahili uses prefixes (e.g. "mtoto" / "watoto"). Japanese is potentially more challenging, as the word remains unchanged, but the number acquires a counter "empitsu sambon" (and they're normally separated in the sentence (e.g. "empitsu ga sambon aru" = "there are three pencils"). I wonder if there are any other challenge cases to consider, and whether a more general pluralization scheme is possible. PUB (http://py-universe.sourceforge.net) has a problem with this, in that much of the pluralization code is mixed in, and assumes English (or other languages where you can make a plural by adding "s"). Mind you, even in english the plur() function will break down for sheep, tooth, calf, and a host of other exception words. Fun concept. Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From ataylor at ucsd.edu Tue Sep 24 21:36:06 2002 From: ataylor at ucsd.edu (Adam Taylor) Date: Tue, 24 Sep 2002 18:36:06 -0700 Subject: Getting started Message-ID: <3D911306.7080609@ucsd.edu> About this: Alex Martelli wrote: > I'm somewhat surprised at seeing you make such assertions at > obvious variance with type theory -- I thought you had a solid > CS background (stronger than my own -- I'm just an engineer, > more interested in pragmatics than in theory). We _do_ share > the fundamentals, I hope? E.g., my favorite "essential Luca > Cardelli bibliography": > > Cardelli, Wegner, "On understanding types, data abstraction, and > polymorphism", ACM Computing Surveys 1985 > > Cardelli, "Type Systems", in "Handbook of Computer Science and > Engineering", CRC Press, 1997. This last is available at: http://research.microsoft.com/Users/luca/Papers/TypeSystems.pdf It says, in part: A program variable can assume a range of values during the execution of a program. An upper bound of such a range is called a type of the variable. For example, a variable x of type Boolean is supposed to assume only boolean values during every run of a program. If x has type Boolean, then the boolean expression not(x) has a sensible meaning in every run of the program. Languages where variables can be given (nontrivial) types are called typed languages. Languages that do not restrict the range of variables are called untyped languages: they do not have types or, equivalently, have a single universal type that contains all values. In these languages, operations may be applied to inappropriate arguments: the result may be a fixed arbitrary value, a fault, an exception, or an unspecified effect. The pure \lambda-calculus (see Chapter 139) is an extreme case of an untyped language where no fault ever occurs: the only operation is function application and, since all values are functions that operation never fails. Based on this definition, it seems to me that Python _is_ untyped, since the type of a variable can change arbitrarily in mid-program. He later discusses the distinction between safety and typed-ness, and shows this table: Typed Untyped Safe ML LISP Unsafe C Assembler Python is safe (at least pure Python, I think), so it should go in the same square as Lisp, correct? Cardelli doesn't use the term "weakly typed" himself, but on page 5 he seems to be say that "weakly typed" is the commonly used term for what he calls "weakly checked". C is weakly checked, in his terminology, and that's why it's unsafe. But people on this thread seem to be using "weakly typed" to mean roughly the same thing as Cardelli's "untyped". Which is fine, and pretty close to Cardelli's terminology. But clearly the terms "untyped" (=="weakly typed" on this thread) and "weakly checked" (=="weakly typed" in common usage) are very different things. Adam -- Adam Taylor ataylor at ucsd.edu 858-534-4763 From chris.gonnerman at newcenturycomputers.net Thu Sep 26 01:10:31 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Thu, 26 Sep 2002 00:10:31 -0500 Subject: Tabs vs. Spaces, VIM vs. EMACS (Was Re: Larry Wall's comment on python...) References: <3D9266B0.7090906@cascade-sys.com> Message-ID: <006101c2651b$0df0c340$0101010a@local> ----- Original Message ----- From: "James J. Besemer" > I myself still prefer tabs as I find "indenting" and "out > denting" sections of code to be a common operation (in Python > and in other languages). Inserting or removing an "if" or > changing inline code to a function makes indenting and out > denting a common operation. In the environments I use, this > works well with tabs and not so well or at all with spaces. At the risk of starting another sort of flamewar, I'll weigh in here. I am a user of VIM, and with the "smartindent" and "expandtab" options activated, spaces are just as convenient as tabs... I use the tab *key* to get my four-character indents, and can backspace to cancel an indent (i.e. "outdent"). No actual tab characters ever get saved that way. When I receive code that contains tabs, I use a global replacement to quickly detab any module I need to modify. Surely emacs can do as well as VIM... (and I expect a rabid emacs user to fill me in posthaste). Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From g_will at cyberus.ca Mon Sep 23 21:09:31 2002 From: g_will at cyberus.ca (Gordon Williams) Date: Mon, 23 Sep 2002 21:09:31 -0400 Subject: httplib 'getaddrinfo failed' Message-ID: <001401c26367$09dd13e0$9504e640@wnt20337> Hi All, It must have been something that I was doing before, though I tried multiple times. Now it is working properly. Thanks, Gordon Williams ----- Original Message ----- From: "Gordon Williams" To: Sent: Friday, September 20, 2002 1:50 PM Subject: httplib 'getaddrinfo failed' > Hi All, > > I recently got a DSL line to connect to the internet and my code is now > broken. Could this be due to the DSL being different from a dialup > connection? > From markus.vonehr at ipm.fhg.de Thu Sep 5 02:54:44 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Thu, 05 Sep 2002 08:54:44 +0200 Subject: tk8.4 in python22 ? Message-ID: <3D76FFB4.FE5EF48A@ipm.fhg.de> Hi, I'd like to use tk8.4 with python22, in fact the windows installer installs tk8.3. How can I replace tk8.3 to 8.4? Do I have to compile any python files? Thanks for any hints, Markus From davbucko at deletethis.yahoo.com Mon Sep 2 04:21:07 2002 From: davbucko at deletethis.yahoo.com (davbucko) Date: Mon, 2 Sep 2002 09:21:07 +0100 Subject: Keyerror problem References: <_lyc9.7164$7N.29584@newsfep3-gui.server.ntli.net> Message-ID: <0cFc9.1718$yB6.25319@newsfep1-gui.server.ntli.net> Thanks! I wasn't too sure about what the backticks meant, but I thought that they might be necessary. Oh well Dave "Gerhard H?ring" wrote in message news:slrnan5f2o.4s9.gerhard.haering at lilith.my-fqdn.de... > davbucko wrote in comp.lang.python: > > I have a class Flags as follows: > > > > class Flags: > > def __init__(self): > > self.flags = {} > > > > def getInverseFlags(self): > > for i in self.flags.keys(): > > #switch some keys/values around > > > > def setFlag(self,name,value): > > self.flags[`name`] = value > ^^^^^^ > > Here's the bug. It should read: self.flags[name] = value. > > `name` calls repr on name, which is most likely not what you want. > > Btw. if you want to invert a dictionary, there are probably hundreds > of examples out there, here's a hopefully readable one: > > def invertdict(orig): > new = {} > for k, v in orig.items(): > new[v] = k > return new > > Gerhard > -- > mail: gerhard bigfoot de registered Linux user #64239 > web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 > public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 > reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From scotty at yang.id.au Thu Sep 26 20:29:09 2002 From: scotty at yang.id.au (Scott Yang) Date: Fri, 27 Sep 2002 00:29:09 GMT Subject: Copying Elements using PyXML References: Message-ID: Assuming you want to have the result DOM as ... You should be able to do it easily using PyXML. # Parse the XML document into DOM objects. from xml.dom.ext.reader.PyExpat import Reader person = Reader().fromString(doc1) xformimport = Reader().fromString(doc2) # Clone person's document node. person_cloned = person.cloneNode(1, xformimport) # Append cloned node to xformimport's child nodes. xformimport.documentElement.appendChild(person_cloned) In article , Jeremy Rew wrote: > I have 2 XML documents. I would like to copy the entire structure of one > document into a child element of the other, but i cannot copy the root node > across: > I get the following error from Zope: > Error Type: HierarchyRequestErr > Error Value: Node manipulation results in invalid parent/child relationship. > > the structures are as follows: > > > >
> > > > and would like to copy this into the following format: > > > > > > >
> > > > > > I have written all the code to build 'xformimport','docID' and 'document', > but just need to copy 'person' across. > I figure i may be missing an easy solution here, so any help/ideas will be > appreciated. > I am using PyXML 0.8.1 and python 2.1.3. > > thanks > Jeremy > > -- Scott Yang :: scotty at yang.id.au :: http://scott.yang.id.au/ :: PGP:0xF9DCFA8C From bokr at oz.net Thu Sep 5 16:04:08 2002 From: bokr at oz.net (Bengt Richter) Date: 5 Sep 2002 20:04:08 GMT Subject: Gratitude due to Red Hat? More work for the PBF? References: Message-ID: On 05 Sep 2002 11:28:14 -0700, Cliff Wells wrote: [...] > >The aggravating thing is that this issue would be a snap for RedHat to >fix. Instead of preempting /usr/bin/python for their own use, they >could maintain a /usr/bin/python-rh and leave python for user-installed >versions (instead of requiring the user version to be called "python2"). > >Problem solved, everyone happy. > So why don't they do this? Do they need help? Regards, Bengt Richter From loewis at informatik.hu-berlin.de Mon Sep 2 09:42:55 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 02 Sep 2002 15:42:55 +0200 Subject: Does IDLE handle unicode? References: Message-ID: "Edward K. Ream" writes: > IDLE took an exception writing a .py file containing the copyright > character. This happened a while ago; IIRC, I lost the file. > > Is this a known problem? I see nothing about this in the FAQ. It will be fixed in Python 2.3. Regards, Martin From mbonig at hotmail.com Sat Sep 14 04:28:53 2002 From: mbonig at hotmail.com (Matthew Bonig) Date: Sat, 14 Sep 2002 08:28:53 GMT Subject: Tkinter listbox clicking problem References: <2D7E3697CF5D1521.5D9711540E657ED8.7EF0451C598438FC@lp.airnews.net> Message-ID: <9rCg9.262546$kp.888557@rwcrnsc52.ops.asp.att.net> I'm confused... I looked at these examples but I didn't see anything pop out that answered my question... or was this mostly for the other post? Thanks Matthew Bonig "Cameron Laird" wrote in message news:2D7E3697CF5D1521.5D9711540E657ED8.7EF0451C598438FC at lp.airnews.net... > In article , > Russell E. Owen wrote: > >In article , > > "Matthew Bonig" wrote: > > > >>Right now I have it bound so when a Tkinter listbox gets a > >>(lb.bind("", someFunc)) it calls function someFunc. Now, > >>someFunc() simply prints the curselection(). The problem is it's lagged... > >>if I first select list item 1 (index 0), and then 2, and then 3 (array > >>indexes 0,1,2) it prints out themout incorrectly. > >>(I have someFunc actually do some try, except stuff so I don't get uncaught > >>exceptions) Instead of printing 0,1,2 it prints "nothing selected", 0, 1. > >>The function get's called before the listbox updates it's selection markers! > >> > >>Does anybody know how I could force listbox to update it's selection markers > >>so instead of printing "nothing selected, 0,1 it prints 0,1,2 like it > >>should? > > > >I'm hoping somebody has better ideas, but here are some to try: > > > >Call update_idletasks before you ask for the selection. I have no idea > >if this will work, but it might. > > > >An ugly solution that would probably work: > >- extract the y coordinate from the event callback > >- call nearest(y_coord) to get the item closest to the mouse click > >- explicitly select that index item. You could try skipping this step, > >but you risk a possible error between what you think they clicked on and > >what is hightlighted. Unfortunately, this step will may be a real pain > >for a list that supports multiple selected items. > > > >Poll for selection changes -- thus it may take a bit of time before your > >code notices a change, but it will always be right once it gets there. > > > >-- Russell > > Whoa! There's a far easier solution. Read up on 'bindtags' > in and elsewhere. > has a small > example that almost is pertinent. > -- > > Cameron Laird > Business: http://www.Phaseit.net > Personal: http://phaseit.net/claird/home.html From aleax at aleax.it Fri Sep 27 04:07:24 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 27 Sep 2002 08:07:24 GMT Subject: comparing all values of a list to regex References: Message-ID: <0lUk9.149240$ub2.3291527@news1.tin.it> Manuel Hendel wrote: ... > This is the input, it is "|" seperated textfile with about 15000 lines > of pop3 accounts: > |Number|String|Number|String(Domain)|String(Account)|String(Login/Email)|String(Password)|String|String| > > These are the fields I care about. > > String(Domain): This is the domain of the Account > String(Account): This is the part in front of the @doamin. This can > also be a * for a catchall account. > String(Login/Email): This is the local pop3-account or a emailaddress, > or both, comma seperated. > String(Password): This is the password if String(Login/Email) is a > pop3-account. > > This should be the output: > > Three text files. One with only forwardings (only emailaddresses in > the String(Login/Email). One with only pop3-accounts in the > String(Login/Email), and one mixed, where String(Login/Email) has > pop3-accounts and emailaddresses. OK, for each line you want fields line.split('|')[4:8], each field space-stripped (at least, you strip them in the code you posted, though that's not in the specs you give above), _plus_ you need to know the set of domains (uniquely) and classify per field 4 (domain) -- you build this in the code you posted, althogh, again, I can't see any trace of that requirement in the specs. So we'll want an auxiliary function to tell us which of the three "bins" to put an entry to depending on the login/email field, e.g.: def classify(login_email): l_e = login_email.split(',') assert 1 <= len(l_e) <= 2, "More than one comma in (%s)" % login_email if len(l_e)==2: return 2 # both elif l_e.find('@'): return 1 # email, I guess else return 0 # other case (local account, I guess) Now the rest, net of imports and file open/close ops: classified = [ [] for i in range(3) ] # 3 separate empty lists per_domanin = {} # initially-empty dict for line in inputfile: fields = [ field.split() for field in line.split('|')[4:8] ] per_domain.setdefault(fields[0],[]).append(fields) classified[classify(field[2])].append(fields) Now you only need the output -- presumaby each line must be output in the same way, e.g. with another auxiliary function: def outline(fileobj, fields): fileobj.write('|'.join(fields)) fileobj.write('\n') so you only need to loop on each of the three lists of lists in 'classified', and on the keys of dictionary 'per_domain' (sort them too, if you wish, of course), in order to emit the results to appropriate files. Presumably your exact specs are not quite as I tried to guess them from a mix of what you wrote and what you coded, but I hope this outline can still be useful to you. Alex From Oschler at earthlink.net Sun Sep 1 17:19:36 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 1 Sep 2002 17:19:36 -0400 Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: "Gerhard H?ring" wrote in message news:slrnan4dl3.18h.gerhard.haering at lilith.my-fqdn.de... > >>> class Foo: pass > ... > >>> foo = Foo() > >>> foo.bar() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: Foo instance has no attribute 'bar' > >>> def bar(self): print "bar" > ... > >>> Foo.bar = bar > >>> foo.bar() > bar Ok bear with me guys (Gerhard and Peter). I'm not lazy, the reason I don't test certain things I should is because Python is capable of such amazing introspective dynamism that, having a _very_ long experience bank in strongly typed "static" languages like C++ and Pascal, I find I don't even consider yet even trying certain possibilies that Python is capable of. Some interesting tidbits I found while trying out your suggestions, as you will see in the two ".py" files that follow, I discovered that to create a method you can dynamically add to a class _instance_, you need to omit the 'self' parameter in the method declaration. For a method you add dynamically to a class definition itself, then you must include the 'self' parameter in the method declaration. If not, you will get an argument count mismatch complaint from the interpreter. Fascinating stuff. I'm running 2.1.1, anybody know if 2.2.2 is going "disable" either of these abilities? (class or class instance dynamic method addition). I saw a note about such activities requiring a "dynamic" keyword, which is fine. I'd really miss either of these abilities. Code follows below, Thanks again. ------------------------------------------------------------- // The test program, test_main.py. import test1 a = test1.Account("Guido", 1000) a.MethodToAdd = test1.MethodToAddToInstance a.MethodToAdd() test1.Account.MethodToAdd = test1.MethodToAddToClass c = test1.Account("Fred", 2000) c.MethodToAdd() // The module test1.py. class Account: "A simple class" account_type = "basic" def __init__(self, name, balance): "Initialize a new account balance" self.name = name self.balance = balance def deposit(self, amt): "Add to the balance" self.balance = self.balance + amt def withdraw(self, amt): "Subtract from the balance" self.balance = self.balance - amt def inquiry(self): "Return the current balance" return self.balance def AddAttr(Acct): Acct.number = 7 def MethodToAddToInstance(): "I want to add this method dynamically to an instance of a class." return 10 def MethodToAddToClass(self): "I want to add this method dynamically to a class." return 11 From emile at fenx.com Thu Sep 26 19:33:40 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 26 Sep 2002 16:33:40 -0700 Subject: Who knows somefunction? References: Message-ID: gus: > I haven't compiled it yet; what happens > when you don't "del x" before you declare x1? Python 2.3a0 (#29, Sep 26 2002, 16:04:25) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from pointer import pointer >>> x = range(3) >>> y = id(x) >>> x1 = pointer(y) >>> x1 [0, 1, 2] >>> del x >>> x1 [0, 1, 2] >>> del x1 >>> x1 = pointer(y) >>> x1 [0, 1, 2] >>> Anybody know anything you can do with a hunk of rope? ;-) -- Emile van Sebille emile at fenx.com --------- From mnations at airmail.net Fri Sep 20 11:49:31 2002 From: mnations at airmail.net (Marc) Date: 20 Sep 2002 08:49:31 -0700 Subject: Strange Telnet error References: <4378fa6f.0209181245.7b06124d@posting.google.com> Message-ID: <4378fa6f.0209200749.1b873c4e@posting.google.com> > Your code is multithreaded. Could another thread have closed the socket on > you? Yeah, the timing was off between one thread and another queue which was closing it prematurely (DOH!) Next time I will know that the "...sendall socket..." implies a socket that has already been closed. An error that says something about trying to use a closed socket would have been helpful, but when I first read the error it sounded like I was sending bad or corrupt information or something. Thanks for the help, Marc From gerhard.haering at gmx.de Thu Sep 26 20:53:51 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 27 Sep 2002 00:53:51 GMT Subject: POP3 and Multipart Mime References: Message-ID: David McInnis wrote in comp.lang.python: > I need to log into a POP3 account (which I have been able to do using > poplib). > > I need to be able to read and decode the message. The problem is that > most of our users send word docs as attachments (1 or more). I need to > take these files and save them to disk. Check out the email module in Python 2.2 and later. -- Gerhard From anton at vredegoor.doge.nl Fri Sep 20 21:00:31 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sat, 21 Sep 2002 03:00:31 +0200 Subject: average? References: Message-ID: On Fri, 20 Sep 2002 15:10:47 -0400, Carl Banks wrote: >Mark McEahern wrote: >> def average(seq): >> return reduce(operator.add(seq) / len(seq)) >> 1. Is there anything else dumb about the above? > >Well, yes; it seems to me you meant this: > > def average(seq): > return reduce(operator.add,seq)/len(seq) >> 2. Am I missing a builtin cousin of min, max that would do this for me? > >In pure Python, I don't think so. I would be surprised if the above >function (when typed correctly) isn't the fastest way in pure Python. Just a few more posters and we will get this function right, I am sure ... >>> import operator >>> def average(seq): return reduce(operator.add,seq)/len(seq) >>> average([1,2,3,4]) 2 >>> def average(seq): return reduce(operator.add,seq)/float(len(seq)) >>> average([1,2,3,4]) 2.5 >>> Anton. From david at no.westcontrol.spam.com Wed Sep 18 10:23:25 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Wed, 18 Sep 2002 16:23:25 +0200 Subject: BibTeX module? References: Message-ID: "Matthias Huening" wrote in message news:Xns928D9F1FBAA22mhueningzedatfuberli at 130.133.1.4... > Hi, > > I am looking for a simple BibTeX module, allowing me to read and > manipulate/convert a bibliography file. > > Thanks, Matthias Are you sure you are posting to the right newsgroup here? comp.text.tex might be a better bet, unless by chance someone has written a BibTeX module in Python - unlikely, since most TeX related programs are written in C, Pascal or perl. From diltonm at pacbell.net Sun Sep 1 18:58:21 2002 From: diltonm at pacbell.net (Dilton McGowan II) Date: Sun, 01 Sep 2002 22:58:21 GMT Subject: urllib bug? References: Message-ID: "Steve Clift" wrote in message news:mailman.1030848662.20745.python-list at python.org... > > Is this *really* a urllib bug, or am I missing something blindingly obvious? > > Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > IDLE 0.8 -- press F1 for help > >>> import urllib > >>> f = urllib.urlopen('http://www.python.org') > Traceback (most recent call last): > File "", line 1, in ? > urllib.urlopen('http://www.python.org') > File "C:\PROGRAM FILES\PYTHON22\lib\urllib.py", line 73, in urlopen > return _urlopener.open(url) > File "C:\PROGRAM FILES\PYTHON22\lib\urllib.py", line 178, in open > return getattr(self, name)(url) > File "C:\PROGRAM FILES\PYTHON22\lib\urllib.py", line 276, in open_http > if not host: raise IOError, ('http error', 'no host given') > IOError: [Errno http error] no host given > > Fails the same way with 2.1. Works OK with 1.5.2 and (IIRC) 2.0. > > -Steve > Works on Windows 2000 using Idle, PythonWin and Cygwin Python all version 2.2. From claird at starbase.neosoft.com Fri Sep 13 08:58:37 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 13 Sep 2002 07:58:37 -0500 Subject: concurrent programming References: Message-ID: In article , Chris wrote: >Hi! > >I have a problem in my project I startet a few weeks ago. The >requirement is to program a Task Scheduler who gets a Python script >with the tasks spezified. So I have to write some extensions in C++ >which provide the functionality. So far so good, now comes the >problem. It should be possible to write something like: > >PARBEGIN > if .... > exeute some shell scripts on distributed computers > some method calls from the extension module, e.g. write in a >database > do something else > while ... > ... >PAREND > > >This means that the code bracketed in PARBEGIN PAREND should be >executed parallel. The contrary would be SEQBEGIN SEQEND for >sequential execution. > >The Task Scheduler is for testing some programs, so the scripts should >be easy to write and not too complicated. My idea would be to handle >this with a call of a function from the extension module which gets a >function pointer to a method with the code inside PARBEGIN PAREND as a >parameter, so that I can do a callback from the C++ module e.g.: > >def f(): > if .... > exeute some shell scripts on distributed computers > some method calls from the extension module, e.g. write in a >database > do something else > while ... > ... > >exec_par(f()) > > >But how can this be executed concurrent? Is there another possibility >in Python? > >thx There are several possibilities for styling concurrent processing in Python. Why are we talking about C++, though? Would a pure-Python solution not meet your requirements? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From tim.one at comcast.net Mon Sep 16 12:18:33 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 16 Sep 2002 12:18:33 -0400 Subject: Are generator functions thread-safe? In-Reply-To: Message-ID: [David Eppstein] > Also, if a call to the generator object is running from one thread, you > will get an exception if you attempt to simultaneously call it (e.g. > from another thread). I don't know how thread-safe is the code that > prevents the generator from being called twice simultaneously, though. A generator-iterator has an internal "am I currently running?" flag that's inspected and mutated under protection of the GIL, so it's thread-safe. The flag is exposed as the gi_running attribute of a generator-iterator object, although I haven't found a use for that yet : >>> def g(): ... print i.gi_running ... yield 42 ... >>> i = g() >>> i.gi_running 0 >>> x = i.next() 1 >>> x 42 >>> i.next() Traceback (most recent call last): File "", line 1, in ? StopIteration >>> From loewis at informatik.hu-berlin.de Wed Sep 11 16:30:04 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 11 Sep 2002 22:30:04 +0200 Subject: Global Interpreter Lock References: <3822aca1.0209111211.8a1538f@posting.google.com> Message-ID: codic at stasis.org (Ian Crawford) writes: > I'm working on a project with an embedded Python > interpreter which I'd like to be capable of parallel > execution on a multi-processor machine. I'm still > trying to figure out one thing in particular. Is > there a global interpreter lock per interpreter (i.e. > if I call Py_NewInterpreter, does that interpreter > have it's own lock), or will I have to embed seperate > interpreters in their own processes to have parallel > execution? The latter: even if you have multiple interpreter objects, the Python runtime still needs to protected with a single lock. Notice that you can have multiprocessor parallelism in Python if the threads invoke long-running C code: if the extension module releases the interpreter lock before the compute-intensive C code starts, this computation can be performed on a separate processor. Regards, Martin From KBASS1 at nc.rr.com Thu Sep 12 06:04:37 2002 From: KBASS1 at nc.rr.com (Kevin Bass) Date: Thu, 12 Sep 2002 10:04:37 GMT Subject: Newby Question: os.rename References: Message-ID: "Dean Goodmanson" wrote in message news:e81be8b2.0209082039.67f33ab4 at posting.google.com... > > > > > > "Kevin Bass" wrote in message > > > news:AcGc9.68214$Xa.3523883 at twister.southeast.rr.com... > ... > > > > > > I have figured it out. Thanks! > > > > > > > > > > > "CotaBas" wrote in message news:... > > > > > LOL if you wait long enough people solve there own problems.... > > If you're skimming or Google'ing for a similar problem...you'll find > the problem listed 3 times and no answer in the follow-up! Good point!! Let me place the solution to my problem. :) Here is the code that I used to solve this problem. I basically (1) give the program the directory that I wanted to create the archived directoy off of, (2) created a timestamp within a variable, (3) joined the directory with the timestamp to form a new varaible housing the new directory, (4) created the new directory with timestamp, (5) use glob to get a list of files, (6) separated the directory name from the files names and placed them into varaibles, (7) joined the new directory to the files that I glob'd, (8) then rename the files which placed the files from one directory to another directory. I know that you probably did not want to know all of this but walking through the steps helps me to undetsand any problems that I may encounter. Like I just noticed that I have to place a try clause in the function so that if the newly created directory is already there (the program was executed more than once) then the program should not attempt to create the directory again. Or I should check to see if the directory if already present before attempting to create the directory. def archive_data(archive): if archive == 'yes': datadir = '/home/oracle/data/' if os.path.isdir(datadir): the_date = strftime("%Y%m%d") archdir = os.path.join(datadir, the_date) os.mkdir(archdir) # Retrieve IBSS data from a previous inventory and archive it. for file in glob.glob('/home/oracle/data/*.XP'): dir, filename = os.path.split(file) oldfile = os.path.join(datadir, filename) newfile = os.path.join(archdir, filename) try: os.rename(oldfile, newfile) except: print "*** Unable to rename %s" %oldfile # Retrieve manual data from a previous inventory and archive it. for file in glob.glob('/home/oracle/data/*.csv'): dir, filename = os.path.split(file) oldfile = os.path.join(datadir, filename) newfile = os.path.join(archdir, filename) try: os.rename(oldfile, newfile) except: print "*** Unable to rename %s" %oldfile else: pass From ajs at ix.netcom.com Mon Sep 16 18:55:28 2002 From: ajs at ix.netcom.com (Arthur) Date: Mon, 16 Sep 2002 18:55:28 -0400 Subject: Not sure how to phrase this question Message-ID: <000501c25dd4$38711460$9865fea9@arthur> Hoping I can get some help digesting the following behavior. ************************************ class returnClassic(object): def __new__(self): return Classic() class callClassic(object): def __new__(self): Classic() class returnNewStyle(object): def __new__(self): return NewStyle() class callNewStyle(object): def __new__(self): NewStyle() class returnNewStyle(object): def __new__(self): return NewStyle() class Classic: def __init__(self): print "Classic class init" class NewStyle(object): def __init__(self): print "NewStyle class init" if __name__ == "__main__": print "call to callClassic()" cc=callClassic() print cc.__class__ print "*************" print "call to returnClassic()" rc=returnClassic() print rc.__class__ print "*************" print "call to callNewStyle()" cns=callNewStyle() print cns.__class__ print "*************" print "call to returnNewStyle()" rns=returnNewStyle() print rns.__class__ Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> call to callClassic() Classic class init ************* call to returnClassic() Classic class init __main__.Classic ************* call to callNewStyle() NewStyle class init ************* call to returnNewStyle() NewStyle class init NewStyle class init Message-ID: Buckshot wrote: > Can anyone here explain why I'm getting different results from > e**2 and exp(2)? Which is more accurate? > > Python 2.2 (#1, Mar 27 2002, 14:56:58) > [GCC 2.95.3 20010315 (release)] on sunos5 > Type "help", "copyright", "credits" or "license" for more information. >>>> from math import * >>>> e**2 > 7.3890560989306522 >>>> exp(2) > 7.3890560989306504 As someone already told you, exp(2) gives a more accurate answer. The reason is, I think, the following: e**2 simply squares e, and this amplifies the error in the value for e (which is stored at finite precision, as a C double inside). OTOH, exp(2) computes e**2 to a given accuracy, so it will not be propagating the finite-precision error inherent in the 'e' value. As long as the exp() function is correctly implemented in the system's math library, it should be more accurate than hand-calculations done with 'e'. In most cases the difference shouldn't matter, but if you are doing something very sensitive to numerical roundoff or require delicately balancing cancellations, you may need to pay attention to this. Cheers, f. From sholden at holdenweb.com Sun Sep 29 06:29:02 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 29 Sep 2002 06:29:02 -0400 Subject: List/Tuple bug or feature? References: <8765wv6o0d.fsf@nospam.eml.cc> Message-ID: <4DAl9.4938$pD4.1871@fe05> "Mahesh Padmanabhan" wrote ... > > Hi, > > I spent a lot of frustrating hours tracking this down and I am > confused as to why I see this behavior. > > >>> x = ('a' 'b') > >>> x > 'ab' > The two adjacent string constants are concatenated. You don't get a tuple because there is no comma folowing the singleton element, so technically the RHS in the assignment is simply a parenthesised expression. > >>> x = ['a' 'b'] > >>> x > ['ab'] > Here no commas are needed because there is no ambiguity. Again, the strings are concatenated by Python. This allows you to more easily specify strings in chunks. > As you might have guessed, I missed a comma between two elements in > a fairly large list. > > If this is a concatenation feature, how can I prevent something like > this happening in the future ? > Don't miss out the commas! It *is* a feature, and it *will* bite you if you use incorrect syntax. > This is with Python 2.1.3 on Debian Linux. > But is valid for everything since 1.5.2 in all known implementations, I would guess. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From markus.vonehr at ipm.fhg.de Tue Sep 10 06:00:48 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 10 Sep 2002 12:00:48 +0200 Subject: compile error on SWIG file References: <3D7C55EE.D9278B1C@ipm.fhg.de> <3D7D97A6.A63610AF@ipm.fhg.de> Message-ID: <3D7DC2D0.8D74E062@ipm.fhg.de> Hi, I succeeded, in the SWIG generated file there's a line: #define SWIG_init init_mvelib I changed it to: #define SWIG_init initmvelib Now it's linked succesfully. Haven't tried it yet, let's see if it works... Markus Markus von Ehr schrieb: > > Hi Lyle, > > thanks for your answer and your efforts! > I changed everything to .cpp > The first error has gone > Now I have an error (translated from german): > > mvelib.obj: error LNK2001: unresolved external symbol initmvelib > build\temp.win32-2.1\Release\mvelib.lib : fatal error LNK1120: 1 > unresolved reference > LINK : fatal error LNK1141: Creation error of export file > error: command 'c:\Programme\VC98\BIN\link.exe' failed with exit status > 1141 > > Markus > > Markus von Ehr schrieb: > > > > Hi, > > > > compiling my c-file generated from SWIG > > (swig -c -python -o mvelib.c mvelib.i) > > with a setup-file, I receive the error: > > > > c:\programme\vc98\include\eh.h(32) : fatal error C1189: #Error: "eh.h > > is only for C++!" > > > > Anybody knows what I have to change??? > > > > Thanks Markus > > > > **************************** > > setup.py > > **************************** > > from distutils.core import setup, Extension > > > > setup (name = "mvelib", > > version = "1.0", > > maintainer = "Markus von Ehr", > > maintainer_email = "markus.vonehr at ipm.fhg.de", > > description = "mvelib Python module", > > > > ext_modules = [Extension('mvelib',sources=['mvelib.c'])] > > ) From emile at fenx.com Sun Sep 8 14:35:32 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 8 Sep 2002 11:35:32 -0700 Subject: transform a list of lists in a lit of strtings??? References: <-1588066870.1031507786228.JavaMail.nobody@webmail2.brturbo.com> Message-ID: > I have a list of lists like this: > > labels=[['D1'], ['D2'], ['D3']] > > and i want to transform ia a list of strings > > labels2==[ 'D1' , 'D2' , 'D3' ] <<<<<<<----------- how i can get it???? > You'll want a flatten function. Look into these threads: http://groups.google.com/groups?as_q=flatten&as_ugroup=comp.lang.python -- Emile van Sebille emile at fenx.com --------- From ark at research.att.com Wed Sep 25 11:43:15 2002 From: ark at research.att.com (Andrew Koenig) Date: Wed, 25 Sep 2002 15:43:15 GMT Subject: Newbie References Question -> Exemple References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> <3d91d2cf$0$1484$79c14f64@nan-newsreader-01.noos.net> Message-ID: Guy> But now, if I change the coordinate of one point: Guy> p[0] = [5,5] Guy> I will have: >>>> p Guy> [[5, 5], [0, 1], [1, 1], [1, 0]] Guy> but: >>>> quad Guy> [[0, 0], [0, 1], [1, 1], [1, 0]] That is because you are not changing the coordinates of the point; you are causing p[0]--the 0th element of p--to refer to a completely new point. If you wanted to change the coordinates of the point, you should have written this: p[0][0] = 5 p[0][1] = 5 or, more succinctly: p[0][:] = [5, 5] If you try this, I think you will get the behavior you want. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From jdavis at empires.org Tue Sep 24 05:56:20 2002 From: jdavis at empires.org (Jeff Davis) Date: Tue, 24 Sep 2002 09:56:20 GMT Subject: Strange values in Accept-Language header? References: Message-ID: <8FWj9.39597$V7.10466682@twister.socal.rr.com> > > Accept-Language: en-us,x-ns1rDGeT4e2FpA,x-ns2f67971hgDw1 > Accept-Language: x-ns13V8cN8S1Xz9,x-ns2T329gfxKa7d > > I have no idea what these could mean (I've changed the actual values > BTW, on the remote off-chance that somebody's highly personal > information was coded in there) If I had highly personal information, I probably wouldn't send it out with all of my HTTP requests ;-) > > > D: Some form of cracking attempt involving a buffer-overrun > vulnerability? > That seems the most likely of your suggestions. I really don't know what those extra characters mean. Do you think it might have to do with some related preference like fonts or the screen or something? Perhaps if you posted the secret info someone else might notice something. Regards, Jeff From imbosol at vt.edu Wed Sep 25 14:28:45 2002 From: imbosol at vt.edu (Carl Banks) Date: Wed, 25 Sep 2002 14:28:45 -0400 Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> <96zj9.150553$pX1.5399868@news2.tin.it> <3D911CFA.4060405@something.invalid> Message-ID: Alex Martelli wrote: > Greg Ewing wrote: >> >> I agree there are good reasons to prefer spaces-only >> for code that will be transmitted or displayed by >> dumb software. > > To put it differently: use tabs only if you ARE willing to > bet a very substantial amount that the source file in question > will NEVER be transmitted, displayed, nor otherwise processed > in any way, shape, or form, by software you consider "dumb" > (take it up with KDE KNode's maintainers whether their news > reader is "dumb"... I like it, though it doesn't show tabs:-). Dumb? I would call it broken. -- CARL BANKS http://www.aerojockey.com From quatrelle at gmx.ch Sat Sep 7 19:09:52 2002 From: quatrelle at gmx.ch (Colin Thefleau) Date: Sun, 08 Sep 2002 01:09:52 +0200 Subject: serve_forever() and non-blocking connection Message-ID: Hi I have a problem programing a small proxy with non-blocking sockets. I guess asyncore would be better, but I have no idea how to implement it and the application is runing now (just too slow). So I would like to use threads. First here a small example of what I use for the connection (inside a function): http_proxy = HTTPServer(configuration.listen, RequestHandler) http_proxy.serve_forever() Now this serve_forever() process one request at a time. Ok this is working but too slow. I tried to to use handle_request() instead of serve_forever() in a while loop and put some thread.start_new_thread(http_proxy.handle_request, ()) in there. But this looks too dirty and apparently does not help much. So here my newbee question: what would be the (better) right approach to be able so serve many connections at the same time? Knowing that each process can be quite CPU hungry. Any advice is greatly aprecieted Thanks Colin From peter at engcorp.com Thu Sep 19 19:30:44 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 19 Sep 2002 19:30:44 -0400 Subject: Nokia 3310 SMS Application, done:connecting to serial port(linux/win), done:reading some hex like \x00 . . ., problem:write/send command! noresponse References: <52facf1d.0209190533.3048e62c@posting.google.com> Message-ID: <3d8a5e19@news.sentex.net> Terry Reedy wrote: > "Polerio Babao Jr.II" wrote in message > news:52facf1d.0209190533.3048e62c at posting.google.com... > >>Greetings: Python Masters >> >>I wanted to create an SMS application using Nokia 3310 with >>DAU-9P(data cable), > > > >>When I connect to the port for the first time I get the ser.read() >>output like this \x00\x0c I think. But that's two response is what I >>get on my first connect. After that when I envoke ser.read() again, > > I > >>get nothing. > > > > I know nothing about Nokia but have had experience (and battle scars) > programming serial i/o. Two suggestions. > > First: make *sure* you have serial protocol set right -- baud rate, > data bits, stop bits, parity, handshaking? Also make sure you have > proper pins active and properly connected. It is easy to be off. > > Second: if you do not have one, get a breakout box that lets you see > activity at the port. Its the equivalent of having a > volt-ohm-ammeter. You plug cable into box and run another cable from > box to port. A simple one just has lights that flash when a signal > passes thru. More complicated one allows some signal patching. I got > mine long ago from Inmac. Would check google for source now. Third: almost anything you can do from Python you could do using something like Hyperterminal (ugh) under Windows, or miniterm under Linux. If you can't get it working that way, you're probably dealing with a non-Python issue. If you *can*, then duplicating the configuration carefully as Terry advises above in "First:" will almost certainly leading to better results. -Peter From spendius at muchomail.com Tue Sep 3 04:09:33 2002 From: spendius at muchomail.com (Spendius) Date: 3 Sep 2002 01:09:33 -0700 Subject: Newbie's unsurmountable pb with IO stream trick References: <3D738EE2.3A8756D@engcorp.com> Message-ID: Peter Hansen wrote in message... OK I forgot to say I'm trying to develop my stuff under Windoze. > at once here. For one thing, why are you trying to use > global variables at all when the original code was in > Java, which doesn't have such things? Do you mean Java doesn't have global variables or I'm mistaken ?!? > And what does not declaring variables have to do with > the "global keyword issue" (whatever that is)? I kept getting the error message # UnboundLocalError: local variable 'cpt' referenced before assignment where I really didn't expect to get such an error, and noticed in this forum a lot of guys who know Python complain and talk themselves about a "mess" (my 'cpt' var. is a counter incremented every time a method gets called and I must sometimes re-initialize it to 0 inside an 'if' statement: merely IMPOSSIBLE). > If you have an SQL database to access, why not use one of the > standard DBAPI modules to get to it? You might be doing a lot > of extra work when you don't have to. And why not ? Anyway SQL*Plus contains plenty of built-in commands that allow you to format your output how you like: I'd like to keep that functionality. And let's say that I want to do that for the sole purpose of learning the handling of IO streams in Python ! > If you're just learning Python, you've taken on a fairly > complicated and large task right at the beginning. Why not I admit it. But I did *exactly* the same with Java (writing the app I'm trying to port) but never got stuck into problems that blocking... Thanks. From paul at boddie.net Thu Sep 19 03:29:01 2002 From: paul at boddie.net (Paul Boddie) Date: 19 Sep 2002 00:29:01 -0700 Subject: linux python ideas References: <3D88E578.6010001@diespammerdieuselesspython.com> Message-ID: <23891c90.0209182329.52b55550@posting.google.com> Fernando P?rez wrote in message news:... > Rob Andrews wrote: > > > I'll be giving a presentation on Python to my local LUG > > (http://lugoj.org) in a few weeks, and would like to point out at least > > a few things that would be of particular interest to linux users. > > > Check out ipython at http://www-hep.colorado.edu/~fperez/ipython I'd very much recommend a demonstration which uses the interactive mode of Python. That was one of the things that impressed me about Python in the beginning: the ability to do things like connecting to servers interactively and with barely any effort, and I amused myself by perusing the Python newsgroups at the Python prompt and thinking how straightforward it would be to write a newsreader in Python instead of C, for example. Of course, stuff like "network programming" is fairly easy with other languages, but unless Perl has spawned an interactive mode, for example, you'll be showing people things they haven't seen before if you show some experimentation at the command prompt. You might also get bonus points by then demonstrating the same things again in Jython. :-) Paul From max at alcyone.com Mon Sep 30 22:28:36 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 30 Sep 2002 19:28:36 -0700 Subject: ANN: empy 2.0 -- Embed Python in template text as markup Message-ID: Summary empy is a system for embedding Python expressions and statements in template text; it takes an empy source file, processes it, and produces output. This is accomplished via expansions, which are special signals to the empy system and are set off by a special prefix (by default the at sign, '@'). empy can expand arbitrary Python expressions and statements in this way, as well as a variety of special forms. Textual data not explicitly delimited in this way is sent unaffected to the output, allowing Python to be used in effect as a markup language. Also supported are "hook" callbacks, recording and playback via diversions, and dynamic, chainable filters. The system is highly configurable via command line options and embedded commands. Expressions are embedded in text with the '@(...)' notation; variations include conditional expressions with '@(...?...:...)' and the ability to handle thrown exceptions with '@(...$...)'. As a shortcut, simple variables and expressions can be abbreviated as '@variable', '@object.attribute', '@function(arguments)', '@sequence[index]', and combinations. Full-fledged statements are embedded with '@{...}'. Forms of conditional and repeated expansion are available via '@[...]'. A '@' followed by a whitespace character (including a newline) expands to nothing, allowing string concatenations and line continuations. Comments are indicated with '@#' and consume the rest of the line, up to and including the trailing newline. '@%' indicate "significators," which are special forms of variable assignment intended to specify per-file identification information in a format which is easy to parse externally. C-style escape sequences can be specified with '@\...', and finally a '@@' sequence expands to a single literal at sign. Getting the software The current version of empy is 2.0. The latest version of the software is available in a tarball here: "http://www.alcyone.com/pyos/empy/empy-latest.tar.gz", http://www.alcyone.com/pyos/empy/empy-latest.tar.gz. The official URL for this Web site is "http://www.alcyone.com/pyos/empy/", http://www.alcyone.com/pyos/empy/. Requirements empy should work with any version of Python from 1.5.x onward. License This code is released under the "GPL", http://www.gnu.org/copyleft/gpl.html. ... Release history [since 1.x] - 2.0; 2002 Sep 30. Parsing system completely revamped and simplified, eliminating a whole class of context-related bugs; builtin support for buffered filters; support for registering hooks; support for command line arguments; interactive mode with -i; significator value extended to be any valid Python expression. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ To be adult is to be alone. \__/ Jean Rostand Crank Dot Net / http://www.crank.net/ Cranks, crackpots, kooks, & loons on the Net. From jepler at unpythonic.net Mon Sep 30 14:34:04 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 30 Sep 2002 13:34:04 -0500 Subject: conditional expressions In-Reply-To: References: <33b491f.0209181820.17b6ea70@posting.google.com> Message-ID: <20020930183403.GB21522@unpythonic.net> On Mon, Sep 30, 2002 at 03:09:08PM +0000, Alex Martelli wrote: > I've shown this i18n'd with gettext's convention _( ... ) , but > of course not all languages can pluralize by a constant suffix > (English can't -- if ever a number of leaves or fishes was > among the found things, we'd be in trouble...!-), so a better > approach might be, e.g., for English: [...] It's even worse than this. For instance, a language where the form for 1 is unique, numbers ending with 2, 3, 4 (except for 12, 13, and 14 -- I'm not sure about 111, 1211, etc) get a second form, and the rest of the numbers get a third form. I quote from the gnu gettext manual: Additional functions for plural forms ------------------------------------- The functions of the `gettext' family described so far (and all the `catgets' functions as well) have one problem in the real world which have been neglected completely in all existing approaches. What is meant here is the handling of plural forms. Looking through Unix source code before the time anybody thought about internationalization (and, sadly, even afterwards) one can often find code similar to the following: printf ("%d file%s deleted", n, n == 1 ? "" : "s"); After the first complaints from people internationalizing the code people either completely avoided formulations like this or used strings like `"file(s)"'. Both look unnatural and should be avoided. First tries to solve the problem correctly looked like this: if (n == 1) printf ("%d file deleted", n); else printf ("%d files deleted", n); But this does not solve the problem. It helps languages where the plural form of a noun is not simply constructed by adding an `s' but that is all. Once again people fell into the trap of believing the rules their language is using are universal. But the handling of plural forms differs widely between the language families. For example, Rafal Maszkowski `' reports: In Polish we use e.g. plik (file) this way: 1 plik 2,3,4 pliki 5-21 pliko'w 22-24 pliki 25-31 pliko'w and so on (o' means 8859-2 oacute which should be rather okreska, similar to aogonek). [.... about 250 more lines describing how gettext attempts to address these situations] From thomas.heller at ion-tof.com Thu Sep 26 02:59:43 2002 From: thomas.heller at ion-tof.com (Thomas Heller) Date: 26 Sep 2002 08:59:43 +0200 Subject: SET_LINENO References: <3D92A46E.2030706@cygnus-software.com> Message-ID: Bruce Dawson writes: > P.P.S. A breakpoint instruction would also be a boon for asserts - I'd > love to be able to stop on the assert when running under a debugger, > to see what is wrong before the stack frame unwinds. Have you seen this? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65287 Thomas From henrik.motakef at web.de Tue Sep 24 13:39:33 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 24 Sep 2002 19:39:33 +0200 Subject: general thoughts References: <3D8B3250.BA964BCF@ObjectWay.it> Message-ID: <87n0q7ffsa.fsf@pokey.henrik-motakef.de> Dave Kuhlman writes: > And, a large part of the book describes how to program without variables and > state. That's weird and interesting, just like the Elephant Man was weird > and interesting. But, after that, then what? Am I supposed to try to > program that way? Read "The Koan of Side Effect" at . Become enlightened. > It did not teach me good Python programming style. I could not hardly read > my own code with all those many layers of parentheses. > > It did not teach me how to use Python data structures. I found myself doing > too many screwy things with lists. As the book's title indicates, it's about how computer programs work, not about using Python data structures. Regards Henrik From mhammond at skippinet.com.au Wed Sep 11 18:54:40 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 11 Sep 2002 22:54:40 GMT Subject: untrusted dynamic module: win32api References: Message-ID: Guy Rabiller wrote: > [Mark] > >>It appears that SoftImage is configuring ActiveScripting for "untrusted" >>scripts - ie, SoftImage is requesting the scripting engine switch into >>untrusted mode. Thus, you really need to ask SoftImage is the >>application can be configured to not request restricted execution mode >>of the language > > > After a closer look, it seems that this has nothing to do with Softimage, > but with MSIE. > > Even if I include ( for exemple ): > > > > in a simple html file, then launching it in MSIE, totaly outside from > Softimage, it doesn't work, I still have the same error message. > ( it works in VBScript and JScript ) > > I think this has to do with restricted execution mode, but I have no clue > how to customize it for allowing the loading of 'untrusted dynamic modules'. > > Any help on this would be greatly apreciated. IE certainly does force restricted execution mode. There is no standard way to remove this restiction so facilities like you request can be performed on any installation. If necessary, you could modify the engine source code to remove this restriction - mail me for details. Mark. From jeremy at alum.mit.edu Fri Sep 13 09:58:39 2002 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 13 Sep 2002 06:58:39 -0700 Subject: Problem with HTTPS request References: Message-ID: "Christian Reyes" wrote in message news:... > I got the following response when trying to make an HTTPS request. > >

SSL required to access this page

> > Then I read in the documentation the following > > Note: HTTPS support is only available if the socket module was compiled with > SSL support. > > Does anyone know where i can get my hands on a socket module that was > compiles with SSL support? What platform are you running? Many people compile such a socket module themselves. If that isn't an option, you'll have to look at binary packages for your platform. Jeremy From somebody at nojunk.invalid Sun Sep 29 18:15:21 2002 From: somebody at nojunk.invalid (Russell E. Owen) Date: Sun, 29 Sep 2002 16:15:21 -0600 Subject: [Mac] Editor on Macintosh? References: <1fj7za2.1erbqps1uvzpj8N%news@agapow.net> Message-ID: In article <1fj7za2.1erbqps1uvzpj8N%news at agapow.net>, news at agapow.net (Paul-Michael Agapow) wrote: >Sadly, it seems like the excellent editor Pepper is going away. (See >.) I found it the best editor for Python on >the Macintosh, having never been really happy with the alternatives. > >So what are other MacPython using? There are some Java-based editors, >but I'm not persuaded that that they'll perform adequately. There's are >numerous X11 based options, but who wants to swap into X everytime they >need to edit a file? The once excellent editor Alpha seems to have >disappeared permanently into testing for its next release. > >Ideas? Anyone? Bueller? BBEdit is the standard. On the whole it works well--it's polished, reliable, fast and programmable. However, I loathe its find/replace dialog box: - To do a "search in selection" you have to UNCHECK "from the top" or "wrap" before you are allowed to check "in selection". What sadist programmed that? - Then when you want to return to normal mode, you uncheck "in selection" and then check "wrap" or "from the top", and heaven help you if you forget to check one of those, because: - If you leave both "from the top" and "wrap" unchecked, then a replace all does not do what it says, but instead it only replaces from the current cursor to the end of the document. I've corrupted quite a few source code files that way. - The dialog box is modal. Good luck if you want to enter text by copying from or reading from your document and you forget to read/copy it before opening the dialog box. (I agree that it's nice to have the box go away after pressing "Find", but a non-modal dialog can be programmed to do that, too!). Also it does not have rectangular selection, and you cannot edit files from browser windows (such as a find results window). jEdit (the Java editor, not the Japanese editor) worked pretty well when I tried it, but has an unusual document model (a given window may show different files at different times). Maybe I'd get used to it, but I decided not to try because I had Pepper. Alpha is quite configurable and programmable but also quite capable of getting into strange states (at least it has done so each of the few times I have test-driven it) where typing no longer works at all or does really weird things (it's been awhile, I don't remember the details). If there's a stable version that runs well under X perhaps you should just use it and not worry about future versions? CodeWarrior's IDE is nice, but does not have Python syntax coloring. Python has the Mac IDE is a bit limited (need an extra plug-in even to do syntax coloring) but OK. IDLE is showing promise and runs w/out xfree86 with Tcl/Tk 8.4 (which is now Aqua native). But Tk bugs may play havoc with key accelerators and generally cross-platform code doesn't seem to feel very Mac-like. -- Russell P.S. I wish Nisus Software hadn't stopped supporting Qued. It was a superb editor, but I think they couldn't maintain it and Nisus at the same time. It had first-rate multiple undo from the beginning, rectangular selections and even multiple selections (surprisingly handy). Pepper is the best I've found and is what I use. It has some rough edges, but very clean design. Unfortunately, the author really decided to pick up his toys and go home. You cannot buy a license anymore, you cannot get a free license, you cannot get source code. From eddie at holyrood.ed.ac.uk Fri Sep 20 06:28:47 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 20 Sep 2002 10:28:47 +0000 (UTC) Subject: general thoughts References: Message-ID: If you want to learn "how it (computer languages) works" I suggest reading "Structure and Interpretation of Computer Languages" by Abelson and Sussman. This is about understanding the principles rather than how to do things in a particular language and is probably the best book on the subject. Eddie From Janssen at rz.uni-frankfurt.de Sun Sep 22 07:02:41 2002 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sun, 22 Sep 2002 13:02:41 +0200 Subject: Python about file I/O References: Message-ID: <3d8da3df@nntp.server.uni-frankfurt.de> Ken wrote: > Hi, I have 2 questions on IO, not necessary related to one another: > > 1.) How do you list the filenames within a given directory so user can > choose which file to open? > > 2.) How do you ensure the program doesn't crash if I specify a > filename to open but the file doesn't exist? (I.E. how to check if > file exist before opening the file?) > > Thanks existence-check is: os.access(file,os.F_OK) Michael From dsavitsk at e-coli.net Thu Sep 26 01:31:22 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 26 Sep 2002 05:31:22 GMT Subject: Python and Scite References: Message-ID: PythonWin is my favorite editor, and it is in the win32all (python for windows extensions) package at http://starship.python.net/crew/mhammond/ -d "Sperry Russ" wrote in message news:mailman.1033005453.8052.python-list at python.org... Chris, Thanks for your help. The problem was in the path which I did not understand at first. Is th PythonWin your favorite editor? Sperry ---------------------------------------------------------------------------- ----------------------------- > I am new to programming. I have downloaded Python 2.2.1 and Scite > 1.48 to learn how to program. I am trying to configure my Scite so > that it will run the python files by using go. When I try to do this > i get a message in the second window at the bottom -- unable to find > file. I have tried configuring the global options and have failed can > anyone help me? I need a step by step example if you can because I > cannot understand it according to the documentation that came with > Scite works out of the box for me. if you're on windows, make sure that python is found in the PATH. i.e. edit PATH that it contains the python directory. and you could look at PythonWin, it uses the editing component used in scite and has some additional features for the python programmer. additionaly it comes also with useful, de-facto standard, windows specific extensions. From aleax at aleax.it Mon Sep 30 11:09:08 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 30 Sep 2002 15:09:08 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> Message-ID: Terry Reedy wrote: ... >> It's _dangerous_ -- to use it, one always has to be fully aware >> of the risk that subexpression b might be false. > > If b is a non-null constant, there is no such risk. Consider If it's a constant, you don't need short-circuiting! > na=1; np=3; nl=1; ng=0 > print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\ > (na, na!=1 and 's' or '', np, np!=1 and 's' or '', nl, nl!=1 and 's' > or '', ng, ng!=1 and 's' or '') > > Found: 1 apple, 3 plums, 1 lemon, and 0 grapes. > > Alternatives to this 'risky' construct: def plur(*ns): for n in ns: yield n yield 's'[n!=1:] print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." % tuple( plur(na, np, nl, ng)) You can inline plur's logic if you want, of course -- although I believe it's more readable in this way. But anyway, the point is that slicing is handier than and/or in this important special case. For other cases in which you don't need short-circuiting, indexing is fine -- " ('ba','glor')[n!=1] " if that's what a certain natural language wants for singular/plural endings. But when one accepts that a function for such pluralization is preferable anyway, then if-else becomes attractive once again: def plur(*ns, singular=_(''), plural=_('s')): for n in ns: yield n if n == 1: yield singular else: yield plural I've shown this i18n'd with gettext's convention _( ... ) , but of course not all languages can pluralize by a constant suffix (English can't -- if ever a number of leaves or fishes was among the found things, we'd be in trouble...!-), so a better approach might be, e.g., for English: def plur(*numbers_and_nouns): for i in range(len(numbers_and_nouns)): number, noun = numbers_and_nouns[i:i+2] yield "%d %s" % (number, pluralize(number, noun)) where: plural_exceptions = {'man':'men', 'child':'children', # etc etc 'leaf':'leafes', 'fish':'fishes', # etc etc } def pluralize(number, noun): if number == 1: return noun else: return plural_exceptions.get(noun, noun+'s') You could factor this up in different ways, but please DO ensure your software never output "plurals" such as "mans", "childs", "leafs", or "fishs". > 1. forgo the nicety of correct English output That's basically what you're doing when you choose to just conditionally append s's. If you do take such a shortcut (because you know that none of the nouns you handle can ever be one of the many exceptions in English pluralization), then slicing is one option -- but overall I prefer a short function to wrap the pluralization task, I think that the ability to give the function a name helps clarity a LOT, whether you ARE willing to "just stick an s at the end" OR waht to ensure "the nicety of correct English output". > 2. nest if/else four levels deep to choose correct variant of 16 print > statements (ugh) > 3. precalculate 4 suffixes and store in 4 temp vars with 4 if/else's > (8 or 16 lines); > though clearly superiour to 2), this is still tedious with some > risk of typo error. "Risk of typo error" is quite present even in your repetition of the and/or idiom (and to a lesser extent in a similarly inlined repetition of the slicing or indexing idioms). Better to wrap things into a function: NO repeated code...! Alex From sscherte at mailbox.epfl.ch Tue Sep 10 04:25:36 2002 From: sscherte at mailbox.epfl.ch (Sebastien Schertenleib) Date: Tue, 10 Sep 2002 10:25:36 +0200 Subject: Embedding python with a C++ multithread apps -> pause and resume python script Message-ID: <001601c258a3$a3e19a20$4c4eb280@epfl.ch> Hi, I am developping a C++ application and I want to embedd python. I have succeeded to export my C++ classes and data using SWIG then I was able to create multithreading call to python and now I have my app running several script at the same time (~). However, I am stack as I would like to be able to pause and resume my python script from C++ side. If we imagine a looping script, my C++ thread in still in the Py_Run_SimpleString() method, and I would like to pause it inside python. I have try to go directly inside the Interpreter state with all the thread queue but it seem that I don't understand how python access to data since I have set to NULL some thread state and my script continue to run as it. If someone can give me a hint how to block a python script directly from C++, it would help me a lot. A second problem is that when I try to redirect the sys.stderr and sys.stdout from python (create a python class which has a write method, and then which called inside my C++ method), It's working only until a certain time then it crash, how can I do a redirection in case of a c++ multithreading app? (I have synchronized the C++ method as well)) Thanks a lot for any help! So, here is my thread run method: /* Wait for the initialization thread if there is one.*/ if (_initScript != _PythonScriptHandle(NULL)) _initScript->_thread->join(); PyEval_AcquireLock(); PyInterpreterState *interp = _service->_mainTstate->interp; // create new PyThreadState only if needed JTCThread * currentThread = JTCThread::currentThread(); PyThreadState * tstate; vhdPythonServiceBody::_Impl::ThreadInfoMap::iterator it = _Impl::threadInfoMap.find(currentThread); if (it == _Impl::threadInfoMap.end()) { vhdPythonServiceBody::_Impl::ThreadInfo threadInfo; threadInfo.pyThreadState = PyThreadState_New(interp); threadInfo.outputBuffer = ""; it = vhdPythonServiceBody::_Impl::threadInfoMap.insert (vhdPythonServiceBody::_Impl::ThreadInfoMap::value_type( currentThread, threadInfo)).first; } tstate = (*it).second.pyThreadState; PyThreadState_Swap(tstate); /* Execute the given script.*/ switch (PyRun_SimpleString((char*) _scriptText->cstr())) { case 0: _executionResult=RES_OK; break; case -1: _executionResult=RES_ERROR; break; } PyThreadState_Swap(NULL); // only for internal threads created by vhdPythonService (by using send for execution methods)if (_bServiceInternalThread) { // Reset the thread state structure. PyThreadState_Clear(tstate); // Nullify the current thread state, release the global // interpreter lock, delete the thread state structure. PyThreadState_Delete(tstate); // removal of ThreadInfo that was used for internal thread // we will not resues it as it was only for the internal thread _Impl::threadInfoMap.erase(currentThread); } PyEval_ReleaseLock(); /* Notify the service about the termination of the thread. */ _service->_notifyTermination(this); } -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.gonnerman at newcenturycomputers.net Sun Sep 29 18:33:57 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sun, 29 Sep 2002 17:33:57 -0500 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: <006701c26808$5385cd20$ba01010a@local> ----- Original Message ----- From: "Bengt Richter" > On 29 Sep 2002 17:06:53 GMT, Christopher Browne wrote: > > >The problem with FP is that FP involves the use of binary > >approximations, which commonly cannot exactly represent > >decimal values. > > > >Notably, the decimal fraction 0.1, which is /exactly/ 1/10, > >does not have any exact encoding in binary. Its > >representation in binary is a repeating binary fraction. > > How is that a significantly different problem from repeating > decimal fractions? (E.g., 1/3. or 1/7. or wxyz/9999. which > will give you 0.wxyzwxzy..?) Humans think in decimal. To a human, 1.0/10.0 == 0.1, not 0.10000000000000001. OK, so this *rounds* to 0.10 at two decimal places, but what about: >>> .70 * .05 0.034999999999999996 Rounded to two decimals, that's 0.03; but done in proper decimal numbers, the answer should be 0.035, rounded to 0.04 using either "classic" or "banker's" decimal rounding. If you are calculating sales tax, for instance, this is unacceptable. (I borrowed this example from memory from a previous poster, and if I could remember who it was I'd give credit...) You ask how it is a different problem. Simple. A human, training in decimal math in grade school, knows that 1/3 = 0.3333333... and would *expect* it to round to 0.33 (still in two decimal places). The problem with *binary* floating point is the "surprise factor." So, Bengt, how do I do this right using only floats? I can't. I have to have decimal arithmetic to get the right answer. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From juliana at pdi.inpe.br Tue Sep 24 14:58:48 2002 From: juliana at pdi.inpe.br (Juliana Braga) Date: Tue, 24 Sep 2002 15:58:48 -0300 Subject: help Message-ID: I need help. For example: x = ?name1? How can I get the value of variable x (in this case the value of variable x is ?name1?). After , I?d like to do this: value of variable x = ?teste?. From joconnor at cybermesa.com Wed Sep 4 20:28:39 2002 From: joconnor at cybermesa.com (Jay O'Connor) Date: Thu, 05 Sep 2002 07:28:39 +0700 Subject: Why read-only nested scopes? References: Message-ID: <20020905.072837.159259470.2038@cybermesa.com> In article , "Martin v. L?wis" wrote: > Gon?alo Rodrigues writes: > >> >Gon?alo Rodrigues writes: >> > >> >> So why hasn't this been extended when nested scopes were introduced, >> >> e.g. by reusing the global directive or some other one? >> > >> >I think the main reason is that nobody could propose an acceptable >> >syntax. Reusing the global directive does not work. >> >> Can you explain why it does not work? > > Consider > > x = 1 > > def foo(): > x = 2 > def bar(): > x = 3 > def baz(): > global x > x = 4 > > If you invoke baz(), which of the variables is changed? How do you > denote that you want to change the others? > > Regards, > Martin Why not simply disallow the using of a name already defined in an enclosing scope? Similar to Smalltalk? Consider the following: | y | aBlock := [ | x | y := [ | x | x := 5 x ] value ] value . ^y Here I'm defining x twice, once inside the outer most block and once inside the inner most block. Attempting to execute this (actually, attempting to compile it) raises an error "x is already defined (perhaps in an outer block)" changing the inner x to 'x1' or something solves the problem This works for instance variables in methods of a class, too. If an object has an instance variable named foo...you can't have a method with a temporary variable named foo also, the compiler will error out with the above error about foo already being defined -- Jay O'Connor joconnor at cybermesa.com http://www.r4h.org/r4hsoftware From mike at bindkey.com Fri Sep 27 18:24:04 2002 From: mike at bindkey.com (Mike Rovner) Date: Fri, 27 Sep 2002 15:24:04 -0700 Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <7nHk9.172208$pX1.6117207@news2.tin.it> Message-ID: "Terry Reedy" wrote in message news:t_3l9.334924$AR1.14880141 at bin2.nnrp.aus1.giganews.com... > na=1; np=3; nl=1; ng=0 > print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\ > (na, na!=1 and 's' or '', np, np!=1 and 's' or '', nl, nl!=1 and 's' > or '', ng, ng!=1 and 's' or '') > > Found: 1 apple, 3 plums, 1 lemon, and 0 grapes. > > Alternatives to this 'risky' construct: > 1. forgo the nicety of correct English output > 2. nest if/else four levels deep to choose correct variant of 16 print > statements (ugh) > 3. precalculate 4 suffixes and store in 4 temp vars with 4 if/else's > (8 or 16 lines); > though clearly superiour to 2), this is still tedious with some > risk of typo error. > 4. Try: use_s=('','s') print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\ (na, use_s[na!=1], np, use_s[np!=1], nl, use_s[nl!=1], ng, use_s[ng!=1]) From mstenner at phy.duke.edu Wed Sep 4 13:29:51 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Wed, 4 Sep 2002 13:29:51 -0400 Subject: simple xml pickle In-Reply-To: ; from mertz@gnosis.cx on Wed, Sep 04, 2002 at 12:13:04PM -0400 References: Message-ID: <20020904132951.A7928@phy.duke.edu> On Wed, Sep 04, 2002 at 12:13:04PM -0400, David Mertz, Ph.D. wrote: > Michael Stenner wrote previously: > | the "old" xml_pickle.py, which appears to not work at all with > | python2.2, but is otherwise appealing.... > | the "new" xml.pickle as it appears in the Gnosis tools. This is > | less appealing because it's very large and distributed over several > | files... > > I think there are some good reasons why the "new" gnosis.xml.pickle is > organized into a package namespace. And there are some new capabilities > and modularity that go along with that. You're quite right. I should have said "less appealing as a solution in my current task" or something similarly qualified. > However, the "old" xml_pickle (use the latest such one, labelled 0.51) > can be fixed up for Python 2.2 by adjusting two uses of dir(). That > built-in function changed meaning in Python 2.2--or at least it changed > behavior. Just replace occurrences of 'dir(obj)' with > 'obj.__dict__.keys()', and I'm pretty sure all will be well. That's the version that I was playing with last night. I'll take another look at it. I think there were some api changes in the DOM stuff too, though. I'm not sure of the specifics. The xml marshalling does almost exactly what I want, and the modifications to make it "standalone" for Python 2.2 were very easy (patch forthcoming) so I may just stick with that. Nonetheless, I'll look at xml_pickle again and see what I can see. > Yours, David (the xml_pickle guy)... Yeah, I remembered the name... when you a google search on "xml pickle" you see "David Mertz, Ph.D" popping up everywhere :) -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From steve at ferg.org Fri Sep 13 09:06:40 2002 From: steve at ferg.org (Stephen Ferg) Date: 13 Sep 2002 06:06:40 -0700 Subject: Newbie Looking for direction References: Message-ID: > So far it seems like I'm a long way away from being able to be productive > with Python... This might help in getting you productive quickly: http://www.ferg.org/easygui/ From jnana4 at DELETEhotmailCAPS.com Sun Sep 1 16:56:34 2002 From: jnana4 at DELETEhotmailCAPS.com (jano) Date: Sun, 01 Sep 2002 20:56:34 GMT Subject: EOFError using cPickle.load Message-ID: <6avc9.264595$me6.34329@sccrnsc01> Hi, I am getting an EOFError when i try to load a cPickled object that was cPickled in binary format. >>> import cPickle >>> cPickle.dump(keywordDict, open('pickle.p', 'w'), 1) >>> somedict = cPickle.load(open('pickle.p', 'r')) Traceback (most recent call last): File "", line 1, in ? somedict = cPickle.load(open('pickle.p', 'r')) EOFError >>> It works fine with small test dictionaries, but it doesn't seem to like my keywordDict dictionary, which is a very long inverted index, an excerpt of which follows: {'cellularli': ['4620'], 'non-cooper': ['2350'], 'liar': ['5800', '5800'], 'consider': ['880', '1270', '1690', '3420'], 'founder': ['3420'], 'illustr': ['3180'], 'fly-bottl': ['6090'], 'hatr': ['1200', '3490'], 'instinctu': ['2260'], 'four': ['20', '1640', '1800', '3420', '3700'], 'presupposit': ['4400'], 'sleep': ['2300'], 'phenomenologist': ['3350', '3350', '3420'], 'conclus': ['470', '1830', '2990'], 'follow': ['390', '390', '1070', '2030', '3700', '3880'], 'children': ['1990', '5030'], 'abid': ['650'], 'skeleton': ['1110'], 'accus': ['3490'], 'incap': ['1060'], 'tu': ['3960'], 'swai': ['1600'], 'articl': ['4230', '4350'], 'self-piti': ['1200'], 'program': ['440'], 'invari': ['1250'], 'ti': ['4530', '5280'], 'hermann': ['3420'], 'smile': ['1070'], 'pride': ['5180'], 'worth': ['1220', '2480', '2490', '2790', '3010', '4750', '5890'], 'volit': ['1690', '1710'], 'case': ['1270', '3700'], 'lure': ['3710'], 'meritrend': ['700'], 'everi': ['390', '500', '610', '820', '840', '1090', '1150', '1190', '1290', '1530', '1620', '1830', '1830', '2050', '2060', '2400', '2410', '2620', '2630', '2660', '2670', '2890', '3240', '3320', '3330', '3460', '3670', '3670', '3670', '4110', '4120', '4160', '4440', '4520', '4520', '4800', '4900'], 'parcel': ['390'], 'physician': ['5670'], 'fals': ['570', '1180'], 'void': ['1020', '1250', '2560'], 'rise': ['3620', '4000'], 'lurk': ['3610'], 'voic': ['3710'], 'util': ['390'], 'lumin': ['1190'], 'candid': ['2180'], 'mechan': ['300'], 'lowland': ['140'], 'fall': ['0', '1160', '1250', '1740', '3710', '3710', '3710', '3790'], 'veri': ['450', '1190', '1320', '1490', '1640', '1900', '2470', '2680', '2680', '2680', '3460', '3490', '3520', '3680', '4590', '4620', '4670', '4670', '4670', '5470'], 'affect': ['250'], 'puffi': ['250'], 'strang': ['700', '1480', '3160'], 'vast': ['2870'], 'school': ['1360', '1370', '2370'], 'heaven': ['710', '5260'], 'affirm': ['3310', '3310'], 'previou': ['3330'], 'sand': ['4060'], 'subhuman': ['1270'], 'tereza': ['3700'], 'small': ['330', '3630', '4620'], 'customari': ['2830'], 'everth': ['1380'], 'disabus': ['1020'], 'triumph': ['1470'], 'fritter': ['5560', '5590'], 'enjoy': ['4570'], 'chew': ['270'], 'abil': ['5870', '6180'], 'direct': ['390', '390', '1780', '4340'], 'dogmat': ['3220'], 'past': ['20', '430', '430', '430', '440', '1270', '1320', '1960', '1960', '2060', '3330', '3530', '3530'], 'consequ': ['1680', '1830', '2550'], 'second': ['110', '3490', '3700', '3700', '3700', '5140'], 'street': ['800', '870', '3700'], 'design': ['4430', '4560'], 'pass': ['2890', '3260', '5140'], 'link': ['3470'], 'illumin': ['3600', '4620'], 'theory': [], 'excit': ['1020', '1210'], 'aim': ['380', '390', '1420', '5110', '6090'], 'hide': ['2700', '3500', '3730', '4340'], 'barrier': ['3750'], 'microphon': ['3620', '3700'], 'solemn': ['250'], 'sun': ['4340', '4340'], 'sum': ['1280']} It works fine in text mode, but is too slow, so i tried it in binary mode, but i get the EOFError everytime. Anybody know what is going on here or how I can get this to work in binary mode? thanks, jano From fperez528 at yahoo.com Mon Sep 23 16:04:49 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 23 Sep 2002 14:04:49 -0600 Subject: Non-interpreted Python? References: <3D8F65A4.38124945@engcorp.com> Message-ID: Tapio Kelloniemi wrote: >>There are other approaches, but there's no point describing them until >>you explain why you want to do this. What are your requirements? > I'm using Linux and searching for a good high-level language to use in > my projects. I don't have any special ideas, it depends on language. Early optimization is the root of all evil. --- D. Knuth. _After_ you: 1. Know your code is correct. 2. Know you _do_ have a problematic bottleneck. 3. Know that bottleneck is due to python's execution speed (and not choice of a poor algorithm, I/O or network bottlenecks, etc). _Then_ you consider optimizing it away in a compiled language. At that point, python offers a plethora of solutions: Numeric (for number crunching), pyrex, weave, boost.python, SWIG, CXX, SCXX, ... Some easier than others, some more tailored to some problems than others. But don't worry, chances are you'll find that 9 times out of 10 python is fine, and for the cases when there is indeed a critical bottleneck (which of course do exist), there are plenty of very convenient ways of addressing that problem in python. Cheers, f. ps. Anyone care to put a summary of this issue into a FAQ, since it seems to show up around here about once a week? Something reasonably detailed and with links to all the current projects (I mentioned the ones I know about above, I'm sure there's more). From whisper at oz.net Tue Sep 17 06:20:18 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 17 Sep 2002 03:20:18 -0700 Subject: More on Protecting Source Code In-Reply-To: <20020917062412.GA85457@hishome.net> Message-ID: > The state has given you the 'right' to use the power of its court and > police to forcibly restrict people that use information you have created > in violation of copy-restriction laws. I don't know what country you're in, but in mine, at least in theory, we ARE the state! We elected those who make the laws we live by and, again at least in theory, we can vote them out when they get out of line (like the current bums, but I digress). We have an independent judiciary to protect us against the more egregious misventures of our legislation and executive branches too. > But that is not enough for you. You also want the 'right' to > complain about > something that was given to you freely and expect that righteous rants > about your view of intellectual property laws will somehow compel people > to modify it to your specification without compensation. > > Oren > Please explain to me where I was complaining? I pointed out what I see as a limitation of Python. As I just said elsewhere, Python didn't get to where it is by impuning and misrepresting the character of those who offer criticisms. Vote Democrat in November! Dave LeBlanc Seattle, WA USA From duncan at NOSPAMrcp.co.uk Tue Sep 24 09:00:27 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 24 Sep 2002 13:00:27 +0000 (UTC) Subject: Guido Van Rossum to speak at UK Python Conference Message-ID: This is a repost of the CFP: if you missed it the first time it isn't too late to put yourself forward as a speaker at the UK Python Conference. No previous experience necessary, just tell me what you want to talk about or suggest a range of topics if you aren't sure. The provisional list of speakers for this conference includes Guido van Rossum, David Abrahams (Boost Python), Andrew Koenig, Marc Andr? Lemburg, and many more. See http://www.accuconference.co.uk/ for more about the conference. *** Call for Participation *** UK Python Conference 2003 April 2-3 2003 Holiday Inn, Oxford The UK Python Conference 2003 is being held in conjunction with the larger ACCU conference. The conference will include two days of papers arranged in 90 minute speaking slots with either one or two tracks. The audience is highly technical and will include experts in many fields of computing, some of whom may know little or nothing about Python. Talks will be welcomed on any aspect of Python, but we are especially interested in the following: - Commercial applications for Python - Cross-language talks Speakers are welcome from the UK or the rest of the world, however our budget for overseas speakers may be limited. Speakers get reasonable travel and accomodation costs paid as well as free attendance at the Python conference and the associated ACCU conference. To submit a proposal, send an email message to duncan at rcp.co.uk by 2nd October 2002. In your message, please include the following: - Speaker name and affiliation - Contact address - Presentation title - A one paragraph abstract -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From ch_knievel at gmx.de Wed Sep 25 12:01:07 2002 From: ch_knievel at gmx.de (christopher knievel) Date: Wed, 25 Sep 2002 18:01:07 +0200 Subject: [newbie] mod_python apache w32 References: Message-ID: Hi Donald, i still didn't find a working solution, but i am trying now with a standalone apache server installation and hey there are some other error messages....but i am still trying :) regards, christopher knievel >"Donald Lessau" schrieb im Newsbeitrag news:amrvgp$lfk$1 at newsreader2.netcologne.de... > hi christopher, > > i've got exactly the same problem... Did you find a solution in the > meantime? > > thanks > Donald > > "christopher knievel" schrieb im Newsbeitrag > news:ami5rr$des$04$1 at news.t-online.com... > > Hi all, > > i got some problems running mod_python with apache under windows. > > I am using python 2.2 and apache 1.3.26. > > As written in the manual i configured httpd.conf like this: > > > > LoadModule python_module modules/mod_python.dll > > > > AddModule mod_python.c > > > > > > AddHandler python-program .py > > PythonHandler mptest > > PythonDebug on > > > > > > I copied the mod_python.dll to C:/Python22/lib/mod_python. > > > > The Apache server is starting with "Apache/1.3.26 (Win32) mod_python/2.7.6 > > Python/2.2.1 running..." > > So i guess it should be working.... > > > > The test script looks like this: > > > > #! C:/Python22/python.exe > > > > from mod_python import apache > > > > def handler(req): > > req.send_http_header() > > req.write("Hello World!") > > return apache.OK > > > > my error.log (last entry): > > [Sat Sep 21 18:00:13 2002] [error] [client 192.168.1.99] python_handler: > > make_obcallback returned no obCallBack! > > > > i've read several newsgroups and googled a lot but i didn't found a > working > > solution > > Thanks a lot in advance... > > christopher knievel > > > > > > From thoa0025 at mail.usyd.edu.au Mon Sep 16 04:36:23 2002 From: thoa0025 at mail.usyd.edu.au (:B nerdy) Date: Mon, 16 Sep 2002 08:36:23 GMT Subject: [xml] convert funny chars to char entites? References: Message-ID: now when i do filehandle.write(str) on text that has the funny chars in it. it crashes with an error like this Traceback (most recent call last): File "./batch-maid.py", line 85, in ? generate_browse_options() File "./batch-maid.py", line 70, in generate_browse_options f.write(options_composer) UnicodeError: ASCII encoding error: ordinal not in range(128) whats going on? how can i fix it? cheeers "Martin v. Loewis" wrote in message news:m3elbuze67.fsf at mira.informatik.hu-berlin.de... > ":B nerdy" writes: > > > ive got a string "Il Est N?" and i want to put it into a xml document > > > > is there a quick and easy way to conver the funny characters to char > > entities so i can store them? > > I recommend you properly declare the encoding of the document, e.g. > > > > (assuming the ? is meant to be encoded in Latin-1). > > XML does not define external entities for non-ASCII characters, so you > would have to create a DTD first if you want them. > > Regards, > Martin > From cce at clarkevans.com Wed Sep 25 00:50:50 2002 From: cce at clarkevans.com (Clark C. Evans) Date: Wed, 25 Sep 2002 04:50:50 +0000 Subject: streaming popen to ftp.storbinary Message-ID: <20020925045050.GA67481@doublegemini.com> Hello. I'm trying to pipe the output of a process created by popen3 through FTP to a file on a remote box. Ideally, the process would block (so that a temporary file isn't needed). I have the following... (sin,sout,serr) = os.popen3( my_command, 'b' ) # binary stream ftp.storbinary("STOR %s " % filename, sout) Anyway, if I go through an intermediate file, say by using os.system and piping to a temp file, and then using open() in the storbinary call it works. Also, this works under Win32 using ActiveState's python 2.2.1 but fails under version 2.2 compiled for FreeBSD. Could this be a version problem? Best, Clark From thorsten at thorstenkampe.de Tue Sep 24 04:08:31 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 24 Sep 2002 10:08:31 +0200 Subject: list problem References: <3D8F9F5E.DC48B13F@pop.ntlworld.com> Message-ID: * Anthony Tuininga > If you have list comprehensions available, use > > [b for a in x for b in a] What about: reduce(lambda x, y: x + y, a) ? Thorsten From kathuw at swbell.net Fri Sep 27 05:03:11 2002 From: kathuw at swbell.net (Kat & Huw) Date: Fri, 27 Sep 2002 04:03:11 -0500 Subject: How do I set-up Multiple socket connections Message-ID: <002a01c26604$b515c3c0$0100a8c0@mshome.net> Ok, I want to iterate through a server IP list and establish multiple socket connections to the various IP address' in the list. I can do the iterations and I can make single connections, but I can't work out how I can connect to several address at once. I understand that a socket is closed, or closes after its done getting the ACk or whatever after sending a request, but how on earth do I connect to like 5 addresses at once? I've used non-blocking sockets and the sockettimeout module to skip a host on certain exceptions, but I want to try the exact same thing on several hosts at once. Any help would really be appreciated. Yours opn -------------- next part -------------- An HTML attachment was scrubbed... URL: From jwold at min.midco.net Tue Sep 24 00:55:53 2002 From: jwold at min.midco.net (Jarrett Wold) Date: Mon, 23 Sep 2002 23:55:53 -0500 Subject: PyXML Building on OS X? References: Message-ID: On 9/23/02 4:45 AM, in article j4k7ldghtp.fsf at informatik.hu-berlin.de, "Martin v. L?wis" wrote: ... extensions/expat/lib/xmlparse.c:3056: warning: `regparm' attribute directive ignored extensions/expat/lib/xmlparse.c:3093: warning: `stdcall' attribute directive ignored extensions/expat/lib/xmlparse.c:3093: warning: `regparm' attribute directive ignored extensions/expat/lib/xmlparse.c:3107: warning: `stdcall' attribute directive ignored extensions/expat/lib/xmlparse.c:3107: warning: `regparm' attribute directive ignored ... cc -L/sw/lib -bundle -flat_namespace -undefined suppress build/temp.darwin-5.5-Power Macintosh-2.2/pyexpat.o build/temp.darwin-5.5-Power Macintosh-2.2/xmlparse.o build/temp.darwin-5.5-Power Macintosh-2.2/xmlrole.o build/temp.darwin-5.5-Power Macintosh-2.2/xmltok.o -o build/lib.darwin-5.5-Power Macintosh-2.2/_xmlplus/parsers/pyexpat.so -flat_namespace /usr/bin/ld: -undefined: unknown argument: -lbundle1.o error: command 'cc' failed with exit status 1 > Jarrett Wold writes: > >> If you want some sample output of the build I can certainly rerun >> it and post it. > > Please do. No need to report the entire output, though - just the > error messages and a little context is needed, such as the compiler > line that caused the error message. > > Regards, > Martin > From lists at gregfortune.com Wed Sep 18 15:06:56 2002 From: lists at gregfortune.com (Greg Fortune) Date: Wed, 18 Sep 2002 12:06:56 -0700 Subject: Loading modules from several directories References: <33803989.0209172247.2e6afc1f@posting.google.com> Message-ID: <3d88ccbb$0$310$39cecf19@nnrp1.twtelecom.net> If it is indeed a package, you don't need to append both paths. Just use: sys.path.append('/somedir/foo') import foo.foostuff import foo.project_a.projectstuff Furthermore, any module in project_a can access modules in foo by using import foo.foostuff and the package will know how to resolve the location. Greg Fortune Miki Tebeka wrote: > Hello Eugene, >> Trying to reuse the code I found a problem (with Python or me) where >> if I have for example, a foo package in two separate directories >> (where foo/ contains common files and foo/project_a/ contains >> project-specific files) I can't load from both. >> >> If I put the common path first in the sys.path it tries to load the >> project-specific stuff from there too. If I try putting the >> project-specific one first it can't find the common stuff. >> >> Anyone know of a good solution for this problem? > Doesn't > > sys.path.append('/somedir/foo') > sys.path.append('/somedir/foo/project_a') > import foostuff > import projectstuff > > works? > > Miki From mhuening at zedat.fu-berlin.de Wed Sep 18 09:38:32 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 18 Sep 2002 13:38:32 GMT Subject: BibTeX module? Message-ID: Hi, I am looking for a simple BibTeX module, allowing me to read and manipulate/convert a bibliography file. Thanks, Matthias From max at alcyone.com Mon Sep 23 20:45:00 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 23 Sep 2002 17:45:00 -0700 Subject: Python quote in cgi References: Message-ID: <3D8FB58C.53EF8CBE@alcyone.com> CheapSkate wrote: > Hi, this might have been discussed b4, > can someone clarify for me, when writing cgi script in python, > does ' = """ > eg > > print """Main""" > > print 'Main' > > are they both the same? Yes. Triple quotes allow you to embed either form of single-character quote in them, and additionally triple quotes can span multiple lines (though in your example they don't). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Ride / Ride this wave of mine \__/ Res Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/ A highly categorized list of Web links. From thehaas at binary.net Thu Sep 26 13:02:01 2002 From: thehaas at binary.net (thehaas at binary.net) Date: Thu, 26 Sep 2002 17:02:01 GMT Subject: shell script in distutils Message-ID: I'm taking over someone else open-source app which is python-based, but is invoked by a shell script. What the shell script does is cd to the install directory and run "python scriptname.py". It's not a bad solution at all. However, they a Makefile to control installation and to make the rpm's. I would like to change it to use distutils. I have it already recognizing the scripts, but how to I get distutils to put the shell script in a different directory than the Python scripts?? Am I making any sense here?? if not, let me know and I will clarify . . -- mikeh -- Mike Hostetler thehaas at binary.net http://www.binary.net/thehaas GnuPG key: http://www.binary.net/thehaas/mikeh.gpg From aleax at aleax.it Wed Sep 18 17:02:32 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 21:02:32 GMT Subject: Is there a list comprehension to do this? References: Message-ID: Joe Sixpack wrote: > Is there a list comprehension or other 'cleaner' or 'prettier' way > to do the following: > >>>> xx = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) >>>> ww = [] >>>> for i in range(0, len(xx), 2): > ww.append((xx[i+1],xx[i])) > >>>> ww > [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)] Sure, you can always use a list comprehension in lieu of a loop that builds a list by calling .append -- a mechanical transcription: ww = [(xx[i+1],xx[x]) for i in range(0, len(xx), 2)] In Python 2.3, where lists finally support generalized slicing: ww = zip(xx[1::2],x[::2]) but that doesn't work in 2.2 and earlier, alas. Alex From jepler at unpythonic.net Mon Sep 30 23:03:57 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 30 Sep 2002 22:03:57 -0500 Subject: Reloading a module In-Reply-To: References: Message-ID: <20020930220356.A14365@unpythonic.net> On Tue, Oct 01, 2002 at 02:16:15AM +0000, Tom wrote: > I wish it were that simple. I've used reload(module) many times, each > time hoping that it would do what the documentation says it will do. > I've tested it by adding a simple variable to my module, watching to see > if it shows up in the new import, but it never does. I noticed also that > sometimes it reloads from the .pyc file, and if the reload happens > before the .pyc file is updated with the new changes, the changes won't > be available. Even if I force a reload from the updated .py file by > deleting .pyc file, it still retains the old code. I'm at a loss to > understand what's going on. # silly.py print "That's silly -- and a bit suspect, I think" Python 2.3a0 (#1, Jul 13 2002, 09:27:09) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import silly That's silly -- and a bit suspect, I think >>> (editing the file: # silly.py print "spam spam spam spam spam" ) >>> reload(silly) spam spam spam spam spam >>> As for .pyc vs .py, Python follows these steps when importing a module: if a .pyc file exists, read the magic number, version, and the stored timestamp. Compare the version to this Python version, and the stored timestamp to the .py file's timestamp. If these both match, or the version matches and the .py file doesn't exist, use the .pyc file. otherwise, compile the .py file and rebuild the .pyc file along the way The only circumstance that would interfere with this is NFS or another network filesystem making the check of the timestamp on the .py file unreliable---i.e., python can fail to detect that the .py file has been updated, because the OS gives it stale data. Using a filesystem that has no timestamp at all (or a very granular timestamp, so that two revisions of "silly.py" could share the same timestamp) could cause the same problem, though I don't know of any such filesystems offhand. (That said, I rarely actually notice problems of this type over NFS) It's possible that you've discovered some sort of new problem with the way .pyc caching or reloading work, but the idea is so simple that I can't see it failing... Jeff From sholden at holdenweb.com Fri Sep 27 09:59:49 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 27 Sep 2002 09:59:49 -0400 Subject: How to upload a file using http protocol References: Message-ID: > "A" wrote in message > news:mailman.1032552637.6156.python-list at python.org... > > Hi, > > Does anyone know how to upload a file through HTTP protocol?Is that a > possible? > > Thank you for help. > > ladislav > > "DeepBleu" top-posted ... > Yes it is. Assume that the user has to enter the file name (with the path) > on a form. You use File type form element which allows the user to browse > for the file. Technically, what you need is an element with the TYPE="FILE" attribute. You may also need to make sure that you have the correct MIME type (Content-Type: multipart/form-data). You may want to read http://www.ietf.org/rfc/rfc2388.txt to get the details absuolutely right, but it might be easier just to try a few options until it works... > Using CGI module, and a Submit button (or some javascript with a submit > function) this form element has a KEY. The VALUE of this key is the Byte > content of the file, NOT the file name. Thus, by using the VALUE KEY, the > server is actually receiving the byte content. From there on, the sky is > the limit. > DeepBleu > Read the CGI module's documentation to determin how to read the content. regards Steve From martin at v.loewis.de Mon Sep 16 17:50:40 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Sep 2002 23:50:40 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> Message-ID: Ian Bicking writes: > I don't think this represents the current state of Stackless -- > Christian has tried to get it into the standard Python, and it is not > for lack of desire or effort that that did not happen. I think it could > be considered a difference of opinion between him and Guido -- in part, > Stackless introduces more complexity which Guido did not want to > maintain, and in part because Stackless is not portable to forms of > Python (not to Jython in particular, and certainly any .NET Python -- > probably a Parrot Python as well). > > So the issue is primarily technical/political, and not a matter of > resources. It's definitely not political, and certainly not the "current state". I looked at the old Stackless patches once, and spotted significant amounts of unexplicable code - code that did not serve any obvious purpose, was not documented, or clearly should have been removed. So the old Stackless patch was incomplete for integration into Python - it would have taken efforts to complete it, and to work with Python maintainers to integrate it. Nobody went through this effort (and again, I don't blame anybody for not doing that). >From a shallow inspection, the code merely looked complex - but it really was complicated, and complex is better than complicated. However, this is *not* the current state. The current implementation (which I have not reviewed, yet) supposedly is much simpler, so past experience with trying to integrate it does not apply. Regards, Martin From fgeiger at datec.at Thu Sep 5 01:55:50 2002 From: fgeiger at datec.at (F. GEIGER) Date: Thu, 5 Sep 2002 07:55:50 +0200 Subject: Does BlackAdder really suck? References: Message-ID: > The NT box? Wise decision LOL. No. Yet I can't be w/o NT. But w/o BlackAdder I can be very well. > Yes. It seems to support wxSizers only, which IMO is relatively easy to do > with just Vim + Python already. So, what's your problem? Regards Franz GEIGER From mcfletch at rogers.com Thu Sep 26 21:13:08 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 26 Sep 2002 21:13:08 -0400 Subject: Help! This is driving me insane! References: Message-ID: <3D93B0A4.6060103@rogers.com> You do two prints: [0, 0] [0, 0] Then somehow or another you're getting the result of the whole method-invocation printed (likely by the interactive interpreter), which is: [[1,1]] After the method has returned, your "grouptotalcounter" code has been called, so there's no mystery there for Python peoples. The list grouptotal's values were updated, just as your method said to do, and that list is the first item in the errorlog list you returned. I _think_ the problem you're having is that you're thinking by appending the list object to self.errorlog you are somehow "fixing" the values in the list object as those when appended (which is something you would see in, for example C, where you were assigning to arrays). i.e. a = [] b = [1,2] a.append(b) b[0] = 3 would end with a == [[3,2]] and b == [3,2]. Because a[0] _is_ b, _not a copy_ of b. That is, a[0] is the same _object_ as pointed to by b, so any changes to b after adding it to a will show up in a (since it's just pointing to same list b). Try using a.append( b[:] ) if you want to append a copy of b, rather than the original list. Note, however, that if you're doing nested lists: a = [[],[],[]] You'll want to use the copy module explicitly for creating copies (otherwise only the top-level list is copied, the lower-level lists are still just referenced in the new list). HTH, Mike kara.klosterman wrote: ... > http://www.geocities.com/dbasch/insane.txt > > I would expect to get: > [0, 0] > [0, 0] > [[0, 0]] > > but I am getting: > [0, 0] > [0, 0] > [[1, 1]] > > I dont understand how the 'grouptotals' list is > getting the incremented values prior to the > 'grouptotalcounter' function being called. > furthermore, I can place a 'print grouptotals' right > after the errorlog append and it isnt the incremented > values! Please tell me this isnt a normal thing! > Thanks, > Derek Basch > > > -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From drifty at bigfoot.com Tue Sep 17 15:50:05 2002 From: drifty at bigfoot.com (Brett C.) Date: 17 Sep 2002 12:50:05 -0700 Subject: Python-dev summary for 2002-09-01 to 2002-09-15 Message-ID: This is a summary of traffic on the `python-dev mailing list`_ between September 01, 2002 and September 15, 2002 (exclusive). It is intended to inform the wider Python community of ongoing developments on the list. To comment on anything mentioned here, just post to python-list at python.org or comp.lang.python in the usual way. Give your posting a meaningful subject line, and if it's about a PEP, include the PEP number (e.g. Subject: PEP 201 - Lockstep iteration) All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on a PEP (or anything else for that matter) if you have an opinion. This is the second summary written by Brett Cannon (hopefully my sophomoric performance will be better then most sophomore music albums). Summaries by me (2002-09-15 to ... when I burn out) are archived at: http://www.ocf.berkeley.edu/~bac/python-dev/summaries/index.php You can find summaries by Michael Hudson (2002-02-01 to 2001-07-05) at: http://starship.python.net/crew/mwh/summaries/index.html Summaries by A.M. Kuchling (2000-12-01 to 2001-01-31) are at: http://www.amk.ca/python/dev/ Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sourceforge.net/rst.html . Any unfamiliar punctuation is probably markup for reST; you can safely ignore it (although I suggest learning reST; its nice and is accepted for PEP markup). Also, because of the wonders of reformatting thanks to whatever you are using to read this, I cannot guarantee you will be able to run this text through DocUtils as-is. If you want to do that, get the original text from the archive. I am considering keeping a list of names that people are often referred to in emails. This would serve a dual purpose: allows people who read emails from the list to have a reference to be able to figure out who is who and makes the summaries easier for me because I can then make reference to people by the names I know them by. =) Any comments on this idea are appreciated. .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _reST: .. _reStructuredText: http://docutils.sf.net/ ============================ `To commit or not commit`_ ============================ Walter Dorwald asked if there were "any objections against committing the patch" for implementing `PEP 293`_ (Codec Error Handling Callbacks). Guido asked what Martin V. Lowis and M.A. Lemburg had to say about it. MAL responded that he was +1 on the patch. Martin was "concerned about the massive amounts of C code, most of which could be expressed way more compact in Python code", but "Walter convinced [MvL] that this does have a real performance impact for real data" so he would live with it. In the end he gave it his vote. Walter said he would check it in (and he has). The PEP has now been moved to the finished PEP list. .. _To commit or not commit: http://mail.python.org/pipermail/python-dev/2002-September/028502.html .. _PEP 293: http://www.python.org/peps/pep-0293.html ======================================= `Proposed Mixins for Wide Interfaces`_ ======================================= Raymond Hettinger suggested adding mixin classes that automatically implement magic methods when certain basic magic methods were already implemented (e.g., "given an __eq__ method in a subclass, adds a __ne__ method"). David Abrahams said that he thought "these are a great idea, *in the context of* an understanding of what we want interfaces to be, say, and do." Guido brought up some points about the initial suggestions Raymond made. He then said that he thought that there wasn't "enough here to warrant putting this into the standard library"; the issue will be revisited when a standard type or interface hierarchy is added to Python (not in 2.3). .. _Proposed Mixins for Wide Interfaces: http://mail.python.org/pipermail/python-dev/2002-September/028543.html =================================== `mysterious hangs in socket code`_ =================================== Jeremy Hylton wrote some threaded code to fetch some web pages that hung when performing a slow DNS operation. Apparently, in Python 2.1 "it produces a steady stream of output -- urls and the time it took to load them". In Python 2.2 and 2.3, though, "it produces little bursts of output, then pauses for a long time, then repeats". Jeremy guessed that it *might* have something to do with Linux's getaddrinfo() being thread-safe by allowing only a single lookup at a time. Aahz said that "gethostbyname() IIRC has frequently been non-reentrant". .. _mysterious hangs in socket code: http://mail.python.org/pipermail/python-dev/2002-September/028555.html ======================================== `Two random and nearly unrelated ideas`_ ======================================== Skip Montanaro had two ideas; one was to make the info in `Misc/NEWS`_ (which is a summary of what has been changed in Python for each release) a web page and the other was "to get rid of the ticker altogether in systems with proper signal support" (see the `2002-08-16 - 2002-09-01 summary`_ for an explanation of what the ticker is). That would get rid of the polling of the ticker and thus reduce the overhead on threads. For the first idea, Guido asked Skip to try seeing what it would look like with reST_ markup and what the resulting page would look like. In response to the second idea, Oren Tirosh said it couldn't be done until "all Python I/O calls are converted to be EINTR-safe" (EINTER-safe means to be able to handle the EINTER signal which what is raised "When an I/O operation is interrupted by an unmasked signal"). That "requires a lot of work in some of the hairiest places in the Python codebase." Fredrik Lundh said that this "sounds like a good topic for a "here's what I learned when trying to fix this problem" PEP. This is most likely in reference to Skip writing the patch to make the ticker global instead of a per-thread issue. Guido said, in terms of signals, to "just say no"; "it is impossible to write correct code in the presense of signals". Guido, in a later email, gave this whole idea a vote of -1,000,000; so it ain't ever going to happen. Some discussion on signals ensued, but Guido never budged from his position. Oren pointed out that if some C code used signals and people didn't handle it in their Python code by checking if IOError was caused by EINTER (as shown below by Oren's code):: while 1: try: except IOError, exc: if exc.errno == errno.EINTR: continue else: raise , it would not restart properly even though there was no reason for it to have stopped. Oren said that Python could add the loop in the C code of the core where EINTR might be raised ("Only low-level functions like os.read_ and os.write_ that map directly to stdio functions should ever return EINTR"). The proposed idea was to wrap functions that might raise this that can be re-entered safely. .. _Two random and nearly unrelated ideas: http://mail.python.org/pipermail/python-dev/2002-September/028555.html .. _Misc/NEWS: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Misc/NEWS .. _2002-08-16 - 2002-09-01 summary: http://www.ocf.berkeley.edu/~bac/python-dev/summaries/2002-08-16--2002-09-01.html .. _os.read: .. _os.write: http://www.python.org/dev/doc/devel/lib/os-fd-ops.html ================================================ `Should KeyError use repr() on its arguments?`_ ================================================ Originally, when an exception was raised and you passed in an optional object to act as a description of why the exception was raised (such as ``KeyError("there is no spoon")`` where ``there is no spoon`` is the optional argument bound to ``.args``), it just returned what args was bound to when you called; ``str() == .args``. Now it calls repr() on what args is bound to; ``str() == str(.args)``. Much better. =) .. _Should KeyError use repr() on its arguments?: http://mail.python.org/pipermail/python-dev/2002-September/028545.html ========================================== `New 'spambayes' project on SourceForge`_ ========================================== Thanks to great work done by Tim Peters and several other contributors, Barry Warsaw started an SF project to host the spambayes code. It can be found at http://sf.net/projects/spambayes . There are two mailing lists: http://mail.python.org/mailman-21/listinfo/spambayes and http://mail.python.org/mailman-21/listinfo/spambaye-checkins (yes, that is Mailman 2.1, and yes, you will "help be a guinea pig for Mailman 2.1"). .. _New 'spambayes' project on SourceForge: http://mail.python.org/pipermail/python-dev/2002-September/028626.html ========================= `Subsecond time stamps`_ ========================= Martin V. Lowis wanted to introduce subsecond timestamps on platforms that supported it. He suggested adding another field to stat, create a new type, or make st_mtime a floating point. The first one option is easy, the second has the usual problems of defining a new type, and the third does not guarantee enough accuracy. Paul Svensson and Guido said that the last option (turning st_mtime into a float) was the most Pythonic. MvL agreed, but worried about breaking code that expected an int. Guido then suggested that maybe the new field is the way to go; define something like st_mtimef that will contain the float if available or contain an int otherwise. Tim Peters also weighed in with his `IEEE 754`_ voodoo about how a float can hold enough info to be accurate up to 100 nanoseconds if you only span a 33 years. That causes an issue starting in 2003 since that is 33 years past the epoch (1970). But then MvL discovered that st_mtime was already a float on the Mac; had that caused issues? Jack Jansen of course chimed in on this by saying that it caused him a headache about once a year in the form of a failing test (other issues caused by timestamps is the Classic Macs having the epoch at 1904 and not using UTC time). He said he would prefer to see the timestamp as a cookie that was passed into a function that spit out "something guaranteed to be of your liking". To address the other issues that Jack mentioned, Guido suggested that all timestamps be converted to UTC time with the epoch at 1970. MvL has `SF patch 606592`_ up on SF that has already been closed that makes all the relevant changes to have timestamps return floats. .. _Subsecond time stamps: http://mail.python.org/pipermail/python-dev/2002-September/028648.html .. _IEEE 754: http://grouper.ieee.org/groups/754/ .. _SF patch 606592: http://www.python.org/sf/606592 ================================= `64-bit process optimization 1`_ ================================= Bob Ledwith posted a simple patch for `Include/object.h`_ that changed the order of certain parts of the PyObject_HEAD macros, affecting PyObject and PyVarObject. This was for a 64-bit platform performance boost (40% for large data sets according to Bob). The reordering eliminated some padding in the struct and allows more Python objects to fit in the L2 cache, or at least that is what Bob thinks is going on. Guido pointed out that this would save 8 bytes per object; he thought all of this was "Interesting!". But alas, using this patch would break binary compatibility. Guido was not sure, though, whether it had been broken yet between Python 2.2 and 2.3 and thus he might be "being too conservative here" in terms of saying that it should be held back for now. A problem Guido pointed out for 64-bit systems, is that theoretically the reference count for an object could go negative with enough references as things stand now. Guido then suggested that perhaps refcnt (struct item that holds the reference count) should be a ``long``. And while dealing with that, Guido suggested that anything that stores a length should store that number in a ``long``. Chime in Tim Peters. He pointed out that it was agreed upon years ago to move refcnt to ``long`` but no one had bothered to do it. Heck, even Guido thought for a long time that it was a long when it wasn't; it required Tim to "beat that out of [Guido] " to stop him from saying that it was a ``long``. He then pointed out that Win64 was still only 4 bytes for a ``long``; what was really desired was for it to be ``Py_intptr_t`` which is the Python way for spelling the C99 type that we wanted. Apparently C99 has a way to specify that things be a specific byte length (now if everyone just had a C99 compiler we wouldn't need these macros; oh, to dream...). Tim also pointed out that what we wanted for the type that held a length argument to be size_t since that is what strlen() and malloc() are restricted by. He said that he writes all of his "string-slinging code as using size_t vars now". Tim pointed out that the issue then became "Whether it's worth the pain to change this stuff" which "depends on whether we think 64-bit boxes are just another passing fad like the Internet ". =) Martin V. Lowis agreed with the changing of refcnt to a long but had reservations about using size_t for the length field (ob_size). He pointed out that some objects put negative values into that field. Frederik suggested that the proposed changes be default on 64-bit systems since the chances that they are willing to recompile is higher then people on 32-bit systems. He also suggested making it a compiler option. Guido thought it was a good idea. But then Mats Wichmann discovered that the switch to long killed the performance boost. So Guido re-iterated that he thinks it should be a compiler option only on 64-bit systems; have "compat", "optimal", and "right" compiler options. As of yet nothing has done about this. .. _64-bit process optimization 1: http://mail.python.org/pipermail/python-dev/2002-September/028677.html .. _Include/object.h: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Include/object.h ========================================== `Weeding out obsolete modules and Demos`_ ========================================== Jack Jansen noticed that there demos for some of the SGI-specific modules that use severely outdated systems and hardware (stuff discontinued 8 to 12 years ago). Guido gave the go-ahead to yank them from CVS. This has yet to be done. .. _Weeding out obsolete modules and Demos: http://mail.python.org/pipermail/python-dev/2002-September/028718.html ============== `utf8 issue`_ ============== (This thread actually started in August) There was a bug in Python 2.2 that raised a UnicodeError when trying to decode a lone surrogate (explanation of surrogates to follow this summary). This caused issues in importing .pyc files that contained a lone surrogate because marshal_ (which is what is used to create .pyc files) encodes Unicode_ literals in UTF-8. This has all been fixed in Python 2.3, but Guido was wondering how to backport this for Python 2.2.2. The option of bumping the magic number for .pyc files was raised and instantly thrown out by Guido; "Bumping MAGIC is a no-no between dot releases". So M.A. Lemburg suggested to either fix the Unicode encoder or change the Unicode decoder to handle the malformed Unicode. MAL wasn't sure, though, if some security issue would be raised by the latter option. Guido said go for the latter and didn't see any possible security issue since "If someone you don't trust can write your .pyc files, they can cause your interpreter to crash by inserting bogus bytecode". Explanation of lone surrogates: In Unicode, a surrogate pair is when you create the representation of a character by using two values. So, for instance, UTF-32 can cover the entire Unicode space (since Unicode is 20 bits, although MvL says it is really more like 21 bits), but UTF-16 can't. To solve the issue for an encoding that cannot cover all possible characters in a single value a character can be represented as a pair of UTF-16 values. The high surrogate cover the high 10 bits while the low surrogate cover the lower 10 bits. High and low surrogates can never be the same since they are defined by a range of possible values and those ranges do not overlap. So with the proper high and low surrogate paired together you can make any possible Unicode character. The problem in Python 2.2.1 is that when there is only a lone surrogate (instead of there being a pair of surrogates), the encoder for UTF-8 messes up and leaves off a UTF-8 value. The following line is an example: >>> u'\ud800'.encode('utf-8') '\xa0\x80' #In Python 2.2.1 '\xed\xa0\x80' #In Python 2.3a0 Notice how in Python 2.3a0 the extra value is inserted so as to make the representation a complete Unicode character instead of only encoding the half of the surrogate pair that the encode was given. You can read http://216.239.37.100/search?q=cache:Dk12BZNt6skC:uk.geocities.com/BabelStone1357/Software/surrogates.html for more info. Thanks goes to Frederik for the link and Guido for some clarification. .. _utf8 issue: http://mail.python.org/pipermail/python-dev/2002-August/028254.html .. _marshal: http://www.python.org/dev/doc/devel/lib/module-marshal.html .. _Unicode: http://www.unicode.org/ ===================================== `Documentation inconsistency in re`_ ===================================== Christopher Craig noticed that the docs for the re_ module for the ``\b`` metacharacter was incorrect; it says that "the end of a word is indicated by whitespace or a non-alphanumeric character". That would indicate that an underscore would be the end of a word, which turns out to be false. Frederik said that "\b is defined in terms of \w and \W" and thus allows underscore to be a alphanumeric character. The documentaiton has been fixed. .. _Documentation inconsistency in re: http://mail.python.org/pipermail/python-dev/2002-September/028644.html .. _re: http://www.python.org/dev/doc/devel/lib/module-re.html ======================= `Codecs lookup order`_ ======================= Francois Pinard discovered that for the codecs_ module "one should be careful about **not** [altered emphasis] naming a module after the encoding name, when closely following the documentation in the Library Reference manual". This is because the codecs module first searches the registry of codecs, then searches for a module with the same name and use that module. The issue comes up when the module does not contain a function named getregentry(); "\`encodings.lookup()` expects a \`getregentry` function in that module, does not find it, and raises a CodecRegistryError, not leaving a chance to subsequent codec search functions to be used". M.A. Lemburg said that this has been fixed in Python 2.3 and will be in 2.2.2 by having encodings.lookup() return None if getregentry() is not found and thus allowing the search to continue. .. _Codecs lookup order: http://mail.python.org/pipermail/python-dev/2002-September/028676.html .. _codecs: http://www.python.org/dev/doc/devel/lib/module-codecs.html ================================= `raw headers in rfc822.Message`_ ================================= John Spurling provided a two-line hack to keep the raw headers in an rfc822.Message_ . Barry responded that email.Message.Message_ keeps the raw headers around. But the reason I am summarizing this is what this thread quickly changed to is how to properly generate a patch. Patches should be generated using UNIX diff, either the -c or -u option with preference for -c (using cvs diff -c is even better; puts the version of the file you are diffing with in the output); Mac folk can send MPW diffs, but UNIX diff is the definitely preference. Always put the order of the files ``diff -c OLD_FILE NEW_FILE`` . And always post the patches_ to SourceForge_! Getting random patches, no matter how small, on the list is annoying (at least to me) because the point of the list is to discuss the design and implementation of Python, not to patch Python. SF is used so that Python-dev does not need to be bothered with mundame problems like applying patches (and to annoy Aahz with SF's UI sucking in Lynx_ =). So please, for my sake and everyone else on Python-dev, use SF! For a funny email from Raymond Hettinger about developing for Python read http://mail.python.org/pipermail/python-dev/2002-September/028725.html . .. _raw headers in rfc822.Message: http://mail.python.org/pipermail/python-dev/2002-September/028682.html .. _rfc822.Message: http://www.python.org/dev/doc/devel/lib/message-objects.html .. _email.Message.Message: http://www.python.org/dev/doc/devel/lib/module-email.Message.html .. _patches: http://sourceforge.net/patch/?group_id=5470 .. _SourceForge: http://www.sourceforge.net/ .. _Lynx: http://lynx.browser.org/ =================== `type categories`_ =================== Yes, the `same thread`_ from the `last summary`_ is back. This thread has become the bane of my summarizing existence. =) Aahz asked "why wouldn't we simply use attributes to hold" interfaces that a class implemented (think of __slots__). David Abrahams then brought up the idea of just adding interfaces to the __class__ attribute. Guido then chimed in on the attributes idea. He pointed out that this is how Zope does it, using the __inherits__ attribute. The limitation is that "it isn't automatically merged properly on multiple inheritance, and adding one new interface to it means you have to copy or reference the base class __inherits__ attribute". And as for David's idea of just adding to __class__, that doesn't work because there is no way to limit the interface; you need "Something like private inheritance" for when an interface is broken by some inherited class. David subsequently added the issue of being able to disinherit when an interface is not valid but is inherited by default as another problem for using inheritence for interfaces. David then brought up the issue of having Python being so dynamic that you could inject an interface if you used __class__ like he suggested through black magic code. If the injected interface didn't work because of the inheritence chain, then you have a problem. Barry Warsaw brought in his objections. He tried playing Devil's Advocate by saying that Guido had said that inheritance would not be the only way to handle interfaces, but that it would be the predominent way. But this duality would complicate any conformsto()-like function since it would have to handle two different ways for a class to get an interface. Barry then brought up the objection that he didn't like the idea of using straight inheritence because he wanted a syntactic way to separate out interfaces. As a side note, Guido pointed out that __slots__ is provisional; nicer syntax will eventually surface when Guido gets over his "fear of adding new keywords". .. _type categories: http://mail.python.org/pipermail/python-dev/2002-September/028738.html .. _same thread: http://www.ocf.berkeley.edu/~bac/python-dev/summaries/2002-08-16--2002-09-01.html#type-categories .. _last summary: http://www.ocf.berkeley.edu/~bac/python-dev/summaries/2002-08-16--2002-09-01.html ======================================= `flextype.c -- extended type system`_ ======================================= Christian Tismer has come up with a replacement for the etype which is "a hidden structure that extends types when they are allocated on the heap" (you can find it in `Objects/typeobject.c`_ in the CVS_). There is a limitation with the etype where it could not be extended by metatypes. Well, Chris worked his magic and came up with a new flextype that allows overriding of methods. So with Christian's code you would be able to override methods in a type without having to hack something together to handle the overriding correctly; it would be handled automatically. Through some clarification from Christian and Guido, it was pointed out to me (as of this moment I am the only one to make any noise on this thread, and it was for this summary) that this simplifies an esoteric issue; note the use of the words "metatype" above. This is type/metatype black magic hacking. Spiffy, but something most of us "normal" folk will not have to worry about. .. _flextype.c -- extended type system: http://mail.python.org/pipermail/python-dev/2002-September/028736.html .. _Objects/typeobject.c: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/typeobject.c .. _CVS: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/#dirlist From rajarshi at presidency.com Mon Sep 9 16:10:39 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Mon, 09 Sep 2002 16:10:39 -0400 Subject: a re question Message-ID: Hi, I have a file with lines of the format: 001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23 001 Xya FGh 143557789 7 100 09/05/2002 20:23:23 I am trying to extract the 9 digit field and the single digit field immediatley after that. When I use Visual Regexp to try out the regexp (\d{9,} {3,}\d) it highlights the 2 fields exactly. But when I use the following Python code I get None: >> s='001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23' >> p = re.compile(r'(\d{9,} {3,}\d)') >> print p.match(s) >> None Could anybody point out where I'm going wrong? Thanks, From wanner.dx at mellon.com Wed Sep 11 08:57:18 2002 From: wanner.dx at mellon.com (dxterra) Date: 11 Sep 2002 05:57:18 -0700 Subject: file upload using msvcrt Message-ID: I am trying to upload msword docs to my webserver. Here is the code that I am using: #!I:\Python22\Python -u # $Header: $ # $Log: $ import cgi, sys, string, time, types, os import posixpath, dospath, macpath import msvcrt msvcrt.setmode(0, os.O_BINARY) msvcrt.setmode(1,os.O_BINARY) from pso.service import ServiceHandler # allows for more verbose feedback when a cgi exception occurs import cgitb cgitb.enable() sys.stderr = sys.stdout UPLOAD_DIR = "o:\\upload" def splitpath( orig_path ): for pathmodule in [posixpath, dospath, macpath]: basename = pathmodule.split(orig_path)[1] if basename != orig_path: return basename return orig_path def save_file(fileinfo): basename = splitpath( fileinfo.filename) srvrname = os.path.join(UPLOAD_DIR, basename ) msvcrt.setmode(0, os.O_BINARY) msvcrt.setmode(1,os.O_BINARY) fp = file( "s:\\cgi-bin\\project\\log.lis", "a+" ) fp.write( "saving file '%s' as '%s'\n" % (fileinfo.filename, srvrname) ) fp.write( "file contents %s\n" % fileinfo.value ) fp.write( "file size as read from stdin '%s'\n" % ( len(fileinfo.value) ) ) fp.write( "file mode in '%s' file mode out '%s'\n" % (sys.stdin.mode, sys.stdout.mode ) ) fp.close() srvrfile = file(srvrname, "wb" ) while 1: data = fileinfo.file.read( ) if not data: break srvrfile.write(data) return fileinfo.filename def upload_file(): form = cgi.FieldStorage() msgs = [] fileinfo = None for field in form.keys(): if field == "zzz": if not form[field].filename: msgs.append( "ERROR: filename is missing" ) else: fileinfo = form[field] fp = file( "s:\\cgi-bin\\project\\log.lis", "a+" ) fp.write( "attachment filename is '%s'\n" % (fileinfo.filename) ) fp.close() if fileinfo is not None: fp = file( "s:\\cgi-bin\\project\\log.lis", "a+" ) fp.write( "preparing to save attachment '%s'\n" % (fileinfo.filename) ) fp.close() srvrname = save_file(fileinfo) # process the form data for msg in msgs: print '
%s
' % (msg) if __name__ == '__main__': upload_file() I cannot get the binary file to write. It get to about 8k and then stops. When I query the mode it always says 'r' for stdin and 'w' for stdout. Can anyone help me? From syver-en+usenet at online.no Mon Sep 16 11:06:58 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Mon, 16 Sep 2002 15:06:58 GMT Subject: python performance References: <3D84E66F.6020701@linux.ie> Message-ID: loewis at informatik.hu-berlin.de (Martin v. L?wis) writes: > Padraig Brady writes: > > > > Calling functions adds overhead. Running code within functions > > > reduces overhead for object access. > > > > Ah OK, this because it has to search a smaller namespace? > > No. Inside a function, local variables are accessed with integer > indices, instead of by name. This is possible because there is static > knowledge about the local variables in a function. > > > Wouldn't compiling overcome this? > > Not if you want to preserve Python semantics; the compiler would need > to emit code that performs the same actions that the interpreter > currently does. What about Psyco? -- Vennlig hilsen Syver Enstad From jeremy at jdyallop.freeserve.co.uk Tue Sep 3 04:03:49 2002 From: jeremy at jdyallop.freeserve.co.uk (Jeremy Yallop) Date: 3 Sep 2002 08:03:49 GMT Subject: getch in python References: <75ca4e69.0209022326.4cde72e8@posting.google.com> Message-ID: * Venkat Venkataraju | Is there any function that behaves like getch() function in C? I'd say that getch() is probably the closest. It's a method of the window class in the curses module: http://www.python.org/doc/current/lib/curses-window-objects.html There are some demos that use it in the Demo/curses directory of the Python distribution. Jeremy. From tjreedy at udel.edu Sat Sep 21 14:50:08 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 21 Sep 2002 18:50:08 GMT Subject: filter(lambda W : W not in 'ILLITERATE','BULLSHIT') (Re : python expression) References: <3D86FF01.FE0CECC5@geneva-link.ch> <3d87069c.34652637@news.rcn.com> <3D871316.AA1E8FFC@geneva-link.ch> <3d882cd4.9181792@news.rcn.com> <3f74f974.0209180713.27889f74@posting.google.com> <3d88c258$0$707$5402220f@news.sunrise.ch> <3d89be92$0$707$5402220f@news.sunrise.ch> <3d89ee85$0$712$5402220f@news.sunrise.ch> <3d8b4498$0$717$5402220f@news.sunrise.ch> <3d8c6982$0$719$5402220f@news.sunrise.ch> Message-ID: "Boris" wrote in message news:3d8c6982$0$719$5402220f at news.sunrise.ch... > > Terry Reedy a ?crit dans le message : > WSLi9.165658$z91.6788612 at bin3.nnrp.aus1.giganews.com... > > "Boris" > > > > > > filter(lambda W : W not in 'ILLITERATE','BULLSHIT') > > > > This somewhat-well-known and certainly well-worn programmer joke > > Well, *I* invented this formula myself soon after Mr Bush revealed to > the world that "USA" is written in "CRUSADE" just like "US" is in > "BUSH". Adding : "Either you are with US, or you are against US". Congratulations on your cleverness. You have used it as your signature over 20 times on this mail-list/newsgroup so it is somewhat familiar to me and, I presume, to other regular readers According to google, you seem to have used it at least once in at least 10 other newsgroups(and a few more with this posting), but pardon me for overestimating its well-knownness outside the confines of Pythonland. ---- >> and the presence of very un-Pythonic ugliness > Ah, you are an aesthetician of pythonicity Yes. To quote from the post where you added c.l.p to the newgroup list: """ Malev : [after accusing me of an opaque vice on the basis of an incompetent interpretation of the headers of his copy of my post] > > >by this channel. This really has nothing to do with me. You should > >abstain from reading technical small print if it's beyond your ability > >to interpret it adequately. > > Pompous patronizing fool. I prefer that to being the unrepenting "innocent" liar that you are, """ Again, this sort of personal attack and counterattack has nothing to do with Python and is contrary to the generally friendly spirit here. I consider it ugly and make no apology for stating so. > But then, what's your competence to formulate such assertions ? My humanity and at least 5 1/2 years of participation here. Terry J. Reedy From jkraska at san.rr.com Mon Sep 23 02:15:31 2002 From: jkraska at san.rr.com (Courageous) Date: Mon, 23 Sep 2002 06:15:31 GMT Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> Message-ID: >Using *tabs* only is the only way to get truly >preference-independent indentation. But makes impossible certain constructs that involving lining indentation level up with specific items of text in surrounding lines, which actually matters. This is one of the reasons people often use mixed tabs and spaces. Here is an example: void MyFunction ( int a, char c, float f ); void MyFunction ( int a, char c, float f ); void MyFunction ( int a, char c, float f ); Furthermore, when you use only spaces, you can guarntee that all those reading will see it formatted as close to correctly as is possible. C// From michael.amrhein at t-online.de Sat Sep 21 11:45:05 2002 From: michael.amrhein at t-online.de (Michael Amrhein) Date: Sat, 21 Sep 2002 17:45:05 +0200 Subject: monetary applications [was: Python GUI app to impress the bos s?] References: Message-ID: <3D8C9401.4000805@t-online.de> Tim Peters wrote: > About http://starship.python.net/crew/aahz/FixedPoint.py > > If someone is willing and able to do the work (sorry, I can't make > time for it), Guido will accept this into the standard library for > 2.3. It's a small, self-contained, pure Python module; it's been in > use for a few years with no bugs reported; There was a short thread in this ng some months ago, where two bugs in FixedPoint.py were reported (incl. fixes). > and is unencumbered by any license (a lawyer has told > me that an individual in the USA cannot meaningfully disclaim > copyright, so fine, the copyright I didn't want is hereby transferred > to the PSF ). > > What work remains: > > + Write docs for the Library Reference manual. I expect the existing > module docstring will be a good start. > > + Create a test driver for Python's regression suite. > > + Have fun modernizing it, if you like (for example, "/" should be > changed to "//" where integer division is intended; playing with > __slots__ may yield some nice savings; whatever). > > This should be a fun and comparatively easy task -- if you ever > wanted to get your name into the ACKS file, here's one way to do it > without tithing you income directly to Guido . > > although-tithing-saves-me-time-ly y'rs - tim > > I've written a simular class named 'fixed' (see below) with portions adopted from your FixedPoint, but a slightly different constructor (no default precision; precision calculated from given value, if no precision given) and some additional functions. And, yes, it uses __slots__ and supports the new integer division. So, maybe, it could serve as the "modernized" version you recommend in your third point. But, while willing to contribute it to the PSF, I just don't know what is required to do so. And because I've never written docs for the Library Reference nor created test drivers I'll need some guidance. Maybe, Doug can help with this. Cheers, Michael --- ##------------------------------------------------------------------------------ ## Name: fixedpoint.py ## Purpose: Decimal arithmetic with a fixed number of fractional digits ## ## Author: Michael Amrhein (michael.amrhein at t-online.de) ## ## Created: 2001-12-06 ## RCS-ID: $Id: fixedpoint.py,v 1.2 2002/06/15 12:26:58 am Exp $ ## Copyright: (c) Michael Amrhein ## Portions adopted from FixedPoint.py written by Tim Peters ## License: This program is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public ## License as published by the Free Software Foundation; either ## version 2 of the License, or (at your option) any later version. ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ## See the GNU General Public License for more details. ## You should have received a copy of the license text along with ## this program; if not, get it from http://www.gnu.org/licenses, ## or write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ##------------------------------------------------------------------------------ __version__ = 0, 9, 1 from __future__ import division class fixed(object): __slots__ = ['_value', '_precision'] # initialize fixed point number def __init__(self, value=0L, precision=None): """Set value adjusted to precision. Keyword arguments: value initial value (default: 0L) precision initial number of fractional digits (default: None) If precision is given, it must be of type int. If value is given, it must be of type fixed, string, float, long or int (or be convertable to float or long). If a string is given as value, it must be a string in one of two formats: [+|-][.][[e|E][+|-]] [+|-].[[e|E][+|-]] The value is always adjusted to the given precision or the precision is calculated from the given value, if no precision is given. """ if precision is not None: assert isinstance(precision, int), \ "Precision must be of ." assert precision >= 0, "Precision must be >= 0." if isinstance(value, fixed): vp = value._precision if precision is None or precision == vp: self._precision = vp self._value = value._value else: self._precision = precision if precision < vp: self._value = _shiftdecimal(value._value, vp - precision) else: self._value = value._value * 10L ** (precision - vp) return if isinstance(value, str): i, e = _string2exact(value) if i is None: raise TypeError, "Can't convert "+repr(value)+" to fixed." else: if precision is None: if e > 0: self._precision = 0 self._value = i * 10L ** e else: self._precision = abs(e) self._value = i else: self._precision = precision p = e + precision if p >= 0: self._value = i * 10L ** p else: self._value = _shiftdecimal(i, -p) return if isinstance(value, float): if precision is None: self._precision = vp = len(repr(value).split('.')[1]) self._value = long(round(value * 10L ** vp)) self.adjust() else: self._precision = precision self._value = long(round(value * 10L ** precision)) return if isinstance(value, (int, long)): if precision is None: self._precision = 0 self._value = long(value) else: self._precision = precision self._value = long(value) * 10L ** precision return # Coerce value to Float? ok = 1 try: v = float(value) except: ok = 0 if ok: self.__init__(v, precision) return # Coerce value to Long? ok = 1 try: v = long(value) except: ok = 0 if ok: self.__init__(v, precision) return # unable to create fixed raise TypeError, "Can't convert "+repr(value)+" to fixed." # copy instance def __copy__(self): return fixed(self) __deepcopy__ = __copy__ # return v, p so that self == v // 10 ** p and v % 10 != 0 def __reduce(self): sv = self._value if sv == 0L: return 0L, 0 sp = self._precision while sp and sv % 10L == 0L: sp -= 1 sv = sv // 10L return sv, sp # return _value adjusted to given precision def __get_adjusted_value(self, precision): p = precision - self._precision if p == 0: return self._value elif p > 0: return self._value * 10L ** p else: return _shiftdecimal(self._value, -p) # adjust precision def adjust(self, precision=None): """Adjust this fixed to the given precision. If the given precision is less than the current precision information may be lost. If no precision is given it is adjusted to the minimum precision preserving x == x.adjust(). """ if precision is None: self._value, self._precision = self.__reduce() else: assert isinstance(precision, int), "Precision must be of type Int." assert precision >= 0, "Precision must be >= 0." self._value = self.__get_adjusted_value(precision) self._precision = precision # return precision def getPrecision(self): """Return precision.""" return self._precision # string representation def __repr__(self): return "fixed('"+self.__str()+"')" # convert to string def __str(self): sp = self._precision if sp == 0: return str(self._value) else: sv = self._value s = str(abs(sv)) n = len(s) if n >= sp: return (sv<0)*'-' + s[0:-sp] + '.' + s[-sp:] else: return (sv<0)*'-' + '0.' + (sp-n)*'0' + s # convert to string (according to current locale) def __str__(self): from locale import format, localeconv sp = self._precision if sp == 0: return format("%d", self._value, 1) else: i = self.__long__() f = self.__frac() s = (i==0 and f<0)*'-' # -1 < self < 0 => i = 0 and f < 0 !!! return s + format("%d", i, 1) + localeconv()['decimal_point'] \ + format("%0*d", (sp, abs(f))) # compare to fixed or any type that can be converted to a fixed def __cmp__(self, other): if isinstance(other, fixed): p = max(self._precision, other._precision) return cmp(self.__get_adjusted_value(p), other.__get_adjusted_value(p)) elif other is None: return 1 else: return self.__cmp__(fixed(other)) # compute hash index def __hash__(self): sv, sp = self.__reduce() return hash(sv) ^ hash(sp) # return 0 or 1 for truth-value testing def __nonzero__(self): return self._value != 0L # return integer portion as long def __long__(self): sp = self._precision if sp == 0: return self._value else: sv = self._value result = abs(sv) // 10L ** sp if sv < 0: return -result else: return result # return integer portion as int def __int__(self): return int(self.__long__()) # return fractional portion as long def __frac(self): return self._value - long(self) * 10L ** self._precision # return fractional portion as fixed def frac(self): """Return fractional portion as fixed.""" return self - long(self) # convert to float (may loose precision!) def __float__(self): sv, sp = self.__reduce() return sv / 10L ** sp # positiv value def __pos__(self): return fixed(self) # negative value def __neg__(self): result = fixed(self) result._value = -result._value return result # absolute value def __abs__(self): result = fixed(self) result._value = abs(result._value) return result # self + other def __add__(self, other): if isinstance(other, fixed): p = self._precision - other._precision if p == 0: result = fixed(self) result._value += other._value elif p > 0: result = fixed(self) result._value += other._value * 10L ** p else: result = fixed(other) result._value += self._value * 10L ** -p return result else: return self.__add__(fixed(other)) # other + self __radd__ = __add__ # self - other def __sub__(self, other): if isinstance(other, fixed): p = self._precision - other._precision if p == 0: result = fixed(self) result._value -= other._value elif p > 0: result = fixed(self) result._value -= other._value * 10L ** p else: result = fixed(other) result._value -= self._value * 10L ** -p return result else: return self.__sub__(fixed(other)) # other - self def __rsub__(self, other): return self.__neg__().__add__(other) # self * other def __mul__(self, other): if isinstance(other, fixed): sp, op = self._precision, other._precision if sp >= op: result = fixed(self) result._value = _shiftdecimal(self._value * other._value, op) else: result = fixed(other) result._value = _shiftdecimal(self._value * other._value, sp) return result else: return self.__mul__(fixed(other)) # other * self __rmul__ = __mul__ # self / other def __div__(self, other): if isinstance(other, fixed): if other._value == 0L: raise ZeroDivisionError sp, op = self._precision, other._precision if sp >= op: result = fixed(self) result._value = _divdecimal(self._value * 10L ** op, other._value) else: result = fixed(other) result._value = _divdecimal(self._value * 10L ** (2 * op - sp), other._value) return result else: return self.__div__(fixed(other)) # other / self def __rdiv__(self, other): return fixed(other).__div__(self) # fixed division is true division __truediv__ = __div__ __rtruediv__ = __rdiv__ # self // other, self % other def __divmod__(self, other): if isinstance(other, fixed): if other._value == 0L: raise ZeroDivisionError sp, op = self._precision, other._precision if sp >= op: r = fixed(self) sv = self._value ov = other.__get_adjusted_value(sp) else: r = fixed(other) sv = self.__get_adjusted_value(op) ov = other._value q = sv // ov r._value = sv - q * ov return fixed(q, r._precision), r else: return self.__divmod__(fixed(other)) # other // self, other % self def __rdivmod__(self, other): return fixed(other).__divmod__(self) # self // other def __floordiv__(self, other): return self.__divmod__(other)[0] # other // self def __rfloordiv__(self, other): return self.__rdivmod__(other)[0] # self % other def __mod__(self, other): return self.__divmod__(other)[1] # other % self def __rmod__(self, other): return self.__rdivmod__(other)[1] # self ** other def __pow__(self, other): if isinstance(other, (int, long)): result = fixed(self) result._value = _shiftdecimal(self._value ** other, self._precision * (other - 1)) return result else: raise TypeError, "Exponent must be int or long." # return percentage of self according to rate def percent(self, rate): """Return percentage according to rate. x.percent(rate) = x * rate / 100 The result is returned as fixed with the same precision as self. """ if isinstance(rate, fixed): result = fixed(self) f = 10L ** (rate._precision + 2) result._value = _divdecimal(self._value * rate._value, f) return result else: return self.percent(fixed(rate)) # return net value of self according to rate def net(self, rate): """Return net value according to rate. x.net(rate) = x * 100 / (100 + rate) The result is returned as fixed with the same precision as self. """ if isinstance(rate, fixed): result = fixed(self) f = 10L ** (rate._precision + 2) result._value = _divdecimal(f * self._value, f + rate._value) return result else: return self.net(fixed(rate)) # return gross value of self according to rate def gross(self, rate): """Return gross value according to rate. x.gross(rate) = x * (100 + rate) / 100 The result is returned as fixed with the same precision as self. """ if isinstance(rate, fixed): result = fixed(self) f = 10L ** (rate._precision + 2) result._value = _divdecimal(self._value * (f + rate._value), f) return result else: return self.gross(fixed(rate)) # functions: # return percent value according to rate def percent(rate): """Return percent value according to rate. percent(rate) = rate / 100 The result is returned as fixed with precision of rate increased by 2. """ if isinstance(rate, fixed): r = rate else: r = fixed(rate) r._precision += 2 return r # helper functions: # divide x by y, return rounded result def _divdecimal(x, y): i, r = divmod(x, y) c = cmp(abs(2*r), abs(y)) if c > 0 or (c == 0 and i >= 0): # r > y/2 or r = y/2 and i not negative return i + 1 else: return i # shift decimal point left, return rounded result def _shiftdecimal(x, n): if n == 0: return x return _divdecimal(x, 10L ** n) # parse string import re _pattern = r""" \s* (?P[+|-])? ( (?P\d+)(\.(?P\d*))? | \.(?P\d+) ) ([eE](?P[+|-]?\d+))? \s*$ """ _parse = re.compile(_pattern, re.VERBOSE).match del re def _string2exact(s): m = _parse(s) if m is None: return None, None ep = m.group('exp') if ep: e = int(ep) else: e = 0 ip = m.group('int') if ip: fp = m.group('frac') else: fp = m.group('onlyfrac') if ip: i = long(ip) else: i = 0L if fp: f = long(fp) n = len(fp) else: f = 0L n = 0 i = i * 10 ** n + f e -= n if m.group('sign') == '-': i = -i return i, e From arosado at softhome.net Mon Sep 2 22:00:03 2002 From: arosado at softhome.net (Andres Rosado) Date: Mon, 02 Sep 2002 22:00:03 -0400 Subject: Is it worth learning python? Message-ID: <5.1.0.14.0.20020902220001.00bea188@mail.softhome.net> At 12:44 AM 8/26/2002 -0400, you wrote: > > languages. Python is a great first language. > >Python is a great last language! I agree with you, Python is a great language no matter when you learn it. But this is my recommendation for the OP, who is learning to program. P.D. Sorry for the delay, but last week was a tough one. ----------------------------------- Andres Rosado Email: andresr at despammed.com ICQ: 66750646 Homepage: http://andres980.tripod.com/ A word to the wise is enough. -- Miguel de Cervantes From duncan at NOSPAMrcp.co.uk Mon Sep 2 05:57:55 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 2 Sep 2002 09:57:55 +0000 (UTC) Subject: Why it is so dramatical? References: Message-ID: "Bo M. Maryniuck" wrote in news:mailman.1030957743.4021.python-list at python.org: > The task: > Adding a text to a text. > > The problem: > It is tragically slow to add string to huge string. > > The question: Why? Because the text in strings is stored in a single block of memory, so extending a string requires making a copy of all the data. Also strings are immutable so you cannot extend them 'in-place'. Like all things it is a tradeoff. If you make strings mutable then extending them might be a bit faster, but many other operations would then require copying strings in case they were modified, so you lose out in general more than you gain. None of this is specific to Python, the same issues arise in almost any programming language (although not always the same solutions). > > The other question: > Is it true, that I should through all the Python life > use lists and then join it into single text instead to use += > operator? > Using lists and joining them should come to hand as the first solution in most cases where you are building up a string. Using cStringIO, array or mmap should also be in your toolbox for those cases where they are the most appropriate. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From manuel at hendel.net Tue Sep 17 04:02:09 2002 From: manuel at hendel.net (Manuel Hendel) Date: Tue, 17 Sep 2002 10:02:09 +0200 Subject: problems getting a single item out of a list In-Reply-To: <200209170030.52964.shalehperry@attbi.com> References: <20020917071900.GB23629@partagas.as.de.cw.net> <200209170030.52964.shalehperry@attbi.com> Message-ID: <20020917080209.GC23629@partagas.as.de.cw.net> On Tue, Sep 17, 2002 at 12:30:52AM -0700, Sean 'Shaleh' Perry wrote: > > just use fields[2] (you start counting at zero). This worked fine: domainfield = fields[3] But the next problem is, that after a domainfield = string.split(fields[3]) domainfield seams to be a list item again. print domainfield ['142000'] Manuel -- In Ohio, if you ignore an orator on Decoration day to such an extent as to publicly play croquet or pitch horseshoes within one mile of the speaker's stand, you can be fined $25.00. From martin at v.loewis.de Wed Sep 4 18:50:43 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 05 Sep 2002 00:50:43 +0200 Subject: Memory fault - core dumped while compiling 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> <3D765A05.6030004@nospam.yahoo.com> <3D768753.8030302@nospam.yahoo.com> Message-ID: Anton Graph writes: > python -E setup.py build in gdb: > > (gdb) where > #0 0x80016d06 in do_reloc () from /usr/lib/libc.so.1 That sounds like a question to bring to an SCO forum. Apparently, this crashes when doing relocations while loading the extension module. This raises a number of questions: - Why does it do relocations at all? Could it be that you have object files that a not position-independent? I.e. is distutils using the compiler correctly both for compilation, and for linking? It might be correct that it tries to perform relocation, e.g. for the global offset table, and the procedure linkage table - but it *is* troubling that relocations is where it crashes. - What is the precise version of the operating system you are using? - I'm troubled by the fact that in both configurations (with an without gcc), the compiler is always referred-to as "cc". Are you sure you are not using gcc? Please have a look at http://gcc.gnu.org/ml/gcc-testresults/1999-04/msg00239.html Notice that the failure mode is quite similar... Likewise, http://www.bitmechanic.com/mail-archives/dbi-users/Jun1999/0485.html reports such a problem when using gcc on SCO. Regards, Martin From chris.gonnerman at newcenturycomputers.net Sat Sep 7 00:23:36 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Fri, 6 Sep 2002 23:23:36 -0500 Subject: Python from C/SDL References: <3D793B29.3198AB0E@ihug.co.nz> Message-ID: <006101c25626$56c9b1c0$0101010a@local> ----- Original Message ----- From: "Gib Bogle" > Hi, > > I am a complete beginner with Python. My interest in it is focussed on > a great piece of open-source software called pymol, a system for > visualization of molecules that uses Python and OpenGL. I'd like to get > access to pymol's graphical functions from my own program, which is > built from C, SDL and OpenGL. Have you looked at PyGame (www.pygame.org)? It wraps SDL in Python. Some pretty impressive things can be done there, and in less lines of code than the equivalent C. > I'm wondering if (with a bit of surgery) I'd be able to get access to > the lower-level functionality of pymol, by which I mean the file I/O and > rendering functions. Probably not too hard to implement as a C module, if you are already an accomplished C programmer. The C API for Python is pretty easy, once you grasp refcounting. > I will not want to use the GUI at all. SDL would > create the surface(s), and handle the buffer swapping. My goal is to be > able to send a request to the pymol API asking for a frustum view to be > rendered on the provided surface. > > Sorry if my question is one that gets asked and answered frequently. If > there is a place where this has been dealt with please direct me. Never heard this one before... Good luck! Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From sholden at holdenweb.com Tue Sep 17 12:33:25 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 17 Sep 2002 12:33:25 -0400 Subject: don't understand error message References: Message-ID: "Manuel Hendel" wrote in message news:mailman.1032255920.1725.python-list at python.org... > On Tue, Sep 17, 2002 at 09:12:06AM +0000, Duncan Booth wrote: > > It simply means that at least one line of your file doesn't have 4 fields > > after you have finished your processing. If the line only has two "|" > > characters in it, then you will only get three fields which you can access > > with indices 0 to 2. Trying to use an index out of range for a list will > > produce this error. > > > > Try sticking a "print fields" line just before the if statement, the last > > line printed will show you which line didn't match. > > My script already changed a little bit, I tried to fix it by my self, > but it seams, that I just moved the error. How would you check the > lines for the number of fields? > Actually, I think I found that problem. I forgot some "---|--|--" at > the end. > But I already got a new one. > > [....] > if domainfield in domain: > domainlines.append(line) > [....] > > This should work if the domainfield and domain got the following > values, shouldn't it? > > domainfield = 1234.ab.cdef.de > damain = 1234.ab.cdef.de > > But I get this error message: > > TypeError: 'in ' requires character as left operand > You're just a little bit ahead of reality (have you been using Guido's time machine without permission?). This should woirk in 2.3, but for now you'll have to use the .index() or .find() methods of the string objects. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From skip at pobox.com Thu Sep 5 22:29:06 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 5 Sep 2002 21:29:06 -0500 Subject: pygtk-2 tutorial/doc? In-Reply-To: References: Message-ID: <15736.4850.859179.13616@12-248-11-90.client.attbi.com> Matt> I'd like to find some kind of tutorial or at least some Matt> introductory documentation on programming with pygtk-2 with python Matt> 2.2. Matt> Anyone have any ideas on where I should be looking? I had similar problems when I first used PyGtk. I had no real Gtk experience, so it took a little while to get comfortable with its model. I think the intention is that the plain old Gtk docs should suffice. Failing that, you might look at the examples in the PyGtk distribution. In any case, you might get more helpful responses from the pygtk mailing list (pygtk at daa.com.au). -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From romany at actimize.com Thu Sep 12 06:18:32 2002 From: romany at actimize.com (Roman Yakovenko) Date: Thu, 12 Sep 2002 12:18:32 +0200 Subject: class variable won't icrement! Message-ID: <7647A9F4B298E74DB6793865DA67285004ADF4@exchange.adrembi.com> Hi it is simple just change self.id = self.id + 1 To test.id += 1 Roman > -----Original Message----- > From: Gumuz [mailto:gumuz at amoebe.looze.net] > Sent: Thursday, September 12, 2002 10:55 AM > To: python-list at python.org > Subject: class variable won't icrement! > > > Hello everyone, > > I have something very strange and i can not understand it. > probably, it's > not _that_ strange : ) > > I have this simple class which registers itself on a class > variable in the > following code: > > -------------------------------------------------------------- > -------------- > ------ > class test: > dict = {} > id = 1 > def __init__(self, name): > self.dict[name] = self > self.id = self.id + 1 > > def show(self): > print "class variable dict element count: ", > str(len(self.dict)) > print "class variable id: ", self.id > -------------------------------------------------------------- > -------------- > -------- > > now, look at the following: > > >>> john = test("john") > >>> frank = test("frank") > >>> bill = test("bill") > >>> bill.show() > class variable dict element count: 3 > class variable id: 2 > >>> frank.show() > class variable dict element count: 3 > class variable id: 2 > > The dict variable acts fine, maintaining it's content throughout every > instance of the class. > The id variable however, seems to be only incremented within > the instance. > In the end this variable should've been 4. > > Could someone explain this to me? Is there something about > class variables > whta i should know? > > many thanx, > Guyon > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gerhard.haering at gmx.de Tue Sep 3 16:36:51 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 3 Sep 2002 20:36:51 GMT Subject: Servizi Internet References: Message-ID: Powell, Thomas wrote in comp.lang.python: > Wasn't this spam from an _ISP_ anyway? An abuse message to the ISP > might get them to back off their spamming practices, but otherwise, > what is the only "legal" recourse? Complain to their backbone > provider? Yep. It contains: "X-Complaints-To: abuse at baymountain.net" [x] Done. > -----Original Message----- > [snip stupid M$ Outhouse quoting, yuck!] http://www.math.fu-berlin.de/user/guckes/mail/edit.html -- Gerhard From marklists at mceahern.com Mon Sep 23 23:02:38 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 23 Sep 2002 22:02:38 -0500 Subject: confusion about opening files In-Reply-To: <3d8fd215$0$192$75868355@news.frii.net> Message-ID: > O. K. Now I am confused. I thought that when I imported the os module, i > would have to call its functions like this: os.open() Why am I > just using the function name? You are assuming open == os.open. Not so. Watch... *** $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> print open.__doc__ file(name[, mode[, buffering]]) -> file object Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. Note: open() is an alias for file(). >>> import os >>> print os.open.__doc__ open(filename, flag [, mode=0777]) -> fd Open a file (for low level IO). >>> open == os.open 0 *** Cheers, // m - From loewis at informatik.hu-berlin.de Thu Sep 19 10:21:42 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 19 Sep 2002 16:21:42 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: Christian Tismer writes: > Maybe sufficient for not crashing on the C level. > But this is not enough for micro-thread-safety. > See the random module for example, it needs a lock > or it will give unpredictable results. Academically, I don't think the results are unpredictable, as micro-thread switch occur at predictable points in processing. Regardless, you are saying that the random module is not thread-safe. A number of Python modules is not thread safe; many of them won't be 'safe' in the presence of microthreads, either. With microthreads, the problem is usually not as bad as with real threads, since a switch usually cannot occur in the middle of a library routine (unless the library calls back, and the call-back causes a switch). So this is something that has been accepted all the years, and should not cause FUD. Regards, Martin From phr-n2002b at NOSPAMnightsong.com Thu Sep 26 17:42:30 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 26 Sep 2002 14:42:30 -0700 Subject: Who knows somefunction? References: <3D937B08.4090704@aon.at> <3D937D4C.2BFDF40A@alcyone.com> Message-ID: <7xsmzwwhq1.fsf@ruckus.brouhaha.com> Erik Max Francis writes: > > Is there a function in Python > > for which > > > > something is (id(something)) > > > > returns invariably true? > > Not offhand, but there's an easier test. x is y really just means id(x) > == id(y), so you could change this test to: > > id(something) == id(somethingElse) > > and you probably wouldn't have the need for your hypothetical function. No I think he's asking for a way to dereference an id of an object. And the answer is there's no way to do that. From owen at nospam.invalid Tue Sep 10 17:11:59 2002 From: owen at nospam.invalid (Russell E. Owen) Date: Tue, 10 Sep 2002 14:11:59 -0700 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> Message-ID: In article <3D7C210F.7090708 at something.invalid>, Greg Ewing wrote: > "Joseph A. Knapka" wrote in message news:<3D798461.B3FE0E06 at earthlink.net>... >>...(text elided)... >...I hope you're aware that what you're doing in your buttons >example is NOT equivalent to using the "command" option. >The latter does a number of extra things: it waits until >the mouse is released, and triggers the handler only if >the release is within the button. (what Joseph was doing was binding the button to the event, e.g. mybutton.bind("", afunction)) Alas, too true. Button-1 fires when the mouse button is pressed (very nonstandard behavior) and ButtonRelease fires when the mouse button is released even if the mouse is no longer over the Button object. I don't know of any event binding that does a proper job of emulating the standard behavior of pressing a button. Button(command=...) is the way to go for this. If you need to know which button the user pressed (or any other information that you know at the time you specify the button command callback), define a new callback function that contains the information. You certainly don't have to use lambda (and I never do). Scott David Daniels wrote a very useful class that makes writing callback functions that contain stored information a breeze. It is available at ). I make heavy use of it and feel it really cleans up my code. Actually, I use a minor variant I wrote that optimizes the common case of no stored keyword arguments. You can get my version (as well a Tkinter summary I wrote) at ; the former is called GenericCallback and can be found in util.zip. -- Russell From bobx at linuxmail.org Mon Sep 16 22:35:49 2002 From: bobx at linuxmail.org (Bob X) Date: Tue, 17 Sep 2002 02:35:49 GMT Subject: Python equivalent to perldoc? References: Message-ID: <9ywh9.7955$Lg2.1406050@news2.news.adelphia.net> Skip Montanaro wrote: > Bob> In Perl you can run "perldoc warnings" and get the definition of > Bob> what "warnings" does. Is there a equivalent in Python? > > Try "pydoc warnings". > What a funny guy! :-) From wavefrnt at tampabay.rr.com Sat Sep 28 06:24:51 2002 From: wavefrnt at tampabay.rr.com (David Edwards) Date: Sat, 28 Sep 2002 06:24:51 -0400 Subject: print a % In-Reply-To: References: Message-ID: <20020928102451.GA27641@buttercup.3digital.com> On Sat, Sep 28, 2002 at 03:11:57AM -0700, Claude wrote: > When I do > print "image size=%d%" %(50) > I've got an error > > Traceback (most recent call last): > File "", line 1, in ? > ValueError: incomplete format > > I do not know how to escape the second % > > print "image size=%d%" %(50) > image size=50% > You escape the % with another %. Like this: print "image size=%d%%" %(50) -- david edwards From bobx at linuxmail.org Mon Sep 16 16:46:03 2002 From: bobx at linuxmail.org (Bob X) Date: Mon, 16 Sep 2002 20:46:03 GMT Subject: [FEEDBACK] Is this script efficient...is there a better way? References: <4ZRf9.1782$Lg2.248733@news2.news.adelphia.net> <3hSf9.168947$l_4.98525@atlpnn01.usenetserver.com> <8PSf9.1796$Lg2.257378@news2.news.adelphia.net> <_oUf9.170870$l_4.126599@atlpnn01.usenetserver.com> <3pkg9.3313$WV.2782@fe03> Message-ID: Steve Holden wrote: I did a test on the 30MB sized logs and the RE did indeed come out the faster, thought not by much. The interesting thing is it caught more as well since my script looked for exact matches and the RE based one ignored case (as far as my feeble brain understands such things). I remember why I had the "result" statement. It was because I needed to write the keyword found and then the line it was found on to the hits file. Can't seem to make that work with the RE based one. Then again...I know RE as far as the east is from the west. Bob From pierpaolo.glave at ciaolab.com Thu Sep 12 04:11:04 2002 From: pierpaolo.glave at ciaolab.com (Pier Paolo Glave) Date: 12 Sep 2002 01:11:04 -0700 Subject: Tkinter, updateStringProc for type font References: <1907a5e4.0209040455.64ae73b1@posting.google.com> <3D7F772C.80205@ActiveState.com> Message-ID: <1907a5e4.0209120011.7acb1a40@posting.google.com> Jeffrey Hobbs wrote in message news:<3D7F772C.80205 at ActiveState.com>... > Do you have any other C extensions in your application? I've not seen this > occur myself, except in bugs where other C extensions were abusing Tcl objects > internally. No, I'm not using any C extensions, as far as I know. Besides the standards distribution, I only installed BLT, but I were not using it when these errors occurred. Bye -- Pier Paolo Glave From wlfraed at ix.netcom.com Thu Sep 26 16:06:41 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 26 Sep 2002 13:06:41 -0700 Subject: Getting last char in string. References: Message-ID: CheapSkate fed this fish to the penguins on Thursday 26 September 2002 04:15 am: > Single character are strings of length 1(as u said) and " is single > character right? > The line did NOT contain a double-quote (") but rather /two/ single-quotes ('') next to each other. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From max at alcyone.com Tue Sep 24 20:22:04 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 24 Sep 2002 17:22:04 -0700 Subject: Strange python and cgi! References: Message-ID: <3D9101AC.842F0513@alcyone.com> CheapSkate wrote: > when I go to the webpage, it stops halfway and in "view source: it > only show > the code till the open "pre". It's likely some other error occurred. Check your Web server error log for the final word. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ As far as I'm concerned, being any gender is a drag. \__/ Patti Smith Kepler's laws / http://www.alcyone.com/max/physics/kepler/ A proof of Kepler's laws. From 53ab2750 at meowing.net Wed Sep 25 20:08:14 2002 From: 53ab2750 at meowing.net (itsy bitsy meowbot) Date: Thu, 26 Sep 2002 00:08:14 GMT Subject: "which" command? References: Message-ID: marco wrote: > > Hi, > > A few days ago there was a discussion here about a > "which" written in python (as opposed to running > the OS "which" command). Any pointers to that thread? Are you looking for this? From bogle at ihug.co.nz Sat Sep 7 20:47:22 2002 From: bogle at ihug.co.nz (Gib Bogle) Date: Sun, 08 Sep 2002 12:47:22 +1200 Subject: Larry Wall's comment on python... References: <3d796c18@news.sentex.net> Message-ID: <3D7A9E1A.1171C857@ihug.co.nz> Peter Hansen wrote: > > mmaddox at hcsmail.com wrote: > > Although I grant the Python structure and the column-based > > structures are not completely analogous, they BOTH burden the programmer > > with arbitrary rules to govern the physical layout of the code. Although > > this layout may be considered more elegant from a readability standpoint, > > it's the enforcement of the layout that is irritating to the more > > Libertarian of us. > > I think you have the wrong meaning for "arbitrary". From the > sounds of it, you have exactly reversed which is arbitrary (your > own "libertarian" coding style) and which is "governed by fixed > rules" (Python layout). > > > Having read Wall's comments on Slashdot, I think he is really just mildly > > complaining about ridiculously long page-widths in his editor, not really > > slashing Python seriously. He's just giving some props to his own baby at > > the expense of another. (He had to say something, right?) You must agree > > that Python can lead you to horizontal scrolling in your editor - the bane > > of user interface design. > > I agree with the comments about Larry "having" to say something like this. > > I definitely don't understand how Python, more or less than any other > language, leads to more horizontal scrolling. Pretty much all > Python code I've ever seen (though I haven't seen yours yet :-) is > roughly 80 characters max, and mine own has been about that since I > started writing C code 16 years ago. > > Do you mean there is something special about Python not delimiting > blocks in the traditional ways which somehow leads you to write > much wider lines of code? Maybe he is referring to an effect of default editor tab size. From a.clarke11 at pop.ntlworld.com Sat Sep 7 16:23:39 2002 From: a.clarke11 at pop.ntlworld.com (a.clarke11) Date: Sat, 07 Sep 2002 21:23:39 +0100 Subject: Thinking of joining References: <3D7970DC.5115BCC8@earthlink.net> <20020907095211.24938.00000006@mb-mt.aol.com> Message-ID: <3D7A604B.31FE7E73@pop.ntlworld.com> And its not dead, hasn't expired, gone to Valhalla, isn't kaput or aything like that. Thanks, teaand bikkie for reminding us what it is all about TeaAndBikkie wrote: > IMHO Python has beautiful plumage, isn't nailed to the perch, and won't leave > you pining for the fields. It also has a good range of cheese, even the ones > you thought you didn't need, and you won't get stoned by your friends for > joining. > > (Any implied references to Parrot are completely accidental). > > I'm too new to Python to give you good technical reasons to use it, but I like > it :) From aleax at aleax.it Thu Sep 26 10:28:11 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 14:28:11 GMT Subject: Getting started References: <00a801c26511$4e084750$df7e4e18@brianspiv1700> Message-ID: <%PEk9.146154$ub2.3217944@news1.tin.it> Thomas Heller wrote: ... > Hidden fields in a union by the discretion of the compiler? > Don't think that would be allowed by any C standard. Could you help me out by pointing to chapter and verse that would make it disallowed, please? I can't find anything that would disallow it, and it appears to me that the sentence: """ if the value of a member of a union object is used when the most recent store to the object was to a different member, the behavior is implementation- defined. """ (with the specific exception of unions of structs that share a common initial sequence). The specs for sizeof seem to go out of their way to NOT constrain sizeof(aunion) to be the largest sizeof of union members, so as to avoid prohibiting such internal tags -- it says the size is *sufficient* to contain the largest member, NOT *is* that member's size. So, what _am_ I missing...? Thanks, Alex From fperez528 at yahoo.com Mon Sep 30 22:58:43 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Mon, 30 Sep 2002 20:58:43 -0600 Subject: Reloading a module References: Message-ID: Tom wrote: > I wish it were that simple. I've used reload(module) many times, each > time hoping that it would do what the documentation says it will do. > I've tested it by adding a simple variable to my module, watching to see > if it shows up in the new import, but it never does. I noticed also that > sometimes it reloads from the .pyc file, and if the reload happens > before the .pyc file is updated with the new changes, the changes won't > be available. Even if I force a reload from the updated .py file by > deleting .pyc file, it still retains the old code. I'm at a loss to > understand what's going on. True. I actually don't rely on reload almost ever. I instead tend to use a cooked-up version of execfile() for this, or deep_reload. The former is available under ipython as @run, the latter as dreload(). Using @run works ok only for top-level stuff, of course. dreload() is pretty good but still can fail in certain cases. You may want to give them a try. Cheers, f. From tismer at tismer.com Thu Sep 19 14:02:52 2002 From: tismer at tismer.com (Christian Tismer) Date: Thu, 19 Sep 2002 20:02:52 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: <3D8A114C.50007@tismer.com> Martin v. L?wis wrote: > Christian Tismer writes: > > >>Maybe sufficient for not crashing on the C level. >>But this is not enough for micro-thread-safety. >>See the random module for example, it needs a lock >>or it will give unpredictable results. > > > Academically, I don't think the results are unpredictable, as > micro-thread switch occur at predictable points in processing. Yes, right now, but this will change pretty soon. > Regardless, you are saying that the random module is not > thread-safe. A number of Python modules is not thread safe; many of > them won't be 'safe' in the presence of microthreads, either. With > microthreads, the problem is usually not as bad as with real threads, > since a switch usually cannot occur in the middle of a library routine > (unless the library calls back, and the call-back causes a switch). I am not saying that the random module is not thread safe (although I'm not sure if it is). The point is: Microthread safety is more than thread safety, since microthreads don't care about thread locks, since they are still *in the same thread*. It will for sure become a problem, and it is different from effect, but similar to the C probs by reason: We are switching context where some code might not expect it. It might feel safe because it is thread safe, but this is not enough. I have to do rigid locking of every unknown piece of code, until somebody explicitly claims some code to be switchable. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From peter at engcorp.com Fri Sep 6 08:57:53 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Sep 2002 08:57:53 -0400 Subject: Timothy Rue References: <898662b7d85d2c966c0bd45d563d5d2d@xganon.com> Message-ID: <3d78a638$1@news.sentex.net> xganon wrote: > Does Timothy Rue still Troll here? > If not, how did you get rid of him? > We need him out of our group now, > maybe we could get him into a Perl > group for a while and let them deal > with him? Have you heard of that nasty "cocktail" treatment that has been tried in the past for cancer? It looked a lot like that... Sorry to hear the infection has spread. -Peter From syver-en at online.no Sat Sep 14 19:57:45 2002 From: syver-en at online.no (syver-en at online.no) Date: Sat, 14 Sep 2002 23:57:45 GMT Subject: IDLE References: <3D7D4F84.318CDB0F@bellatlantic.net> Message-ID: "Ali K" writes: > Hardware: 386 enhanced, 75MHz, 32MB RAM. > OS: Win98 > Copied files from other computer to mine. > It doesn't open when I click on ide.pyw or when I choose to edit a py > file > > with it. I suggest you install the python distro from www.python.org. -- Vennlig hilsen Syver Enstad From google at quinceleaf.com Thu Sep 19 16:38:50 2002 From: google at quinceleaf.com (Brian Ibbotson) Date: 19 Sep 2002 13:38:50 -0700 Subject: Strange behavior of ClientCookie and site-packages Message-ID: <6cb82943.0209191238.4b116988@posting.google.com> I'm running Python 2.2 in RH7.3. I've been trying to use ClientCookie, and have installed it per its README instructions (moving it to a ClientCookie dir in site-packages). The module is accessible from the 2.2 command line shell, where sys.path reports /usr/lib/python2.2/site-packages/ClientCookie among the search paths. The command import ClientCookie succeeds without problem. However, Idle for Python 2.2 cannot do the same. With an identical set of paths reported by sys.path, including the ClientCookie reference above, Idle reports: >>> import ClientCookie Traceback (most recent call last): File "", line 1, in ? import ClientCookie ImportError: No module named ClientCookie >>> Can anyone suggest an explanation for this behavior? Other third-party modules installed to site-packages (such as ChartDirector and MySQLdb) have had no problems once they are included in sys.path - Brian From lordmacro at hotmail.com Mon Sep 30 06:01:57 2002 From: lordmacro at hotmail.com (Tom Widrick) Date: Mon, 30 Sep 2002 05:01:57 -0500 Subject: sizeof PyTypeObject difference References: Message-ID: Interestingly enough, it turned out that the easiest way to look at it for me was to remember that: class Accumulator: __metaclass__ = type __value = 0 value = property(lambda s: s.__value) def add(self, v): self.value = self.__value + v def sub(self, v): self.value = self.__value - v was the same as tp_dict = {} def add(self, v): self.__value = self.__value + v tp_dict['add'] = add def sub(self, v): self.__value = self.__value - v tp_dict['sub'] = sub tp_dict['__value'] = 0 tp_dict['value'] = property(lambda s: s.__value) Accumulator = type('Accumulator', (), tp_dict) I was able to take a "regular" extension type I was working on, defined a tp_init type member that implemented the (name, bases, dict) interface and bam, a metatype. So, I guess it could be argued that metatypes in C are supported by the class/type unification. It's just easier to use the builtin functions as helpers when implementing the metatype, (like PyObject_GenericGetAttr). Nearly all of the functionality of the Type object could be grafted over into my extension type, so I assume that was the intended way, and not to subtype PyType_Type. Tom From kokohh at hotmail.com Wed Sep 4 23:53:44 2002 From: kokohh at hotmail.com (koko) Date: Thu, 05 Sep 2002 03:53:44 GMT Subject: newbie problem: use socke lib to retrieve one web page: Message-ID: I write this to retrieve one web page using socket lib. # retrieve webpage import socket HOST='www.uic.edu' # remote host PORT=80 # remort port s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) m="""GET /home/events.shtml HTTP/1.0 From: hh at uic.edu User-Agent: test/1.0 """ s.connect((HOST,PORT)) s.send(m) data=s.recv(4096) print data s.close() ----------- But I retrieved nothing and the program stuck. From sismex01 at hebmex.com Thu Sep 26 17:33:15 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 26 Sep 2002 16:33:15 -0500 Subject: How do you pronounce "__" (double underscore)? Message-ID: > > In article <525eaba.0209260956.72bf6786 at posting.google.com>, > Pat Notz wrote: > > @ = "at" > > ! = "bang" > > . = "dot" > > * = "star" > > > > Is there a short (one or two syllable) pronounciation for > > "__" (double underscore). "Underscore underscore" and "double > > underscore" are kind of long. Somthing like "splat"? Anyone? > > I've heard "splat" used for both '#' and '*', so I'd cross it > off the list... > > -- > Grant Edwards grante Yow! Sign > my PETITION. > at > visi.com Hmmm.. how about a "squish"? -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From nhodgson at bigpond.net.au Mon Sep 9 23:20:36 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Tue, 10 Sep 2002 03:20:36 GMT Subject: PythonWin bug [very weird] References: <3D7CC91D.5000607@mxm.dk> Message-ID: <8ydf9.14146$_l1.38749@news-server.bigpond.net.au> Max M: > That is almost as good as when you write a top latin-1 character like > '?' and you try to delete it via backspace and it only seems to delete > one of two bytes making it up, and you end up with '?'. That is caused by reusing the IDLE automatic indentation smart backspace code without allowing for characters that use multiple bytes. If you are interested in fixing it, the code is in Pythonwin\pywin\idle\AutoIndent.py Neil From 2002 at weholt.org Thu Sep 19 07:05:00 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Thu, 19 Sep 2002 11:05:00 GMT Subject: StructuredText -> HTML module?? Message-ID: Need a module to parse StructuredText/Wiki into HTML. Looked at PyWiki, but the generated code was not what I expected. Does anybody have module or lib to do this? Best regards, Thomas From wlfraed at ix.netcom.com Sun Sep 29 23:19:36 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 29 Sep 2002 20:19:36 -0700 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <3d976fbc$0$23666$91cee783@newsreader02.highway.telekom.at> <8428na.7vj.ln@ix.netcom.com> <3d979184$0$20332$79c14f64@nan-newsreader-03.noos.net> Message-ID: <8sf8na.86m.ln@ix.netcom.com> Guy Rabiller fed this fish to the penguins on Sunday 29 September 2002 04:49 pm: > > yes it works on MS-DOS too. > Ah, good to know... Still need -vv to get the details from import though; -v just says "not found" -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From aleax at aleax.it Thu Sep 26 09:32:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 13:32:45 GMT Subject: Getting started References: <3D920950.323B25B3@alcyone.com> Message-ID: <10Ek9.170778$pX1.6080993@news2.tin.it> James J. Besemer wrote: ... >>(I favor the >>latter definition, since it carries more information about the >>language.) > > It doesn't really tell you anything. > > Else, in 25 words or less, why does Perl's "+" operator supposedly work > the one way and Python's "*" operator work the other way? Perl's + *creates a numeric context*: operands implicitly "become numbers". Python's x*y calls x.__mul__(y) or else y.__rmul__(x) -- no "context", nothing "becomes", _objects_ drive. There -- 24 words by wc's count, so, little space to insert caveats about implementation quirks &c, such as optimizations which e.g. * could insert for types it knows about -- conceptually, everything should work as if operators were implemented by dispatching special methods, although optimization with invariant program-observable results is clearly fine; and the like. I have to agree with you that Perl's overall defined behavior CAN be implemented by mechanisms akin to Python's (don't know if it IS -- my knowledge of Perl's internals dates to Perl 4, and back then, as I recall, it wasn't); but the mental model becomes too cumbersome that way -- in practice, thinking in terms of various established-contexts is just about inevitable in Perl (some of them you can even TEST for, e.g. via wantarray). Python's own overall defined behavior OTOH is most simply conceived by seeing operators as syntax sugar for templates (in the sense of the "template method" DP -- they aren't methods, but they're templates in just that way), involving one or more calls to the operands' special methods. Stringification does involve "implicitly become" (via __str__ or __repr__, but that's really no more than "giving context" as in so many cases in Perl) -- the print statement, and the % operator with string LHS, being the two cases. One could quibble about "boolean contexts" (in statements if and while, and operators and, or, not) -- arguing that there's a "become" there, however, is denied by the fact that and and or return one of their two operands, without having made it become anything, so I don't think __nonzero__ is best considered a "become" special method here (but I can see the arguments on the reverse side, since it IS quite natural to speak of "truth context" and the like to explain this little part of Python). Alex From tarnower at optonline.net Tue Sep 24 22:10:53 2002 From: tarnower at optonline.net (DT) Date: 24 Sep 2002 19:10:53 -0700 Subject: Zope Documentation and example sites References: <503511c2.0209230758.74a64a3d@posting.google.com> Message-ID: <9bf19f33.0209241810.1fbd28f5@posting.google.com> Hi Sam, I am in the same boat as you. I've just become a Zope user, and I hope to apply it to an Intranet project I plan to start soon. I'm particularly interested in the CMF product. I also did a search for existing websites. One I found that seems pretty well written is: http://spring.parkinsons.org.uk/ I would like to find some working examples that use CMF. Does anyone know of any? sam-nospam- at totallynerd.com (Sam Alexander) wrote in message news:<503511c2.0209230758.74a64a3d at posting.google.com>... > Hi all, > > I've just installed Zope, and now I'm trying to find reesources to > learn it. I have a few questions along these lines... > > 1) What online resources are out there to help a newbie learn Zope? > I've downloaded the Zope Book, but it's a bit technical for my taste. > I'm looking for something with examples or tutorials showing how to do > some basic stuff from scratch. Any suggestions? Either online or > books ??? > > 2) What sites are using Zope? I've noticed most if not all the Zope > sites I've seen don't mention they're using Zope. Can someone give me > some examples of sites which use Zope so I can get a better idea of > the type of layouts I can do with Zope? I know it's very > programmable, but other then the Plone site (which is great), I'm not > sure what other sites use Zope. > > 3) Finally, I've never used Python, but I'm seasoned in Linux and in > web/app programming (Perl, PHP, C++, Cold Fusion, etc). How long > would it take to learn Zope/python well enough to create a production > site? > > Thanks for your help and suggestions. From gua81 at XXXyahoo.com Mon Sep 30 21:00:23 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Tue, 1 Oct 2002 11:00:23 +1000 Subject: PROBLEM with form in cgi Message-ID: HI, I'm having problem trying to figure out what is wrong with my cgi script. here's the code that's creating the problem in the apple.cgi print """
""" ^ it keeps on saying invalid syntax in the action(as indicated) and if I try to change it to this print """""" ^ it gives the error at action. Please help. From sabren at manifestation.com Wed Sep 25 18:21:56 2002 From: sabren at manifestation.com (Michal Wallace) Date: Wed, 25 Sep 2002 18:21:56 -0400 (EDT) Subject: a python puzzle In-Reply-To: <20020926000315.K30315@prim.han.de> Message-ID: On Thu, 26 Sep 2002, holger krekel wrote: > OK. something like > > def decrypt(yourstring): > dedict = {'F': 'S', 'I': 'C', 'H': 'I', 'a': 't', 'c': 'f', 'b': 'v', 'e': 'n', > 'd': 'o', 'f': 's', 'i': 'c', 'h': 'i', 'k': 'p', 'j': 'h', 'm': 'l', > 'l': 'j', 'o': 'm', 'q': 'u', 'p': 'w', 's': 'b', 'u': 'z', 't': 'd', > 'w': 'y', 'v': 'x', 'y': 'e', 'x': 'a', 'z': 'g', 'g': 'k'} > return "".join([dedict.get(i,i) for i in yourstring]) > returns ... > It's time to test your brainpower! I will give > six months of free web hosting to the first person > to solve this cryptogram. Can you figure it out? Hi Holger, Yep, that's it! I figured it would be easy to solve - especially given the python code, but I didn't expect a solution THAT quick. Next time I'm using RSA! > but i don't know if i need free webhosting :-) Hahaha. Well, if you change your mind, just let me know. :) Cheers, - Michal http://www.sabren.net/ sabren at manifestation.com ------------------------------------------------------------ Switch to Cornerhost! http://www.cornerhost.com/ Low Priced, Reliable Blog Hosting, With a Human Touch. :) ------------------------------------------------------------ From donnal at donnal.net Mon Sep 23 06:08:25 2002 From: donnal at donnal.net (Donnal Walter) Date: 23 Sep 2002 03:08:25 -0700 Subject: convention for Pickler file extension Message-ID: <918bc22f.0209230208.4eaca702@posting.google.com> When one uses Pickler.dump(object) to serialize an object to a file associated with the Pickler, is there a Python convention for the file extension name? Thanks, Donnal Walter Arkansas Children's Hospital From lbrannma at cablespeed.com Thu Sep 19 09:03:25 2002 From: lbrannma at cablespeed.com (Lance) Date: Thu, 19 Sep 2002 06:03:25 -0700 Subject: Getting started Message-ID: Hi All, Last night I attended a Weak typing, C++ Templates, and Python talk by Bruce Eckel. It was great, my introduction to Python. I'm sold on Python and weak typing. I want to write a graphics module that will link to a C application, permitting scatter plots, bar charts, log scales, etc. I suppose the Python Imaging Library will be used for this purpose. Would you be able to suggest an indispensable learning Python book? Thanks, Lance PS: Bruce has Python material on his website, www.bruceeckel.com From franke at ableton.com Tue Sep 3 17:15:05 2002 From: franke at ableton.com (Stefan Franke) Date: Tue, 03 Sep 2002 23:15:05 +0200 Subject: Better tracebacks for exec and execfile References: <3i99nusjbgpiepva9pkuv3mtl7equ7h88h@4ax.com> <87elcbm1ze.fsf@andreasen.org> Message-ID: On 03 Sep 2002 19:12:21 +0200, "Erwin S. Andreasen" wrote: >I don't know how to make SyntaxError appear correctly, Ah. I didn't understood that until I tried it out. In SyntaxError tracebacks still "" appears as the filename. This should be considered a bug in compile(), shoudn't it? From bogle at ihug.co.nz Fri Sep 6 22:36:26 2002 From: bogle at ihug.co.nz (Gib Bogle) Date: Sat, 07 Sep 2002 14:36:26 +1200 Subject: Python from C/SDL References: <3D793B29.3198AB0E@ihug.co.nz> Message-ID: <3D79662A.402E47B6@ihug.co.nz> Gerhard H?ring wrote: > > Gib Bogle wrote in comp.lang.python: > > Hi, > > > > I am a complete beginner with Python. My interest in it is focussed > > on a great piece of open-source software called pymol, a system for > > visualization of molecules that uses Python and OpenGL. I'd like to > > get access to pymol's graphical functions from my own program, which > > is built from C, SDL and OpenGL. > > > > I'm wondering if (with a bit of surgery) I'd be able to get access > > to the lower-level functionality of pymol, by which I mean the file > > I/O and rendering functions. > > You'll have to embed Python > (http://www.python.org/doc/current/ext/embedding.html), load the pymol > modules and call functions or classes in it from C. > > This means you'll have to get familiar with the Python/C API. The good > thing is that this is relatively easy. You should be able to find > documentation and examples on embedding Python. If you have any > particular questions on how to use the Python/C API, just ask here. Thanks Gerhard. I'll have a look and see if I can grasp it. Gib From pinard at iro.umontreal.ca Fri Sep 6 16:00:14 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Fri, 06 Sep 2002 16:00:14 -0400 Subject: Larry Wall's comment on python... In-Reply-To: (brueckd@tbye.com's message of "Fri, 6 Sep 2002 13:03:59 -0700 (PDT)") References: Message-ID: [brueckd at tbye.com] > The very idea of Larry Wall lecturing on code readability is hilarious. While I understand the sentiment, history adds some perspective. I've been following Perl since version 1, and in the beginnings, despite the syntax was admittedly eclectic, Perl was much easier to read then, than now. Perl grew many $X variables where X was a special character, but in the state of the things at the time, it was still bearable. The legibility problem developed progressively when adding things to Perl, while trying to stay compatible to what it was. Running out of special characters, $X started to use control characters. The very notion of announcing the type of something to a prefix character ($%@&) did not mix well when references and more complex structures were added. Larry made an effort to clean out the syntax a bit when going from Perl 4 to Perl 5, but the damage was already too intense for the cleanup to be effective, also considered that the cleanup just could not be too drastic, to protect the existing code base. I take Larry Wall as a nice and clever guy. Perl does not marry so well with evolution, and this is probably the doom of all languages which do not enough foresee evolution, and overly praise backward compatibility. On the other hand, too much rapid or drastic changes might erode the user base or make it less solid. Equilibrium is a very difficult art. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From gupsmail at ihatespam.shaw.ca Wed Sep 25 01:23:21 2002 From: gupsmail at ihatespam.shaw.ca (Grant Hallam) Date: Wed, 25 Sep 2002 05:23:21 GMT Subject: problem with dictionaries within lists Message-ID: the code attached opens a small wxPython frame with menu's to select parsing web survey entries or mailing list responses which are then outputted to Excel. Problem occurs in the parsing part of the code. After the last elif statement I have a list appended with a dictionary that is created my matching keys to the parsed text file. However, the list seems to get populated with the same dictionary repeatedly until the entire file is parsed. It is currently over 305 entries so the resulting list is 305 dictionaries holding the same value instead of unique entries. Any help would be grateful,hopefully it is just a stupid error on my part :) import string,re from win32com.client import Dispatch from wxPython.wx import * #Global variables holding event ID's for menus ID_Web = 101 ID_Mail = 102 ID_EXIT = 103 ID_ABOUT = 201 #Compiled regular expressions #Used in web parser rcN = re.compile('Name') rcL = re.compile('Location') rcT = re.compile('Transit') rcTN = re.compile('Technical_Knowledge') rcLS = re.compile('Like_Site') rcRT = re.compile('Resolve_Tech_Issues') rcEN = re.compile('Easy_Navigation') rcPC = re.compile('Publish_Comments') rcAN = re.compile('Answered_No') rcFS = re.compile('Find_Support') rcFSO = re.compile('Find_Support_Other') rcFI = re.compile('Find_Information') rcWLS = re.compile('Which_LEOnet_Site') rcFIO = re.compile('Find_Information_Other') rcVA = re.compile('Visit_Again') rcVOS = re.compile('Visited_Old_Site') rcTS = re.compile('Time_Spent') rcRTI = re.compile('resolve_tech_issues') #Used in both web and mail parser rcP = re.compile('Position') rcC = re.compile('Comments') rcB = re.compile('B1') #Used in mail parser rcM = re.compile('Membership') rcEM = re.compile('Email_address') class MainFrame(wxFrame): '''Main window for program, uses menus to call parsing engines that output results to excel''' def __init__(self, parent, ID, title): wxFrame.__init__(self, parent, ID, title, wxDefaultPosition, wxSize(200, 150)) #sets up status bar self.CreateStatusBar() self.SetStatusText("Version 3.1, built by Grant Hallam") #sets up file menu filemenu = wxMenu() filemenu.Append(ID_Web, "&Web Survey", "Go find your file") filemenu.Append(ID_Mail, "&Mail Survey", "Go find your file") filemenu.AppendSeparator() filemenu.Append(ID_EXIT, "&Exit", "Terminates the program") #sets up help menu helpmenu = wxMenu() helpmenu.Append(ID_ABOUT, "&About", "Info about program") #adds the menubar menuBar = wxMenuBar() menuBar.Append(filemenu, "&File") menuBar.Append(helpmenu, "Help") self.SetMenuBar(menuBar) #links events from menus to id and callable def's EVT_MENU(self, ID_Web, self.Web) EVT_MENU(self, ID_Mail, self.Mail) EVT_MENU(self, ID_EXIT, self.Exit) EVT_MENU(self, ID_ABOUT, self.About) def Web(self, event): '''Opens file dialog box to select web data file to parse''' dlg = wxFileDialog(self, "Choose a file", ".", "", "*.*", wxOPEN|wxMULTIPLE) if dlg.ShowModal() == wxID_OK: for path in dlg.GetPaths(): filename = path parsefile = WebParser(filename) dlg.Destroy() def Mail(self, event): '''Opens file dialog box to select mail data file to parse''' dlg = wxFileDialog(self, "Choose a file", ".", "", "*.*", wxOPEN|wxMULTIPLE) if dlg.ShowModal() == wxID_OK: for path in dlg.GetPaths(): filename = path parsefile = MailParser(filename) dlg.Destroy() def Exit(self, event): '''Closes the program''' self.Close(true) def About(self, event): '''Opens the about dialog box''' dlg = wxMessageDialog(self, 'This program parses text files currently coded to parse\n survey & mail responses but future parsing engines\n may be included.', 'About Parsing', wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() class MailParser: '''This class parses a text file containing mailing list entries, and outputs the results to excel''' def __init__(self, filename): '''Gets filename and calls the FileRead method''' self.filename = filename self.FileRead() def FileRead(self): '''Opens the text file, parses it, stores the various sections into a dictionary, and then stores that into a list, which is then iterated over to output result in to excel''' file = open(self.filename, 'r') input = file.read() file.close() #sets the column title dictionary, the field names dictionary, the pos list for the variable field values of Position, and the maildatabaselist that stores all the field dictionaries columntitle = ['Membership','Email_address','Position','Comments'] dict = {'Membership':'','Email_address':'','Position':'','Comments':'','B1':''} pos = [] maildatabaselist = [] #This is the guts of the parser, splits the file into blocks,then splits the blocks in to lists of two fields, compares the 1st field to a RE, and adds the 2nd field to the field name dict rawline = string.split(input, '\n') for x in rawline: list = string.split(x, '=') if rcM.match(list[0]): case = string.capwords(list[1]) dict['Membership'] = case elif rcEM.match(list[0]): dict['Email_address'] = list[1] elif rcP.match(list[0]): pos.append(list[1]) elif rcC.match(list[0]): dict['Comments'] = list[1] elif rcB.match(list[0]): dict['B1'] = list[1] #joins the various items in pos list into one string that is inserted in the Position field, POS = string.join(pos,',') dict['Position'] = POS #adds field name dict to maildatabaselist maildatabaselist.append(dict) fs = [] fi = [] #opens Excel, sets to visible, and adds a worksheet xlApp = Dispatch('Excel.Application') xlApp.Visible = 1 workbook = xlApp.Workbooks.Add() worksheet = workbook.Worksheets.Add() #sets the titles of the columns count = 0 for x in columntitle: cell = columntitle[count] count = count+1 worksheet.Cells(1,count).Font.Bold=1 worksheet.Cells(1,count).Value = cell #sets up excel cells and inserts maildatabaselist fields into cells row = 2 for x in maildatabaselist: row = row +1 worksheet.Cells(row,1).Value = x['Membership'] worksheet.Cells(row,2).Value = x['Email_address'] worksheet.Cells(row,3).Value = x['Position'] worksheet.Cells(row,4).Value = x['Comments'] #adds bottom column headers to excel count = 0 titlerow = row +2 for x in columntitle: cell = columntitle[count] count = count+1 worksheet.Cells(titlerow,count).Font.Bold=1 worksheet.Cells(titlerow,count).Value = cell class WebParser: '''This class parses a text file containing web survey list entries, and outputs the results to excel''' def __init__(self, filename): '''Gets filename and calls the FileRead method''' self.filename = filename self.FileRead() def FileRead(self): '''Opens the text file, parses it, stores the various sections into a dictionary, and then stores that into a list, which is then iterated over to output result in to excel''' file = open(self.filename, 'r') input = file.read() file.close() #sets the column title dictionary, the field names dictionary, the fs and fi list for the variable field values of Find support and find information, and the webdatabaselist that stores all the field dictionaries columntitle = ['Name','Transit','Location','Position','Knowledge','Like site','Resolve issues','Navigate','Publish','Answer no','Find support','Find support other','Find information','Find information other','Which leonet other','Visit','Old visit','Spent','Comments'] dict = {'Name': '','Location':'','Transit':'','Position':'','Technical_Knowledge':'','Like_Site':'','Resolve_Tech_Issues':'','Easy_Navigation':'','Publish_Comments':'','Answered_No':'','Find_Support':'','Find_Support_Other':'','Find_Information':'','Which_LEOnet_Site':'','Find_Information_Other':'','Visit_Again':'','Visited_Old_Site':'','Time_Spent':'','Comments':'','B1':''} fs = [] fi = [] webdatabaselist = [] #This is the guts of the parser, splits the file into blocks,then splits the blocks in to lists of two fields, compares the 1st field to a RE, and adds the 2nd field to the field name dict rawline = string.split(input, '\n') for x in rawline: list = string.split(x, '=') if rcN.match(list[0]): case = string.capwords(list[1]) dict['Name'] = case elif rcL.match(list[0]): dict['Location'] = list[1] elif rcT.match(list[0]): dict['Transit'] = list[1] elif rcP.match(list[0]): dict['Position'] = list[1] elif rcTN.match(list[0]): dict['Technical_Knowledge'] = list[1] elif rcLS.match(list[0]): dict['Like_Site'] = list[1] elif rcRT.match(list[0]): dict['Resolve_Tech_Issues'] = list[1] elif rcEN.match(list[0]): dict['Easy_Navigation'] = list[1] elif rcPC.match(list[0]): dict['Publish_Comments'] = list[1] elif rcAN.match(list[0]): dict['Answered_No'] = list[1] elif rcFIO.match(list[0]): dict['Find_Information_Other'] = list[1] elif rcWLS.match(list[0]): dict['Which_LEOnet_Site'] = list[1] elif rcFSO.match(list[0]): dict['Find_Support_Other'] = list[1] elif rcFS.match(list[0]): fs.append(list[1]) elif rcFI.match(list[0]): fi.append(list[1]) elif rcVA.match(list[0]): dict['Visit_Again'] = list[1] elif rcVOS.match(list[0]): dict['Visited_Old_Site'] = list[1] elif rcTS.match(list[0]): dict['Time_Spent'] = list[1] elif rcC.match(list[0]): dict['Comments'] = list[1] elif rcB.match(list[0]): dict['B1'] = list[1] #joins the various items in fs and fi list into one string that is inserted in the Find Support and Find Information fields, findS = string.join(fs,',') dict['Find_Support'] = findS findI = string.join(fi,',') dict['Find_Information'] = findI #print dict #adds field name dict to maildatabaselist webdatabaselist.append(dict) fs = [] fi = [] totalnumberrecords = len(webdatabaselist) #opens Excel, sets to visible, and adds a worksheet xlApp = Dispatch('Excel.Application') xlApp.Visible = 1 workbook = xlApp.Workbooks.Add() worksheet = workbook.Worksheets.Add() #sets the titles of the columns count = 0 for x in columntitle: cell = columntitle[count] count = count+1 worksheet.Cells(1,count).Font.Bold=1 worksheet.Cells(1,count).Value = cell #sets up excel cells and inserts webdatabaselist fields into cells row = 2 for x in webdatabaselist: row += 1 worksheet.Cells(row,1).Value = x['Name'] worksheet.Cells(row,2).Value =x['Transit'] worksheet.Cells(row,3).Value =x['Location'] worksheet.Cells(row,4).Value =x['Position'] worksheet.Cells(row,5).Value =x['Technical_Knowledge'] worksheet.Cells(row,6).Value =x['Like_Site'] worksheet.Cells(row,7).Value =x['Resolve_Tech_Issues'] worksheet.Cells(row,8).Value =x['Easy_Navigation'] worksheet.Cells(row,9).Value =x['Publish_Comments'] worksheet.Cells(row,10).Value =x['Answered_No'] worksheet.Cells(row,11).Value =x['Find_Support'] worksheet.Cells(row,12).Value =x['Find_Support_Other'] worksheet.Cells(row,13).Value =x['Find_Information'] worksheet.Cells(row,14).Value =x['Find_Information_Other'] worksheet.Cells(row,15).Value =x['Which_LEOnet_Site'] worksheet.Cells(row,16).Value =x['Visit_Again'] worksheet.Cells(row,17).Value =x['Visited_Old_Site'] worksheet.Cells(row,18).Value =x['Time_Spent'] worksheet.Cells(row,19).Value =x['Comments'] #adds bottom column headers to excel count = 0 titlerow = row +2 for x in columntitle: cell = columntitle[count] count = count+1 worksheet.Cells(titlerow,count).Font.Bold=1 worksheet.Cells(titlerow,count).Value = cell class SurveyParser(wxApp): def OnInit(self): frame = MainFrame(NULL, -1, "SurveyParser") frame.Show(true) self.SetTopWindow(frame) return true app = SurveyParser(0) app.MainLoop() Sample text file for web parser Name = Mourad Salji Location = Western Canada Transit = 05110 Position = Other Technical_Knowledge = Expert Like_Site = Yes Resolve_Tech_Issues = Yes Easy_Navigation = Yes Found_Everything = Yes Publish_Comments = Yes Answered_No = Find_Support = TSC_Telephone Find_Support = TSC_Web Find_Support_Other = (Other - describe here) Find_Information = TSC_Telephone Find_Information = Word_Of_Mouth Which_LEOnet_Site = (Which LEOnet site?) Find_Information_Other = (Other - describe here) Visit_Again = Daily Visited_Old_Site = When_A_Problem_Occurs Time_Spent = 5_Plus_Minutes Comments = B1 = Submit Name = Nelson Location = Eastern Canada Transit = 08271 Position = Other Technical_Knowledge = Expert Like_Site = Yes Resolve_Tech_Issues = Yes Easy_Navigation = Yes Found_Everything = Yes Publish_Comments = Yes Answered_No = Find_Support = TSC_Telephone Find_Support_Other = (Other - describe here) Find_Information = TSC_Telephone Which_LEOnet_Site = (Which LEOnet site?) Find_Information_Other = (Other - describe here) Visit_Again = When_A_Problem_Occurs Visited_Old_Site = Never Time_Spent = 5_Plus_Minutes Comments = great JOB B1 = Submit Name = Dina Della Porta Location = Eastern Canada Transit = 03511 Position = Other Technical_Knowledge = Expert Like_Site = Yes Resolve_Tech_Issues = Yes Easy_Navigation = Yes Found_Everything = Yes Publish_Comments = Yes Answered_No = Find_Support = Other Find_Support_Other = My own department Find_Information = Other Which_LEOnet_Site = (Which LEOnet site?) Find_Information_Other = surfing Visit_Again = When_A_Problem_Occurs Visited_Old_Site = Never Time_Spent = Less_Than_2_Minutes Comments = The site came in handy for a SECAF problem I was working on. B1 = Submit Name = MARYKE GAUVREAU Location = Western Canada Transit = 00620 Position = Branch - Other Technical_Knowledge = Average Like_Site = Yes Resolve_Tech_Issues = Yes Easy_Navigation = Yes Found_Everything = Yes Publish_Comments = Yes Answered_No = Find_Support = TSC_Telephone Find_Support = Word_Of_Mouth Find_Support = TSC_Web Find_Support = LEOnet Find_Support = Folio_HOCircular Find_Support_Other = (Other - describe here) Find_Information = TSC_Newsletter Which_LEOnet_Site = (Which LEOnet site?) Find_Information_Other = (Other - describe here) Visit_Again = When_A_Problem_Occurs Visited_Old_Site = When_A_Problem_Occurs Time_Spent = 5_Plus_Minutes Comments = B1 = Submit From h_schneider at marketmix.com Fri Sep 27 08:58:52 2002 From: h_schneider at marketmix.com (Harald Schneider) Date: Fri, 27 Sep 2002 14:58:52 +0200 Subject: SOLVED: py2exe Error creating NT Service References: Message-ID: Thanks for the hint! I solved the prob myself: must have been a tab or whitespace beyond the last line of the script. That irritated py2exe for some reason. After deleting everything after the last line it compiled well. Bye, Harald From bokr at oz.net Wed Sep 4 17:17:24 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2002 21:17:24 GMT Subject: Why read-only nested scopes? References: Message-ID: On Wed, 4 Sep 2002 19:46:49 GMT, Andrew Koenig wrote: >Gon?alo> Anyway, I've been directed to PEP 227, cheerfully obeyed, and >Gon?alo> from what I have understood having read-only nested scopes >Gon?alo> was more of a design decision than something else. And while >Gon?alo> I can live happily with the decision (some would even say >Gon?alo> happier) there is something about the "You can look at it but >Gon?alo> not touch it" attitude that I dislike ;-) > >You can do anything to the object that the object support. >What you can't do is change the binding of the name. > OTOH, if "everything is an object," then the namespace of an enclosing scope could also be an object, and as such could support rebinding of names therein ;-) The question would be how to spell such access. E.g., "global x" is a way to say that x=123 will be short for the effect globals()['x']=123 within a certain scope. If you visualized nested scopes as a list of scopes, starting with locals and ending with globals, you could refer to them by index, e.g., scopes[0] for local and scopes[-1] for global, and others in between, if any. If you treated those spaces like attribute name spaces, you could write a silly example like def foo(): x=123 def bar(): scopes[1].x=456 bar() return x and expect foo() => 456 Regards, Bengt Richter From missive at frontiernet.net Fri Sep 27 16:41:44 2002 From: missive at frontiernet.net (Lee Harr) Date: Fri, 27 Sep 2002 20:41:44 -0000 Subject: pygame.event.Event? References: Message-ID: In article , Max wrote: > Hi! > I can't generate a QUIT event in pygame: > pygame.event.Event(type, dict, [keyword_args]) -> Event > > What do I have to put in "dict"? > How about an empty dict? pygame.event.Event(QUIT, {}) From rs at onsitetech.com Tue Sep 3 11:25:02 2002 From: rs at onsitetech.com (Robb Shecter) Date: 03 Sep 2002 15:25:02 GMT Subject: Automatically find the source of a method invocation? References: <3D6FC3AF.30006@onsitetech.com> Message-ID: <3D74D43B.1090509@onsitetech.com> holger krekel wrote: > Why is this a problem? Well, you know; it's just clutter with zero information content since it must always be there. [...] > > It depends on what you really want to do. I wouldn't bother too much ... > Good ideas, thanks. I can see it'd take a bit of work. I pretty much just want an object receiving a PS message to be able to ignore it if it was the sender (for example). From michael at stroeder.com Thu Sep 26 11:01:24 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 26 Sep 2002 17:01:24 +0200 Subject: Page describing http compression with gzip. References: Message-ID: <53kb6-iu7.ln1@junker.stroeder.com> Alan Kennedy wrote: > > A few months ago, after spending a couple of days troubleshooting gzip > compression over HTTP, I put together a page describing how to do HTTP > compression in python, > [..] > http://xhaus.com/alan/python/httpcomp.html Thanks for writing it down. Things I'd like to note: Netscape Navigator 4.x (tested with 4.8) does not handle Transfer-Encoding: gzip. It displays garbage. Mozilla (tested with 1.1) shows a download select box. Netscape Navigator 4.x (tested with 4.8) does not display images which were gzip'ed. It is possible to deliver dynamic content of unknown length. Personally I've implemented my own wrapper class around gzip.GzipFile. Some people mentioned that it's necessary to add a header line Vary: Accept-Encoding Do you have more detailed information about that? Ciao, Michael. From vlcus at vlcank.co.jp Wed Sep 18 21:06:10 2002 From: vlcus at vlcank.co.jp (vlcus at vlcank.co.jp) Date: 19 Sep 2002 01:06:10 -0000 Subject: Win $ 4,000.00 in cash ! Message-ID: <20020919010610.13444.qmail@www.canausr.com> Dear Sir/Madam, This mail has been sent to persons who answered to the past questionnaire of our company. Now, we offer you the chance?to take part in our 'Questionnaire About Digital Camera and Color Printer' posted on our web site and to win $ 4,000.00in cash. This survey is intended for female only. Please visit now HERE http://www.vlcank.com/usa/index.html We think you will find this web survey very interesting and your input will help guide manufacturers to improve their products ! Once you qualify and complete our web survey, you will be automatically get a chance to win $ 4,000.00 in cash prizes ! Fill the questionnaire now and become the winner who will be randomly selected and get $ 4,000.00 in cash ! Sincerely, Sumio Muramatsu VLC Inc. * Please discard this message if you do not have any interest. * If you'd like to unsubscribe, Send mail to: vlcus at vlcank.co.jp From loewis at informatik.hu-berlin.de Fri Sep 27 06:37:21 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 27 Sep 2002 12:37:21 +0200 Subject: SET_LINENO References: <3D92A46E.2030706@cygnus-software.com> Message-ID: Michael Hudson writes: > > So, wouldn't a break-point opcode be a more substantial improvement > > than removing SET_LINENO? Just bringing up that old topic again to see > > if it gets any more traction :-) > > How would a breakpoint opcode differ from what SET_LINENO was? This is easy to answer: a breakpoint instruction could be inserted in the code at the points where the user wishes to have a breakpoint. Thus, with a breakpoint instruction, you could disable all tracing, and wait for the breakpoint callback. With such a scheme, you can have zero-overhead debugging, for breakpoints. If your debugger supports watchpoints, you get overhead, again. Regards, Martin From deltapigz at telocity.com Tue Sep 10 20:57:57 2002 From: deltapigz at telocity.com (Adonis) Date: Tue, 10 Sep 2002 20:57:57 -0400 Subject: test (ignore) References: <3d7e2957$1_2@nopics.sjc> Message-ID: <3d7e950e_2@nopics.sjc> oh im sorry i was not aware of that, just on another news thread i placed a post and did not show up for about 20mins later, thought it was a general issue with my server and i happened to be here and just ran a test. sorry if it incovenienced you in any way... Adonis "Gerhard H?ring" wrote in message news:slrnansspr.6im.gerhard.haering at lilith.my-fqdn.de... > Adonis wrote in comp.lang.python: > > just a test, please ignore. > > What exactly is wrong with alt.test or one of the other .test groups? > > -- Gerhard From bokr at oz.net Tue Sep 10 15:49:42 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Sep 2002 19:49:42 GMT Subject: Graph Layout Algorithms References: Message-ID: On Tue, 10 Sep 2002 14:37:00 +0100, "Duncan Smith" wrote: >Hello, > Just wondering if anyone has implemented anything in Python. I >need to lay out my graphs (directed acyclic / undirected / trees) in a >reasonably clear way. So if anyone has already implemented anything, or if >anyone has advice on appropriate algorithms, I'd be glad to hear about it. >Cheers. > >Duncan > > IIRC Ka-Ping Yee made some beautiful pdf(?) plots of python data structures, but I can't find anything right now. If the plotting software is open source and Python, that would sure be a treat. I think Guido made reference to some of the plots in some post. Anyone know where that stuff is? Regards, Bengt Richter From oren-py-l at hishome.net Tue Sep 10 10:30:13 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Tue, 10 Sep 2002 10:30:13 -0400 Subject: UNIX processes In-Reply-To: <200209101233.05796.b.maryniuk@forbis.lt> References: <200209101233.05796.b.maryniuk@forbis.lt> Message-ID: <20020910143013.GA71272@hishome.net> On Tue, Sep 10, 2002 at 12:33:05PM +0200, Bo M. Maryniuck wrote: > Hi, all. > Somebody know how to list all the processes in RIGHT way on Linux/UNIX? > I need to find the zombies, stopped processes etc. Ah, it's tricky. The output of the ps command is not consistent and the native API can be anything from variations on a /proc filesystems to actually looking at the kernel data structures. It's a lot of work to support all these different interfaces. Fortunately, someone already did the hard work - the lsof utility: http://ftp.cerias.purdue.edu/pub/tools/unix/sysutils/lsof/ (Thanks!) It lists all open files on the system and as a side-effect also reports a great deal of information about processes. It also has an output mode designed for parsing by other programs. It works for a large number of different platforms and is installed by default on many systems. Opening lsof with popen and decoding the output should be trivial. Oren From phncontact.libero.it at Wed Sep 4 04:14:02 2002 From: phncontact.libero.it at (Benjamin) Date: Wed, 04 Sep 2002 08:14:02 GMT Subject: Why Python? Message-ID: Hi guys (and girls) I just begun to learn how to program. And I choosed Python for doing that. surfing around the web i found an article about this language, they said it's the ideal language for beginners to the world of programming. and i admit it, the syntax is very clear making the code very readable, i learn easily the concepts of programming and i soon wrote some nice programs. but since i finished my newbie-tutorial, i am wondering about one question: is it worth to go deeper into python? i talked to a friend of mine, he told me that i should try php.. what should i do?? ^_^ in other words: what is python good for? why should i continue with python? thank you! _____________________________________________________ I'm going to prove the impossible really exists From james.kew at btinternet.com Sun Sep 8 16:18:04 2002 From: james.kew at btinternet.com (James Kew) Date: Sun, 8 Sep 2002 21:18:04 +0100 Subject: transform a list of lists in a lit of strtings??? References: Message-ID: "James Kew" wrote in message news:algah9$1p0kp3$1 at ID-71831.news.dfncis.de... > labels1 = [["D1"], ["D2"], ["D3", "D4"]] > --> labels2 == ["D1", "D2", "D3", "D4"] > labels2 = reduce(lambda x, y: x+y, labels1) > > Can this be written in list comprehension form? Emile's google link suggests (a) flattening is a hoary old chestnut, and (b) yes it can: labels2 = [i for item in labels1 for i in item] (I find this oddly hard to read.) James From merman at snafu.de Wed Sep 4 10:33:18 2002 From: merman at snafu.de (T. Kaufmann) Date: Wed, 04 Sep 2002 16:33:18 +0200 Subject: newbie-question: difference between classmethod and staticmethod in Python2.2 Message-ID: <3D7619AE.3050605@snafu.de> Hi there, can anybody explain the difference between 'staticmethod' and 'classmethod' in a simple way in Python2.2? When should I use staticmethod or classmethod in classes? I thought a staticmethod is a classmethod like in C++/ Java? Thanks for help. o-o Thomas From aleax at aleax.it Fri Sep 27 02:51:27 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 27 Sep 2002 06:51:27 GMT Subject: POP3 and Multipart Mime References: Message-ID: David McInnis wrote: > Does anyone know where I can find a tutorial on how to accomplish the > following? > > I need to log into a POP3 account (which I have been able to do using > poplib). > > I need to be able to read and decode the message. The problem is that > most of our users send word docs as attachments (1 or more). I need to > take these files and save them to disk. The email package, bundled since Python 2.2, makes it easy -- e.g.: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86676 Alex From glingl at aon.at Thu Sep 26 17:57:03 2002 From: glingl at aon.at (Gregor Lingl) Date: Thu, 26 Sep 2002 23:57:03 +0200 Subject: Who knows somefunction? References: <664e469667.69667664e4@icomcast.net> Message-ID: <3D9382AF.5070800@aon.at> Tim Peters schrieb: >[Gregor Lingl] > > >>Is there a function in Python for which >> >>something is (id(something)) >> >>returns invariably true? >> >> > >I'm not sure you're asking the question you intended to ask, but str() >is one answer to the question you actually asked. > > I don't think so: >>> something = [1,2,3] >>> something is str(id(something)) 0 How did you understand my question? (Errors should never pass silently) Gregor >uselessly y'rs - tim > > > > > From bbeck at REMOVE-THIS-TO-EMAIL-ME.austin.rr.com Wed Sep 4 11:59:03 2002 From: bbeck at REMOVE-THIS-TO-EMAIL-ME.austin.rr.com (Brandon Beck) Date: Wed, 04 Sep 2002 15:59:03 GMT Subject: Regexp Over Multiple Lines References: <565e316f.0209040740.36573b56@posting.google.com> Message-ID: Yes, please see the python online documentation for the re module (http://www.python.org/doc/current/lib/module-re.html) the section you specifically want is at (http://www.python.org/doc/current/lib/node99.html). You'll want to pass the VERBOSE flag to your compilation statement. pattern = re.compile(''' # comment ... # comment ''', re.VERBOSE); Additionally you may want to check out the regular expression howto at sourceforge (http://py-howto.sourceforge.net/regex/regex.html). Keith wrote: > In Python can I have a regular expression that spans multiple lines... > e.g. In Perl I may define a regular expression like: > > $depends_def = qr/ > [\w_\.]+\s*: # simobject: > \s* > [\w_\.]+ # job name > \(\s*(?:[\d]*)?\s*\) # arg list for job (optional > num) > \s+ > depends\s+on # keywords "depends on" > \s+ > (?: > [\w_\.]+\s*: # simobject: > \s* > (?: > [\w_\.]+ # job name > \(\s*(?:[\d]*)?\s*\) # arg list for job (optional > num) > (?: > (?: > \s+ > and\s*[\w_\.]*\s*: # "and simobject:" > \s* > [\w_]* # job name > \(\s*(?:[\d]*)?\s*\) # arg list for job (optional > num) > )+ > )? # match optional "and" 1 or > more times > ) > ) > /sx; > > then later I can use that regular expression in another regular > expression. > > It helps to span multiple lines for commenting what the heck the ugly > regular expression is trying to do... > > BTW: I am investigating Python and have no knowledge of it. Our Perl > code has just gotten out-of-hand. > > Thanks, > Keith From oren-py-l at hishome.net Sat Sep 7 12:10:37 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sat, 7 Sep 2002 12:10:37 -0400 Subject: Daemonize? In-Reply-To: References: Message-ID: <20020907161037.GA70503@hishome.net> On Sat, Sep 07, 2002 at 12:43:51PM -0000, A.M. Kuchling wrote: > Here's the daemonize function I use; I think Greg Ward originally > gave it to me. > > def daemonize (self): > # Fork once > if os.fork() != 0: > os._exit(0) > os.setsid() # Create new session > if os.fork() != 0: > os._exit(0) > os.chdir("/") > os.umask(0) > > os.close(sys.__stdin__.fileno()) > os.close(sys.__stdout__.fileno()) > os.close(sys.__stderr__.fileno()) devnull = os.open('/dev/null', 0) os.dup2(devnull, 0) os.dup2(devnull, 1) os.dup2(devnull, 2) This is safer because it prevents these file descriptors from being reused. Oren From stencelp at web.de Thu Sep 12 07:45:10 2002 From: stencelp at web.de (Paulus) Date: 12 Sep 2002 04:45:10 -0700 Subject: Starting external functions in Python applications Message-ID: <1d3ffc6b.0209120345.64cf64a1@posting.google.com> Hi. How can I link an external dll in a Python programs and (when possible) start any function from this DLL ? Thanks in advance paulus From Oschler at earthlink.net Wed Sep 18 20:07:00 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Thu, 19 Sep 2002 00:07:00 GMT Subject: PyLog, not require SWI-Prolog right? Message-ID: PyLog is inpendent of any Prolog interpreter right? There's PyLog and PyProlog, the latter I believe is a wrapper and therefore requires SWI-Prolog (just like bevedere requires GNU-Prolog), but PyLog doesn't, is that correct? Just looking for confirmation. Also, PyLog supports backracking right? thx From see_reply_address at something.invalid Tue Sep 24 22:18:34 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 25 Sep 2002 14:18:34 +1200 Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> <96zj9.150553$pX1.5399868@news2.tin.it> Message-ID: <3D911CFA.4060405@something.invalid> Alex Martelli wrote: > > Greg Ewing wrote > >>Using *tabs* only is the only way to get truly >>preference-independent indentation. > > ...unless other people use tools that do NOT let them change the > ways tabs are displayed, and that way is intolerably incompatible > with your use of tabs. I agree there are good reasons to prefer spaces-only for code that will be transmitted or displayed by dumb software. I was only pointing out that, whatever arguments there may be in favour of spaces-only, "it doesn't force the reader to view it the way you do" is not one of them! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From tdelaney at avaya.com Wed Sep 4 18:56:13 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 5 Sep 2002 08:56:13 +1000 Subject: Privacy and Inheritance Message-ID: > From: Eric Brunel [mailto:eric.brunel at pragmadev.com] > > In languages that have actual "private", "protected" and "public" > attributes, private attributes are not inherited. They are > visible only in > the class that define them, not outside it and not in its > sub-classes. What > you want is a protected attribute, that is visible in the > defining class > and in its sub-classes. > > Unfortunately, Python doesn't know anything about protected > attributes. > AFAIK, there's no simple way to do what you want: in Python, > attributes are > either private or public; there's nothing in between... Actually, there is. Anything beginning with a leading underscore is not imported via a 'from module import *' (not that anyone should in general use this ;) Thus anything with a leading underscore is something other than completely "public". There is a (strong) convention that anything beginning with a *single* leading underscore is "protected". No name mangling is performed, but the name is flagged as "special". class StandardNormal: def letEventZScore(self, eventZScore): self._eventZScore = float(eventZScore) class DerivativeNormal(StandardNormal): def getCentral(self): if self._eventZScore < 0: Tim Delaney From see_reply_address at something.invalid Tue Sep 24 23:30:11 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 25 Sep 2002 15:30:11 +1200 Subject: help with print function in extension References: Message-ID: <3D912DC3.7010302@something.invalid> Eric Hagemann wrote: > Traceback (most recent call last): > File "", line 1, in ? > SystemError: error return without exception set Check what your C function implementing str() is returning. My guess is that you've forgotten a "return 0" statement, and it's returning some junk value that in some cases the Python interpreter thinks is signalling an error. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From markus.vonehr at ipm.fhg.de Mon Sep 9 04:03:58 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Mon, 09 Sep 2002 10:03:58 +0200 Subject: compile error on SWIG file Message-ID: <3D7C55EE.D9278B1C@ipm.fhg.de> Hi, compiling my c-file generated from SWIG (swig -c -python -o mvelib.c mvelib.i) with a setup-file, I receive the error: c:\programme\vc98\include\eh.h(32) : fatal error C1189: #Error: "eh.h is only for C++!" Anybody knows what I have to change??? Thanks Markus **************************** setup.py **************************** from distutils.core import setup, Extension setup (name = "mvelib", version = "1.0", maintainer = "Markus von Ehr", maintainer_email = "markus.vonehr at ipm.fhg.de", description = "mvelib Python module", ext_modules = [Extension('mvelib',sources=['mvelib.c'])] ) From robin at jessikat.fsnet.co.uk Thu Sep 19 05:31:28 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Thu, 19 Sep 2002 10:31:28 +0100 Subject: cgi binary upload References: <3D88D492.1080909@mxm.dk> Message-ID: <3tD8sIAwlZi9EwoD@jessikat.demon.co.uk> In article <3D88D492.1080909 at mxm.dk>, Max M writes >Robin Becker wrote: ..... >That should not be a problem. I have not heard of the cgi module having >those kind of problems at least. > ....... > >I don't think your problem is with Python. You are probably having a >problem somewhere else in the chain. > >At least we should see some code, or you need to be more specific. > >regards Max M > > My colleague, who is doing the work reports that "I've just installed Apache 1.3.26 and the demo with file upload works completely, but still not with Apache 2.0.40 which I'm running in parallel." So that may be something to do with our difficulties. -- Robin Becker From thomas at xs4all.net Thu Sep 12 09:44:25 2002 From: thomas at xs4all.net (Thomas Wouters) Date: Thu, 12 Sep 2002 15:44:25 +0200 Subject: class variable won't icrement! In-Reply-To: <20020912131422.GB29027@meson.dyndns.org> References: <7647A9F4B298E74DB6793865DA67285004ADF4@exchange.adrembi.com> <20020912131422.GB29027@meson.dyndns.org> Message-ID: <20020912134425.GC797@xs4all.nl> On Thu, Sep 12, 2002 at 09:14:22AM -0400, Jp Calderone wrote: > On Thu, Sep 12, 2002 at 12:18:32PM +0200, Roman Yakovenko wrote: > > Hi it is simple just change > > self.id = self.id + 1 > > To > > test.id += 1 > Actually, that turns out not to be the case. += behaves differently > depending on its arguments - sometimes rebinding the name, sometimes > mutating in place. For integers, it can not mutate in place (ints are > immutable, of course!) so "self.id = self.id + 1" is exactly the same as > "self.id += 1". Were 'id' a mutable type, say a list, then the above > solution would work (assuming you changed 1 to something iterable). Notice how Ramon said 'test.id', not 'self.id. He's changing the class attribute directly, not through the instance. The switch from addition+assignment to augmented assignment is just a smoke screen :) -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From bbrelin at yahoo.com Wed Sep 18 15:07:45 2002 From: bbrelin at yahoo.com (Braun Brelin) Date: 18 Sep 2002 12:07:45 -0700 Subject: How do I find out which context I'm passing? Message-ID: I'm running into a strange problem. I've written a small e-mail sender python script for Zope/CMF/Plone. It gets activated from DCWorkflow. The script works fine when I test it from the "manage" interface, i.e. I save the script and then push the "test" button. When I try and run it from my portal, however, the script fails. The script looks like this: ---------------------------------------------------------------------------- members = context.portal_membership.listMembers() try: mailhost = getattr(context,context.superValues('Mail Host')[0].id) except: raise AttributeError,"Can't find a mail host object" addrs = [] for member in members: if 'Member' in member.getRoles(): email = member.getProperty('email') if email: addrs.append(email) #url = getattr(exprNamespace['object'].absolute_url()) url = 'test url' to_list = string.join(addrs, ',') mFrom = 'ciaran at localzope' mSubj = 'New Content' mailhost.send(url, to_list, mFrom, mSubj) #return to_list --------------------------------------------------------------------------- The script constantly gets a "No mailhost found" error. Which means, I presume, that the getattr(context, context.superValues()) function call fails. The only reason that I can think of for this happening is that the context that's passed when I test it via the manage window is a different context than that which gets passed within the users portal window. There is definitely a MailHost object defined within the portal application. Anybody have any thoughts on how to debug this? Thanks, Braun Brelin From pedronis at bluewin.ch Thu Sep 5 08:29:54 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Thu, 5 Sep 2002 14:29:54 +0200 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> <3d765ce6_4@news.bluewin.ch> <3d767c4a$1_1@news.bluewin.ch> Message-ID: <3d774f40$1_1@news.bluewin.ch> Ok, I have discovered an undocumented fact and maybe relevant fact. The JVM ignore the Xmx limit for classes, now classes are garbage collected if not used, but if that not the case and new classes are continously loaded the JVM will allocate memory up to exhaustion of total memory, instead of stopping at Xmx. Now one can log class loading, you can edit jython.bat and put -verbose:class in there: "..java.exe" -verbose:class "-Dpython.home=..." then running jython.bat you should get an initial burst of [Loaded ] and then normally nothing or a pattern of [Loaded ...] ... [Unloading class ...] If you get an increasing sequence of [Loaded ...] without corresponding [Unloading class ...] then we have reduced the possible suspects. regards. From cjw at sympatico.ca Wed Sep 18 11:05:30 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 18 Sep 2002 11:05:30 -0400 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <20020917.151708.502278611.1586@cybermesa.com> Message-ID: <3D88963A.F61FDD82@sympatico.ca> You might look at: http://www.scopal.com/information06.htm A digital oscilloscope is controlled by a PC, using wxPython and Python. Colin W. Lee Gray wrote: > Jay O'Connor wrote: > > > In article <96904b50.0209171305.6d65f574 at posting.google.com>, "Lee Gray" > > wrote: > > > >> > >> Can someone point me to a good Python GUI app to demonstrate (other than > >> IDLE)? > > > > Bioreason makes some products in Python. You can see some screenshots of > > their Python/Gtk products here: http://www.bioreason.com/lead.html and > > http://www.bioreason.com/drug.html > > > > Thanks, I'll show those. > > Lee From ledirach at wanadoo.fr Wed Sep 4 15:39:06 2002 From: ledirach at wanadoo.fr (Pierre-Yves Le Dirach) Date: 4 Sep 2002 12:39:06 -0700 Subject: Python critical mass /turning point References: <899f842.0209040617.711664fe@posting.google.com> Message-ID: X-No-archive:yes If i dare adding a word, I think you forgot at least one reason among "Suitability for commercial products" : 2.4) Human-readable and understandable source code (even for non-techies); Even if you could open a Perl program in vi (Notepad ?) and read it, no non-techie could understand it at first sight (sometimes even techies...;). But the day my boss (not a programmer, but a marketing guy) had a look on my Python source, he felt like he understood it. And most "Microsoft-minded" bosses can't consider selling "understandable" source to a client. Closed-source companies... Just my 2 cents. P. anthony_barker at hotmail.com (Anthony_Barker) wrote in message news:<899f842.0209040617.711664fe at posting.google.com>... > I have been trying to determine what is holding python back from > reaching the critical mass/success that perl/c++/Java have experienced. > Caveate - I am not a python guru - so some of the technical stuff may be wrong. > > I believe most of the issues are not technical - If technical features were > key to critical mass then LISP would be the main programming > language. > > 1. Interpreter Available on every desktop/server > Perl has this on the server > Java had this in the browser space > > Solution(s) > Parrot/Perl6 integration - the if python is included > with the perl interpreter it would be everywhere > Lobby Sun & IBM to include Python on their Unix CDs > Lobby Microsoft to get added to their resource kit > Other options are already available such as freeze.... > > 2. Suitability for commercial products > A couple of the problems I believe are technical and > reputation. > 1) Speed issue compared when compared with c/c++ > 2) The ability to enforce interfaces > Allow enforced type checking and encapsulation - people are often > surprised when they find out data is hidden in python. > 3) Access c libraries/apis seamlessly > > Solutions(s) > Speed issue I believe may be solved by psycho, and time. As python > matures it seems to be getting faster, while computers are getting > so fast speed matters less. > > Having a compiler would allow python to be know not only as a > scripting language. Unfortunately "scripting language" for some > is equivalent to - not a real language. Enforced interfaces > and the ability to enforce data hiding > > SWIG is doing a good job with the last issue. > > > 3) Big corporate sponsor(s) > IBM sponsors Java/Perl/C/C++ & Cobalt > by having IDEs and corporate support available for those languages. > > IBM supports PERL? > Surprise - Tivoli products are glued together with Perl > Lotus Unix server products use perl under the hood > Perl is shipped on every AIX box > Perl courses are available as is support > etc > > Microsoft Supports > VB/C/C++/c#/Java(kind of)/Perl etc > > Perl is included in the NT/Win2K resource kits > Also is part of the tools for Unix > > Sun > Java/Perl/etc > > Perl is bundled with Solaris > Sun Solutions has Perl courses available > > > Cheers, > > Anthony > http://xminc.com/anthony/ From mstenner at phy.duke.edu Thu Sep 12 10:53:05 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Thu, 12 Sep 2002 10:53:05 -0400 Subject: Coding Style: Quotes In-Reply-To: ; from javajohn@cox.net on Thu, Sep 12, 2002 at 02:25:11PM +0000 References: Message-ID: <20020912105305.A6508@phy.duke.edu> On Thu, Sep 12, 2002 at 02:25:11PM +0000, John Waycott wrote: > I'm curious if others have adopted any standards for choice of single vs. > double quotation marks to delimit strings. A look through the standard > library reveals the choice of one over the other is rather arbitrary. I > suspect it really makes no difference, but the question has come up during a > code review. Since there is no "physical" difference between them, I can't imagine why it would matter. The only reason there "needs" to be two is for nested quoting. Sure, it would be annoying to alternate for each string, but beyond that... Personally, my use tends to be c/perl influenced. I use single quotes for short static things and double quotes for longer things and format strings. f['key'] = "This is a long string, but it's just _my_ style..." -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From jkraska at san.rr.com Thu Sep 26 00:29:35 2002 From: jkraska at san.rr.com (Courageous) Date: Thu, 26 Sep 2002 04:29:35 GMT Subject: Larry Wall's comment on python... References: Message-ID: >Once upon a time, a large class of computers, and their attendant >peripherals, OSs and utility programs universally implemented tabs >hard-wired at 8 stops. Indeed; such is this issue that I leave hard tabstops as 8 in my editor, and set soft tab stops set to 4. What this means, in vim, is that when tab is struck it "takes the cursor to the next logical tab stop by inserting enough spaces to get it there." No real tab exists. In fact, I have to strike ctrl-V[TAB] in order to get a real one. I also use another setting that displays ascii-187 (?) wherever a tab is. This is nice for editing those nasty makefiles (that _REQUIRE_ tabs). The relevant parts of my .vimrc can roughly be summarized as follows: set tabstop=8 set softtabstop=4 set shiftwidth=4 set et "ascii-187==? set lcs=tab:?\ If you want to enter ascii-187 manually in vim (and can't cut out of this message) type ctrl-V187 C// From Oschler at earthlink.net Wed Sep 11 22:44:15 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Thu, 12 Sep 2002 02:44:15 GMT Subject: SpamBayes PIK file? References: Message-ID: <3cTf9.1805$Lg2.262739@news2.news.adelphia.net> "Tim Peters" wrote in message news:mailman.1031790134.7684.python-list at python.org... > [Robert Oschler] > > It's a binary pickle of a trained instance of class GrahamBayes in the code > base. If what to do next isn't instantly obvious, you should return the > .pik file for a full refund -- unless you're a developer on this > project, you don't stand much chance of getting any good out of it. > Thanks Tim, yeah there's two unexpected events that confuse me with Source Forge, since I've come to expect source code in project. That's one of them and the other's an empty project that points to a commercial package that doesn't even sell the source. :) thx From dag at animagicnet.no Mon Sep 30 05:53:21 2002 From: dag at animagicnet.no (Dag) Date: 30 Sep 2002 09:53:21 GMT Subject: is cPickle really this slow? Message-ID: I have a script which starts by parsing a large file and turning into a data stucture (a dictonary of lists) which I then use in the script. This operation however takes about 12-15 seconds. Since the file hardly ever changes , and if it changes it's because I changed it, thought I'd save some time by pickeling the datastructure and and simply getting that at the start of each script. So I pickle my dictionary, which ends up being a 3.2MB file and try to run my script again, this time getting the pickled dictonary instead of building it at runtime. This time however the script takes over 35 seconds to run, close to three times as long. Am I doing something wrong is loading and parsing larger pickled files really very slow. Dag From huaiyu at gauss.almadan.ibm.com Tue Sep 3 13:42:27 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Tue, 3 Sep 2002 17:42:27 +0000 (UTC) Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <1030962064.628232@ampungk.ozonline.com.au> <1031008966.343893@ampungk.ozonline.com.au> Message-ID: jepler at unpythonic.net wrote: >On Mon, Sep 02, 2002 at 09:23:18PM +1000, John La Rooy wrote: >> Carl Banks wrote: >> > >> >pattern = Group(Any()) + Group(Any()) + Group(Any()) \ >> > + GroupRef(3) + GroupRef(2) + GroupRef(1) >> > >> Err symantically that's exactly the same as the re and my suggestion >> only the syntax is different. It's still nothing like saying >> >> pattern = "6 character palindrome" > >Do you mean something like this? > > def palindrome_re(n): > pat = ["(.)" * ((n+1)/2)] > for i in range(n/2, 0, -1): > pat.append("\\%d" % i) > return "".join(pat) [snip] > >I think that building REs in functions is a great approach for more >complex REs. It would also be useful if patterns can be built up as structured objects: def palindrome_re(n): pat = Empty() for i in range(n): pat += Group(Any()) for i in range(n, 0, -1): pat += GroupRef(i) return pat class Palindrom: def __init__(self, n): self.n = n def __call__(self): return palindrome_re(self.n) pattern = Palindrom(6) Once the tree structure is revealed it could be mapped to whatever syntax that is convenient for the situation. The perl-like syntax would just be one of them. Huaiyu From astavale at yahoo.co.uk Fri Sep 13 14:48:34 2002 From: astavale at yahoo.co.uk (Alistair Thomas) Date: Fri, 13 Sep 2002 18:48:34 GMT Subject: Signals for GtkEntry widgets References: Message-ID: <6qqg9.509135$Aw4.21217664@bin2.nnrp.aus1.giganews.com> In article , "David Shifflett" wrote: > I am trying to find which signal is emitted when the user presses Enter > while in a GtkEntry widget. The signal is key_press_event. Which returns a GdkEvent object. The keyval attribute tells you which key was pressed. I use Glade and my sample code is based on my own module which uses libglade, hope this helps: import gtk, GDK # My own module based on libglade: import window class text_entry ( window.open ): def __init__ ( self, title = 'Enter text:', text = '' ): window.open.__init__ ( self, 'text_entry' ) self.add_handlers ( { 'on_key_press' : self.key_press, 'closed' : self.closed } ) self.get_widget ( 'text_entry' ).set_title ( title ) self.modified = 0 self.text = text a = self.get_widget ( 'text' ) a.set_text ( text ) a.grab_focus () gtk.mainloop () def key_press ( self, widget = None, event = None ): if event.keyval in [GDK.Return, GDK.KP_Enter] : self.text = widget.get_text () self.modified = 1 self.close () gtk.mainquit () def closed ( self, widget = None ): gtk.mainquit () -- Al From oliver.smith at removethisbit.baesystems.com Thu Sep 5 06:31:40 2002 From: oliver.smith at removethisbit.baesystems.com (Olly Smith) Date: Thu, 5 Sep 2002 11:31:40 +0100 Subject: Returning lists from python COM servers Message-ID: <3d7731f5$1@pull.gecm.com> Using this snippet on the server side: == return (tags,vals) == Where tags and vals are equal length lists (actually a dict that maps strings to strings split up so it can be returned from the COM object) This snippet on the client side: == tags,vals = self.prodcat.getPDF(id) == I get this error (mildly snipped cgitb output): == 547 tag,val = self.prodcat.getPDF(id) ValueError: unpack tuple of wrong size __doc__ = 'Inappropriate argument value (of correct type).' __getitem__ = > __init__ = > __module__ = 'exceptions' __str__ = > args = ('unpack tuple of wrong size',) == Any ideas on where I'm going wrong? I'm pulling my hair out trying to work this one out. Thanks Olly From SBrunning at trisystems.co.uk Thu Sep 26 05:19:49 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 26 Sep 2002 10:19:49 +0100 Subject: jython web scripting options Message-ID: <31575A892FF6D1118F5800600846864DCBD880@intrepid> > From: Stefaan Nachtergaele [SMTP:snacht at xs4all.nl] > I'm prototyping a three tier web application in java. I've looked at a lot > of java web frameworks but for development speed nothing compares to web > scripting languages like php, etc. But that's not an option for me cause I > need to talk with my server side java code (php-java integration is > dinky). > My question is, what options are there for jython. Why not stick with J2EE, and code your servlets, tags etc. in Jython? See for some simple examples. Oh, and have a look at struts - see . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From a12345 at ms1.url.com.tw Sat Sep 21 15:58:09 2002 From: a12345 at ms1.url.com.tw (Decent) Date: 21 Sep 2002 12:58:09 -0700 Subject: WxString and python string module? Message-ID: <36de4780.0209211158.2fc3815@posting.google.com> Dear all: I'm trying to rewrite my apps using wxpython, but how do I convert WxString object to python string? I have to use python's default string module, not the wxWindow's WxString. Any Idea? From ehagemann at comcast.net Wed Sep 25 17:03:30 2002 From: ehagemann at comcast.net (Eric Hagemann) Date: Wed, 25 Sep 2002 21:03:30 GMT Subject: help with print function in extension References: <4jfk9.163306$pX1.5842487@news2.tin.it> Message-ID: Alex, Thanks -- missed that section in the manual. I blindly assumed that I could use the repr() as the print func...... ok so for the next trick question. I implemented a function that has the proto int print_func(PyObject *obj, FILE *fp,int flags) when I try to print to fp -- as in --> fprintf(fp,"", , )... I crash the program. when the print function is used and output is sent to the screen is the fp set equal to stdout ? The example in the "Extending and Embedding the Python Interpreter" show a fprintf to fp as might be expected ?!? Cheers "Alex Martelli" wrote in message news:4jfk9.163306$pX1.5842487 at news2.tin.it... > Eric Hagemann wrote: > > > I'm handcrafting an extension in C > > > > If have defined both a str() and a repr() function and when I execute > > either repr(obj), or str(obj) I get what I expect > > > > however if I execute 'print obj' I get the following error > > > > Traceback (most recent call last): > > File "", line 1, in ? > > SystemError: error return without exception set > > > > although 'print str(obj)' works like I think it should > > > > Am I mistaken in thinking that 'print str(obj)' should be the same as > > 'print obj' > > *ALMOST!* In the PyTypeObject struct, there's a tp_print slot > that is used by preference, if non-null, when you print something > and stdout is a real file. What do you have in tp_print for > your type? It's smack in-between tp_dealloc and tp_getattr. > > > Alex > From a_salnikov at yahoo.com Mon Sep 2 03:16:54 2002 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Mon, 2 Sep 2002 00:16:54 -0700 Subject: Python GUI References: <3d8d3c0.0208262339.e7bc02c@posting.google.com> <3D6FBB3B.5090700@river-bank.demon.co.uk> Message-ID: "Lothar Scholz" wrote in message news:r794nugam0su9metpaas0nobn4jsm84j3j at 4ax.com... > On Fri, 30 Aug 2002 19:36:43 +0100, Phil Thompson > wrote: > > >Or take the Qt (and PyQt) approach and implement all styles on all > >platforms and let the user decide on a global or per application basis > >with a simple command line argument. > > Thats completely wrong it the user selects a style from the OS style > manager. At least for MacOS Users this is very popular and then > your QT application looks again like an alien. Same is true for WinXP Qt on Windows actually uses whatever style is current on the host (in other words Qt uses native widgets). On X11 they have their own configuration utility which changes style of Qt-based applications. Problem with X11 is that there is no "OS style manager" (whatever this could mean) for X11, or there is no _single_ style manager. Andy. From phil at river-bank.demon.co.uk Sat Sep 28 04:51:50 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Sat, 28 Sep 2002 09:51:50 +0100 Subject: how to create QLineEdit.focusOutEvents? In-Reply-To: References: Message-ID: <200209280951.51269.phil@river-bank.demon.co.uk> On Friday 27 September 2002 10:05 pm, Hans - G. Normann wrote: > Hello > > I'm new in QT and Python. My first project: creating a GUI for Linux tar > command. My prob: > > A QLineEdit contains a directory name. I can create this name by clicking > (Fileselection maodule) or by type in. On lost focus, I want check the > Directoryname, but how can I create slots, signals and the event for Line > Edit? > > For creating gui, I'm using QT's designer. It's works fine, except > focusOutEvent. Is there a (easy) sample? Sub-class QLineEdit and re-implement focusOutEvent() in your sub-class. Phil From dallasm at aiinet.com Wed Sep 11 14:38:03 2002 From: dallasm at aiinet.com (Mahrt, Dallas) Date: Wed, 11 Sep 2002 14:38:03 -0400 Subject: Distutils/setup help Message-ID: <638AA0336D7ED411928700D0B7B0D75B02E1EF96@aimail.aiinet.com> I am in the process of making modifications to the Python build system to aid in the cross-compilation of Python. A primary problem I am running into involves the module detection logic In PyBuildExt::detect_modules() of setup.py. It is determining what modules to build based on the build system. I have modified 'Modules/Setup' to remove some modules from being compiled, but I would still like to be able to specify more cleanly which modules to compile and the necessary flags to use for the hosts system. Is there currently a way to make these specifications? If not, does anyone have any suggestions for a clean longer-term solution? Is this the right list to ask these questions? Thanks. --- Dallas S. Mahrt 614-923-1194 Software Engineer Network Management Systems Applied Innovation Inc. Dublin, Ohio From observer at NOSPAM.space.pl Wed Sep 25 10:17:16 2002 From: observer at NOSPAM.space.pl (Johann) Date: Wed, 25 Sep 2002 16:17:16 +0200 Subject: Python mixed with HTML like PHP Message-ID: I heard about project which can mix python cgi code with html content. I forgot its name. Who remember? -- Johann From al at metroic.no Mon Sep 23 14:54:44 2002 From: al at metroic.no (Andreas Lydersen) Date: Mon, 23 Sep 2002 20:54:44 +0200 Subject: Dynamic loading of modules Message-ID: Hi, I'd like to load a set of modules from a directory. I have tried to use the __import__(...) statement to do so, but with no success. ? The static approch works (of course), but the dynamic does not! static: import plugins.Password dynamic atttempt: __import__("plugins.Password") I have tried 'exec "plugins.Password"', and that works. However, I need to get a list of pointers to the modules I import in order to work with them later. Bottom line is: I need to know how to dynamically load modules and get a pointer to the same module. Any help is appreciated. -- Johan Fredrik ?hman From linuxbrad at rogers.com Thu Sep 12 14:59:56 2002 From: linuxbrad at rogers.com (Brad Fonseca) Date: Thu, 12 Sep 2002 18:59:56 GMT Subject: [newbie] Buying an introductory/reference text Message-ID: Greetings! I'm looking for a few opinions on the above subject. I'm a computer science student who has had some introductory lectures on Python and I've done some very basic mucking around with. I'm looking for a clear reference and/or introductory text. Any suggestions would be nice. I have looked at http://www.python.org/cgi-bin/moinmoin/IntroductoryBooks but there appears to be a number of good books to choose from there. Regards, -- --- Brad Fonseca From pinard at iro.umontreal.ca Tue Sep 3 21:23:27 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Tue, 03 Sep 2002 21:23:27 -0400 Subject: Pyrex 0.4.4 In-Reply-To: ("Delaney, Timothy"'s message of "Wed, 4 Sep 2002 10:33:34 +1000") References: Message-ID: [Delaney, Timothy] >> I noticed too. To get going, I got Plex installed separately, and removed >> the 'Plex' line in `setup.py' for Pyrex. > I decided against that, since one of the ficed bugs was in Plex. I wondered a bit as well. But since the Plex bug never hit me so far that I know, it would take some bad luck for being hit now. The fact that Pyrex traceback got nicely integrated in the overall Python feedback is a nice feature, which outweigh the fear of the Plex bug. In one application, I use Pyrex to embed Python within a Bison generated parser and a Flex scanner, that is, within C code. This afternoon, I got Pyrex to generate some code, then cut-and-pasted the traceback tricks it uses into a new C module, which the parser calls after a Python returns an error. So even the C code is properly referenced in the traceback. Wonderful! -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From kennethg at pd.jaring.my Sat Sep 21 23:59:41 2002 From: kennethg at pd.jaring.my (Kenneth Gomez) Date: Sun, 22 Sep 2002 03:59:41 GMT Subject: Local Python Server Installation References: <3d8b47c6.277669@news.jaring.my> <3d8c993c.2190426@news.jaring.my> Message-ID: <3d8d4009.375344@news.jaring.my> Chris, you're right. It's an Apache config problem. I'll dig into the doc's. Thanks, Regards, Kenneth. On Sat, 21 Sep 2002 11:31:50 -0500, "Chris Gonnerman" wrote: >----- Original Message ----- >From: "Kenneth Gomez" > > >> I tried your method. But instead of getting a cgi listing of >> my environmental listings, all I saw on my browser was the >> two input lines ..i.e. import cgi and cgi.test() > >Your cgi is being displayed rather than executed. The >configuration options for Apache are so complex, that entire >books have been written about configuring it... and Gerhard's >suggestion only works on Windows platforms (AFAIK). You didn't >name your platform, did you? Or did I just miss it? > >You need to verify that Apache 1) recognizes .py files as CGI >scripts, and 2) allows you to run a CGI in the folder you're >putting it in. You probably should put your script in the >cgi-bin directory to start with. If you are on a Unix/Linux >system, you need to make sure that the script is marked >executable. > >Really, I think you need to spend some time with the Apache >docs. It isn't a Python problem per se. > >Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net >http://newcenturycomputers.net > > Cheers, Kenneth Gomez. From pknotz at sandia.gov Tue Sep 24 15:27:53 2002 From: pknotz at sandia.gov (Pat Notz) Date: 24 Sep 2002 12:27:53 -0700 Subject: Copying Elements using PyXML References: Message-ID: <525eaba.0209241127.1ec90a6@posting.google.com> This is an untested snippet of code that should get you started. It looks like you'll want to do you .appendChild on a node other than .documentElement... # Merge subsequet DOMs dom = None for xmlfile in xmlfiles: tmp_dom = xml.dom.minidom.parse(xmlfile) if dom == None: dom = tmp_dom else: for node in tmp_dom.documentElement.childNodes: e = dom.importNode(node,True) dom.documentElement.appendChild(e) From anthony at computronix.com Wed Sep 18 00:31:34 2002 From: anthony at computronix.com (Anthony Tuininga) Date: Tue, 17 Sep 2002 22:31:34 -0600 Subject: can wxpython do this? In-Reply-To: <3d87fbfc@news.sentex.net> References: <737aefee.0209151702.3f735252@posting.google.com> <3d854b44@news.sentex.net> <3d87fbfc@news.sentex.net> Message-ID: <1032323500.23315.0.camel@localhost> I have written a set of routines similar to py2exe and I know that Gordon McMillan's installer does similar things as well. Both of these options are cross-platform. So which platforms do you need to have this run on? On Tue, 2002-09-17 at 22:07, Peter Hansen wrote: > Erick wrote: > > > A better option, although I haven't tried it myself, would be > > > to use py2exe to build an executable, then package that up > > > > thanks Peter, but I was talking about something cross-platform. As py2exe's > > page says: > > > > py2exe is a distutils extension to convert python scripts into > > executable windows programs, which are able to run without > > requiring a python installation. > > > > > > do you know if it works across platforms? > > I don't believe the current solutions are cross-platform, but > it could be feasible to build a meta-packager which uses the > appropriate package to build executables for different platforms > by calling on the appropriate platform-dependent packager. > > Anyway, do you really want all platforms, or a specific subset? > > -Peter > > -- > http://mail.python.org/mailman/listinfo/python-list From markus.vonehr at ipm.fhg.de Tue Sep 10 02:56:38 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 10 Sep 2002 08:56:38 +0200 Subject: compile error on SWIG file References: <3D7C55EE.D9278B1C@ipm.fhg.de> Message-ID: <3D7D97A6.A63610AF@ipm.fhg.de> Hi Lyle, thanks for your answer and your efforts! I changed everything to .cpp The first error has gone Now I have an error (translated from german): mvelib.obj: error LNK2001: unresolved external symbol initmvelib build\temp.win32-2.1\Release\mvelib.lib : fatal error LNK1120: 1 unresolved reference LINK : fatal error LNK1141: Creation error of export file error: command 'c:\Programme\VC98\BIN\link.exe' failed with exit status 1141 Markus Markus von Ehr schrieb: > > Hi, > > compiling my c-file generated from SWIG > (swig -c -python -o mvelib.c mvelib.i) > with a setup-file, I receive the error: > > c:\programme\vc98\include\eh.h(32) : fatal error C1189: #Error: "eh.h > is only for C++!" > > Anybody knows what I have to change??? > > Thanks Markus > > **************************** > setup.py > **************************** > from distutils.core import setup, Extension > > setup (name = "mvelib", > version = "1.0", > maintainer = "Markus von Ehr", > maintainer_email = "markus.vonehr at ipm.fhg.de", > description = "mvelib Python module", > > ext_modules = [Extension('mvelib',sources=['mvelib.c'])] > ) From jo at johnochiltree.uklinux.net Mon Sep 16 03:04:42 2002 From: jo at johnochiltree.uklinux.net (John Ochiltree) Date: Mon, 16 Sep 2002 08:04:42 +0100 Subject: couldnt find __dic__ References: <7153651c.0209151958.4099ac3e@posting.google.com> Message-ID: "black" wrote in message news:7153651c.0209151958.4099ac3e at posting.google.com... > my book told me all dictionaries have __dic__ method but I searched > each dictionaries and find nothing, where is it ??? I think you'll find your book has a misprint try __dict__ instead. John From see_reply_address at something.invalid Tue Sep 10 01:32:47 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 10 Sep 2002 17:32:47 +1200 Subject: dynamism References: <66715c02.0209091923.265fe77e@posting.google.com> Message-ID: <3D7D83FF.6070202@something.invalid> Steven Shaw wrote: > > I thought you could just extend an object's attributes at run-time like this: > >>>>p = object() >>>>p.x = 1 It seems that you can't do this to an instance of "object" itself, because it's a built-in type. But you can do it to a subclass of object: >>> class C(object): ... pass ... >>> c = C() >>> c.x = 1 >>> print c.x 1 >>> > I thought that you could access dictionary values with object syntax: > >>>>x = { 'a': 1, 'b':2 } >>>>x.a No, that has never been possible. But instances have a __dict__ attribute that holds all the other attributes, so you can do this: >>> x.__dict__['a'] = 42 >>> print x.a 42 >>> -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jacek.generowicz at cern.ch Tue Sep 24 10:55:46 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 24 Sep 2002 16:55:46 +0200 Subject: Three dumb questions (ordered by dumbness descending) References: Message-ID: Steven Feil writes: > Humm, what is is zip(), a function in the standard Python library or > is it something you or someone else made up? I did a quick search in > the Python docs and the only zip I found referred to zip > compression. If this is something from the standard Python libraries > please state the library it comes from. Python 2.2.1 (#3, Jun 4 2002, 09:56:27) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> zip >>> print zip.__doc__ 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. >>> or even > pydoc "zip" Python Library Documentation: built-in function zip zip(...) 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. From aleax at aleax.it Thu Sep 19 11:23:36 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 15:23:36 GMT Subject: Python sequences reference - problem? References: Message-ID: Michal Kaukic wrote: > Hi, > > we like Python - I use it (with Numeric and SciPy modules) > for teaching of Numerical analysis and my colleague is doing > some research in discrete optimization in Python. And he often > surprises me with non-conformal use of language :-) > > We are mathematicians, not programmers. I suppose, he believes > that Python "thinks" like Mathematician. Yesterday, he was struggling I think the concept of "MODIFYING an object" is pretty far from most areas of maths I've dabbled in (I'm an engineer, not a mathematician, but do find maths fascinating). It seems to me that the only real way to get a language that WILL "think like a mathematician" is to take your pick among languages that have no concept of "modifying an object" - which nowadays basically means, Functional Programming languages. Personally I find Haskell the most elegant one -- clean syntax (uses whitespace much like Python), clean semantics (lazy evaluation the default everywhere). Last I checked, the best Haskell compilers were able to produce very decent code for many problems -- performance will in most cases be better than Python's. If you want even MORE performance, I suspect some less-puritanical but still FP language (such as O'Caml) can probably deliver it. If for some reason you don't want to get into FP, then I think you can forget everything about "thinking like a mathematician". If data modification IS allowed, then your chosen language needs to choose either of two possibilities: -- COPY-semantics: an assignment such as x = y inherently copies y, so that any future change to y has no more effect on x -- REFERENCE-semantics: an assignment such as x = y makes x a synonym of y, so that both refer to the same object: any future change to that object affects any synonym for the object equally Many languages choose a MIX of these two kinds of behavior, but that's the worst of both worlds, as it complicates things a lot. Generally, OLD languages (such as Fortran) relied on copy semantics (references or synonyms were not considered, and when they could happen, as in argument-passing, they were prohibited by the language rules, although those rules were rarely enforced). Modern languages by and large have moved to reference semantics, which is generally much cleaner even though in some cases performance can suffer (optimization is the main reason some languages complicate things by mixing reference and copy semantics). "Generally" is important: LISP, one of the oldest languages around (second-oldest after Fortran, among those still widely used today), relied on reference semantics from the start. The resulting elegance has much to do with Lisp's acceptance in the mathematical community, IMHO. Python uses reference semantics. When you want a copy, you ask for a copy -- it's as simple as this. If you don't ask for a copy, you don't get a copy... you get a reference to the original. There is no complication: it's _always_ this way. (OK, OK, at the margin there are doubtful cases: in particular, a SLICE is a copy-request for all built-in types, but a reference, sharing data with the original array, when you use the Numeric package... Numeric had to move _away_ from copy and onto reference in this case to avoid accidental copies of huge array slices... take this as the exception that proves the rule, OK?-). Python does have some data types that are immutable, which helps move it a little bit closer to FP -- numbers, strings and tuples are immutable. (Even Java has strings as immutables -- SOME of FP's niceties do start to move into the mainstream, albeit slowly:-). But the main style is still very much NOT FP, rather relying on modifiable data. > with the code shown below (somewhat simplified): > > > L_L=[[1,2,3], [2,3,4], [3,4,5]] > > def do_process(LL): > n=len(LL[0]) > rec = [0]*n > Res=[] > > for row in LL: > rec[0] = row[0] > # further code - modifying rec > # lots of conditional processing and such... > # ... > Res += [rec] > > return Res > > --------------------------------------------- > > After calling do_process(L_L), the "expected" result should be > > [[1, 0, 0], [2, 0, 0], [3, 0, 0]] > > but the true result is > > [[3, 0, 0], [3, 0, 0], [3, 0, 0]]. > > > Yes, this is fully in accordance with how the Python language should > behave: > Res += [rec] inserts references to list object rec, > which are further modified... (he should use copy(rec) instead). Right in all respects, yes. > But there is nothing to make this behaviour clearly VISIBLE in code. *EVERY* assignment in Python uses reference semantics. Every occurrence of an assignment, therefore, makes reference behavior "clearly VISIBLE". Presumably fish don't find water "clearly VISIBLE", being used to that, much as it is for us and air. When something "is *EVERYWHERE*", how can it be "clearly VISIBLE" at the same time?-) > If I work with pointers in C/C++ I know and see they are pointers. That's because C uses copy semantics, and uses pointer to emulate reference semantics when needed. That's just the reverse of Python, which uses reference semantics, and explicit calls to copy to emulate copy semantics when needed. C++ lets you define "references" which IMPLY reference semantics rather than copy semantics -- and you don't SEE what they are at the point of use (only at the point of definition). Flaming about that here, one way or another, won't be very useful:-). But there are LOTS of precedents: Pascal (!!!) lets you declare arguments to a procedure as either reference or copy -- then you don't see the difference at the point of use; Visual Basic emulated that, too (the default has changed in recent releases of VB, but that's -another- flame:-); languages with sophisticated macro systems, such as Dylan or relatively-recent LISPs, let you do all that and worse. But C and Python are SIMPLE languages: one semantics is pervasive (reference for Python, copy for C), you take explicit measures when you want the OTHER semantics, and those measures are visible at the point of use (well, _mostly_ -- C does complicate things a bit by having arrays "decay to" pointers, Python has the "slice aren't copies in Numeric" issue -- but that's definitely at the margin). > You can say - we also know that rec is list object and so be careful > with it. Yes, but consider the complex code where the similar constructs > are very easy to overlook. And debugging of such code can be frustrating. The issue has nothing to do with rec being a list object, really. You may see the issue as having to do with the fact that rec is (any kind of) *MUTABLE* -- indeed, a language without mutable data DOES shield you from these issues. If you tried to mutate non- mutable data, as rec[0] = .... does, you'd get an exception at runtime (if every kind data was immutable, of course, the language wouldn't even have any CONSTRUCTS to express mutation). > My colleague was in state of despair and made thoughtful remarks > about FORTRAN and Python similarity. He believes that Python is corrupting > his (computer) memory... Fortran (up to F77 -- I lost touch with it afterwards) had reference semantics in all parameter passing to subprograms (with aliasing forbidden in rather complex ways -- very few compilers ever enforced that, letting the hard-to-debug cases for the programmers:-)), copy semantics for all assignments. I can't see any parallel between that and Python's behavior, not even in the "anti-parallel" sense of Python // C. > So what is the point? I wrote this message in hope that there are > more people with similar experience. My question is - how to explain > to novice non-programmer users (maybe mathematically "infected") > the quirks of Python sequence objects? Which methodology to use First of all, somebody with reasonable math bent will prefer a more general explanation -- so, forget sequence objects, because that's just one specific cases. ALL object-mutation works the same way, whether it be of a sequence or non-sequence. > in programs so we can clearly see we work with "pointers"? You're in water. Water is *everywhere*. When you think there is nothing there, there's water. Just get used to it. Trying to muddy up the water in an attempt to make it more visibile would be counter-productive. > Or maybe someone can propose the changes to the Language to overcome > this (psychological) barrier? I feel this as a serious obstacle > in using Python (my students experienced it too). It appears, though you never state it, that the behavior you would consider "natural" would have to do with copy semantics. I find that weird, absolutely weird -- I've seen it happen to old died-in-the-wool programmers without solid mathematical bases, because for 20 or 30 years of their lives they had only seen copy semantics and could no longer conceive of any other, but that's exactly the reverse from the "mathematical bent" you keep mentioning. Accepting your mention of "mathematical bent" as relevant, I repeat my suggestion that you look into functional programming. FP is seriously cool, IF all the programmers involved have a solid mathematical outlook on life, the universe and everything. If for whatever reason you want to keep using languages based on the idea of data modification, you won't find a simpler or more regular one than Python. And it would be absurd to pick old-enough languages that use copy semantics because some previous experience (NOT with maths itself, surely?!) makes you feel that's natural and divergences from it should be made "very VISIBLE" -- besides Python, you'd be cutting yourself off from Java, Eiffel, C# ... reference semantics IS the wave of the last decade-plus, and probably of the next one too (unless FP comes into its own, but I've sort of stopped holding my breath for THAT -- there just isn't enough of an audience with a pervasive-enough mathematical turn of mind:-). Just remembed that EVERYTHING works by reference, and what could possibly be the problem...? Alex From sholden at holdenweb.com Fri Sep 27 09:16:41 2002 From: sholden at holdenweb.com (Steve Holden) Date: Fri, 27 Sep 2002 09:16:41 -0400 Subject: Local Python Server Installation References: <3d8b47c6.277669@news.jaring.my> <3d8c993c.2190426@news.jaring.my> <3d8d4009.375344@news.jaring.my> Message-ID: "Kenneth Gomez" wrote in message news:3d8d4009.375344 at news.jaring.my... > Chris, you're right. It's an Apache config problem. I'll dig into the > doc's. The Wrox book "Professional Apache 2.0" is helpful if you need to understand how Apache works and, despite its title, it alos covers older versions of Apache. If you want to write servers in pure Python you could look at "Python Web Programming", but you will probably find you can get a lot further than you thought with simple CGI, then you'll know enough about other directions you'd like to go. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From peter at engcorp.com Wed Sep 4 08:42:47 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 04 Sep 2002 08:42:47 -0400 Subject: Matching a string up to a word References: Message-ID: <3d75ffaa$1@news.sentex.net> Dag wrote: > I have a string that contains an ID number a file path and a date, kind > of like this: > > 23545 /this/is a/path/to/a file Sun Sep 7 2002. > > I want to extract the file name. If I could be sure that the file path > had no spaces or if it would be quited it would be easy. Unfortunatly > many files will have spaces and changing the format of the output I'm > dealing with isn't possible. I do however know that the file name starts > after the first whitspace and that it's always followed by a three letter > day name (like Mon, Tue etc.) Given this is there an easy way to extract > the whole file path from the string. Not unless you can restrict the possibilities still further. What if the file name ended with a space and a three-letter name? Can you instead guarantee the format of the date that follows the filename? Will it always consist of the day of the week, the month, the date, and the year? That would turn this into a relatively simple problem. -Peter From peter at engcorp.com Tue Sep 10 00:04:11 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 10 Sep 2002 00:04:11 -0400 Subject: Windows/DOS: double clicking a .py file References: Message-ID: <3d7d6f26@news.sentex.net> David LeBlanc wrote: > cmd.exe will accept a flag telling it to stay open after something is run. > You can create a shortcut along the lines of: > > cmd /K python myscript.py [snip rest] Although, unfortunately for the OP who has users on Win98, cmd.exe does not exist except in NT/2K/XP. -Peter From buzzard at urubu.freeserve.co.uk Fri Sep 6 20:19:13 2002 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sat, 7 Sep 2002 01:19:13 +0100 Subject: RPy / Win2k Message-ID: Hello, Is there anyone out there who has successfully used RPy under Win2k? I get the impression (from Brian Ripley) that it should be possible to embed R under Win2k, but that it probably isn't straightforward. Can anyone help? Cheers. Duncan From kapis at hotmail.com Sun Sep 15 01:23:22 2002 From: kapis at hotmail.com (Richard) Date: 14 Sep 2002 22:23:22 -0700 Subject: Problem w/ boost_python_debug.dll Message-ID: I'm using Boost.Python (v1) to embed & extend a C++ application. I've downloaded ActiveState's distribution and built the debug python library and DLL. I built the release and python-debug versions of Boost.Python as is documented. I also define BOOST_DEBUG_PYTHON in my C++ files since I have the debug python libraries. Enough with the background, let's get to the problem. For debug builds, I link with boost_python_pydebug.lib. But when I run the program, it still tries to load up boost_python.dll, NOT the debug version! The only way I know to fix the problem is to rename boost_python_pydebug.dll so that it is loaded instead. Does anyone know a better fix? Any help would be appreciated. Thanks. From jb at cascade-sys.com Mon Sep 9 21:02:58 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Mon, 09 Sep 2002 18:02:58 -0700 Subject: Python primer - comments appreciated! References: Message-ID: <3D7D44C2.10901@cascade-sys.com> Thorsten Kampe wrote: >"Python, anyone?"... Yep, this is my first one. Comments on >style/readability and technique/flow appreciated! > Looks good overall, certainly you're off to a good start. I added a few remarks/answers below... --jb > > >#v+ >def quotient_set(seq, func, partition='nonbool'): > """ partition into equivalence classes > > With the 'bool' parameter 'quotient_set' always returns two lists: the > first containing the 'true' items and the second containing the false > ones. """ > if partition == 'bool': > # Yes, I know about 'filter', but this returns just the 'true > # elements'... > > # put this in one line? > true_class = [] > false_class = [] > #### if you are thinking "true_class = []; false_class - []" then I'd guess #### most here would recommend against bunching up as pointless #### and just a tad less readable than two separate statements. #### if you are thinking "true_class = false_class = []" #### then it would be a BIG NO-NO. #### the latter form initializes both variables to the SAME (empty) list #### and I'm pretty sure you want 2 separate lists. #### 'Mutable' constant objects like [] and {} work differently from #### 'Immutable' ones like 1, 0.0 and "abc". Not sure the precise Pythonetics #### terminology, but one way to think of it is that mutable types are accessed #### 'by reference' while immutableones are accessed as if they were 'by value'. #### 2 + 3 results in a new number. list.append(...) changes the list in place and #### affects all 'references' to the list. > > for item in seq: > if func(item): > true_class.append(item) > else: > false_class.append(item) > return [true_class, false_class] > > else: > # put this in one line? > quotient_set = [] > representative_class = [] > > for item in seq: > representative = func(item) > > # "Try: seq.index(item)" is IMO rather ugly in a loop. But > # it's even better than "if item in seq: seq.index(item)", > # which goes twice through seq > try: > quotient_set_index = representative_class.index(representative) > except ValueError: > quotient_set.append([item]) > #### teeny tiny nit: I prefer "quotient_set.extend( item )" to the above. > > representative_class.append(representative) > else: > # This somehow "inelegant", because all I want to do is: > # "seq[index] = seq[index].append(item)" Suggestions? > #### Define your set or sequence types to be a class or classes. #### You can then define [] and .append() operations #### to be whatever you want (e.g., silently exclude duplicates, etc.) #### Even the most trivial data abstractions usually benefit by being made an #### explicit class/object. #### if you are 'indexing' you may want to use a dictionary base type instead of a list. #### if you only want to test membership, instead of the 'try' you can test: if representative in representative_class: .... > > equivalence_class = quotient_set[quotient_set_index] > equivalence_class.append(item) > quotient_set[quotient_set_index] = equivalence_class > > return quotient_set >#v- > >To get a feeling for what 'quotient_set' does, try: > >>>>f = lambda x: x % 3 >>>>quotient_set([1, 2, 3, 4, 5, 6, 7, 8, 9], f) >>>> >[[1, 4, 7], [2, 5, 8], [3, 6, 9]] > >>>>quotient_set([1, 2, 3, 4, 5, 6, 7, 8, 9], f, 'bool') >>>> >[[1, 2, 4, 5, 7, 8], [3, 6, 9]] > >#v+ >def set(seq): > """ make a true set by removing duplicates """ > # Shortest way to do a 'null function'? 'None' doesn't work... > f = lambda x: x # identity function > > return [item[0] for item in quotient_set(seq, f)] >#v- > -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptbjrii at hotmail.com Thu Sep 19 09:33:07 2002 From: ptbjrii at hotmail.com (Polerio Babao Jr.II) Date: 19 Sep 2002 06:33:07 -0700 Subject: Nokia 3310 SMS Application, done:connecting to serial port(linux/win), done:reading some hex like \x00 . . ., problem:write/send command! noresponse Message-ID: <52facf1d.0209190533.3048e62c@posting.google.com> Greetings: Python Masters I wanted to create an SMS application using Nokia 3310 with DAU-9P(data cable), I am now able to get some data from the cell phone. I'm using Pyserial and Siomodule. I use pyserial in my linux system. Out of curiosity I've even tested the pyserial on my mouse to prove that I'm really reading data from the external device connected on my com2 or /dev/ttyS1 on linux. From this you would perhaps believe that I've done the first phase of my plan. The Problem: I tried almost three weeks writing or sending a command to the cell-phone but this gives me no response. I'm talking here about the nokia 3310 connected to my serial port. The command that I send is the AT command. From my pyserial I made an initialization like this ser=serial.Serial('/dev/ttyS1',19200) ser.readline() ser.write() ser.read() When I connect to the port for the first time I get the ser.read() output like this \x00\x0c I think. But that's two response is what I get on my first connect. After that when I envoke ser.read() again, I get nothing. Now I've tried sending commands using the Nokia AT Command which was taken from this link here -> http://3ton.com/besik/ATNOKIA.pdf The problem is, this still gives no response, when I type ser.write('ATCGMI') or any other command, I get no response. Please correct me if I'm wrong for using the Nokia At command on 3310, I doubt that this At command applies only to some device of nokia products like 6110 series, 71.. etc. Thus, ser.read() would not give me anything. And that's my problem. I tried installing SMS application that runs on windows http://www.oxygensoftware.com/download/O2SMS_AX.zip because I doubt that my cell phone is not woking on my sockets. But I found that it works fine. I've tested that software, sending and receiving messages and that works very ok. I hope my explanation gives you enough information. I hope you could help me with this because I plan to integrate this application on my online/sms borrowing of books project part of my undergraduate research. I also tried writing to Mr. Frank Stajano, but it's already 2 weeks and still I get no response. Perhaps his busy or doesn't want to talk about this matter. Frank Stajano had already created an application like this for his research and I think he even asks for help in this group. His output an SMS python scripts is also not available. The Thing that I really want to know is what kind of command will I use to get some response from the nokia 3310? Is it also a hex commands in which I will envoke \x00,.. etc commands. Or is it a flat ASCII file also. I hope you could share some idea which regards to this. Any idea regarding this would be of great help to me, I hope you could give me one. Thanks Polerio From sonnenbu at informatik.uni-bonn.de Mon Sep 2 07:37:28 2002 From: sonnenbu at informatik.uni-bonn.de (Frank Sonnenburg) Date: Mon, 2 Sep 2002 13:37:28 +0200 Subject: wie greife ich mit Python auf die c-bibliotheken zu ? References: <3D7323BB.4070200@uni-koblenz.de> Message-ID: You can't access directly C++ classes via python. I have made some efforts to create a python class and instances of it in C, but up to now not really successfully. The more easy and so preferrable way is to define a python class in python and then modify instances of this class in some extension module function, passing this instance as an argument. To write extension modules, see extending and embedding python: http://python.org/doc/current/ext/ext.html Frank "Oleg Seifert" schrieb im Newsbeitrag news:3D7323BB.4070200 at uni-koblenz.de... > hallo Leute, > > k?nnte vielleicht jemand es mir an einem Beispiel zeigen. Ich habe als > Attachments zwei kleine Anwendungen dazu geschickt. > > danke im Vorraus, > > Oleg > ---------------------------------------------------------------------------- ---- > > /* Dies ist ein Programm in C */ > > #include > > class person > { > private: > char* name; > char* geschlecht; > public: > void set_name(char* n) { name = n; } > void set_geschlecht(char* g) { geschlecht = g; } > char* get_name() {return name;} > char* get_geschlecht() {return geschlecht;} > }; > > > void main() > { > /* > person student; > student.set_name("Peter"); > student.set_geschlecht("mannlich"); > printf("Name : "); > printf(student.get_name()); > printf("\nGeschlecht : "); > printf(student.get_geschlecht()); > printf("\n<<< ende\n"); > */ > } ---------------------------------------------------------------------------- ---- > # dies ist ein Python-Programm > > > # hier instanzierung der Klasse person aus punkt.cpp > > print "<<< ende" > From david.abrahams at rcn.com Fri Sep 13 18:48:22 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Fri, 13 Sep 2002 18:48:22 -0400 Subject: Extending a C++ App References: <996eade8.0209120912.3a653d7@posting.google.com> <996eade8.0209122352.45721938@posting.google.com> Message-ID: "Bwuce_Wee" wrote in message news:996eade8.0209122352.45721938 at posting.google.com... > I'm busy investigating Boost.Python... In that case, get Boost.Python v2 using the instructions at http://mail.python.org/pipermail/c++-sig/2002-May/001100.html It's nearing release, and v1 isn't long for this world. -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From duncan-news at grisby.org Fri Sep 6 15:46:46 2002 From: duncan-news at grisby.org (Duncan Grisby) Date: Fri, 06 Sep 2002 19:46:46 GMT Subject: Interapp communication under Python[Linux]? References: Message-ID: In article , Robert Oschler wrote: >My Python app will talk to 3 or 4 modules written in Java and C/C++. >Fortunately I have the source for the Java and C/C++ modules and I have >experience in both languages. Currently the external modules have no >provision for being accessed outside of the process they are running as. So >I'm wondering what the best protocol would be used to "glue it all >together". There a dizzying array of possibilities: [...] >6) CORBA? (yikes!) CORBA has a reputation for being difficult to use, but it's actually really easy, and it could well solve all your problems for you. Adding simple CORBA interfaces to your existing code would add around 50 lines to the C++ and Java code, and about 20 to the Python code, plus maybe another 10 lines of IDL interface definitions. Obviously if you need more complex interfaces there will be more code involved, but minimal support really is minimal. You can see a simple Python CORBA client and server here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81254 Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From oren-py-l at hishome.net Fri Sep 13 17:20:53 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Fri, 13 Sep 2002 17:20:53 -0400 Subject: wrapping yield ? In-Reply-To: References: Message-ID: <20020913212053.GA12991@hishome.net> On Fri, Sep 13, 2002 at 01:01:15PM +0000, Duncan Booth wrote: > Don't forget that iterating with a generator is *much* more efficient than > calling a Python functions thousands of times. > > Python has a big overhead on each function call, but you only pay that > overhead when you first call a generator and the subsequent iterations have > virtually no overhead at all. In most programming environments function calls are fast and context switches are slow. Python is quite unusual in having it the other way around - a yield statement causes a context switch that is much faster than a function call. Oren From ws at mystrobl.de Sun Sep 22 14:27:43 2002 From: ws at mystrobl.de (Wolfgang Strobl) Date: Sun, 22 Sep 2002 20:27:43 +0200 Subject: How to get memory usage on Windows? References: Message-ID: "GerritM" : >Searching in books , documentation (a.o. win32api) and net did not yet help >I found this article on the net: >http://www.developeriq.com/Magazinestories/02jul29memory.php3 >but how to call this function from Python? I guess thanks to Mark Hammond you already have everything you need. Have a look at \Python22\Lib\site-packages\win32\Lib\win32pdhutil.py, uncomment the test function, run it. I snarfed the following snippet straight from win32pdhutil.py: import win32pdh def GetPerformanceAttributes(object, counter, \ instance = None, inum=-1, format = win32pdh.PDH_FMT_LONG, machine=None): path = win32pdh.MakeCounterPath( (machine,object,\ instance, None, inum,counter) ) hq = win32pdh.OpenQuery() try: hc = win32pdh.AddCounter(hq, path) try: win32pdh.CollectQueryData(hq) type, val = win32pdh.GetFormattedCounterValue(hc, format) return val finally: win32pdh.RemoveCounter(hc) finally: win32pdh.CloseQuery(hq) counter=r'\Memory\Committed Bytes' machine, object, instance, parentInstance, index, counterName = \ win32pdh.ParseCounterPath(counter) result = GetPerformanceAttributes(object, counterName, instance, \ index, win32pdh.PDH_FMT_DOUBLE, machine) print result >>> 264937472.0 -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From nessus at mit.edu Fri Sep 6 17:45:27 2002 From: nessus at mit.edu (Douglas Alan) Date: 06 Sep 2002 17:45:27 -0400 Subject: Setting the microphone volume Message-ID: Hi. Does anyone know how to set the microphone volume from Python running on a Windows machine? (Snack doesn't support doing this under Windows.) |>oug From op73418 at mail.telepac.pt Wed Sep 4 10:42:08 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 04 Sep 2002 15:42:08 +0100 Subject: newbie-question: difference between classmethod and staticmethod in Python2.2 References: <3D7619AE.3050605@snafu.de> Message-ID: On Wed, 04 Sep 2002 16:33:18 +0200, "T. Kaufmann" wrote: >Hi there, > >can anybody explain the difference between 'staticmethod' and 'classmethod' in a simple way in >Python2.2? Morally, a static method is just a function as a class attribute, while a class method is a method that is associated with the class, receiving it implicitly as the first argument (as opposed to intance methods that receive the instance as the first argument). class methods are usually used as factory methods (creating and returning instances of the class) as for static methods I have never found much use to them since whatever functionality they provide is best kept at module level. Someone else might have use cases for them. > >When should I use staticmethod or classmethod in classes? > >I thought a staticmethod is a classmethod like in C++/ Java? > >Thanks for help. > >o-o > >Thomas Hope this helps somehow, if it was not sufficiently clear, just holler. Gon?alo Rodrigues From grabiller at 3dvf.net Sat Sep 28 11:55:51 2002 From: grabiller at 3dvf.net (Guy Rabiller) Date: Sat, 28 Sep 2002 17:55:51 +0200 Subject: Keyboard State Message-ID: <3d95d107$1$6669$79c14f64@nan-newsreader-02.noos.net> Hi, sorry if this is a trivial one, but I'm looking for a way to retrieve the keyboard state at anytime. I'm using pyOpenGL and GLUT. GLUT doesnt allow to call the glutGetModifiers() fonction outside the mouse, keyboard and special callbacks, but I need to get the state of the SHIFT and CTRL keys at anytime. Any idea ? Thanks in advance. -- guy rabiller 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net From phil at river-bank.demon.co.uk Tue Sep 17 09:40:28 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Tue, 17 Sep 2002 14:40:28 +0100 Subject: PyQT License In-Reply-To: <27E327AB8201B54495D54105FBBBB1485D205A@SRVMSG.GERLAND2.local> References: <27E327AB8201B54495D54105FBBBB1485D205A@SRVMSG.GERLAND2.local> Message-ID: <200209171440.28885.phil@river-bank.demon.co.uk> On Tuesday 17 September 2002 1:56 pm, Maric MICHAUD wrote: > I did not really understand terms of Qt and PyQt license. > Is it GPL for both Win32/UNIX platforms ? No. There is a commercial version for Win32 and UNIX that allows you to develop and ship closed source applications. There is a GPL version for UNIX. Phil From rolf.kalbermatter at citeng.com Mon Sep 2 04:51:18 2002 From: rolf.kalbermatter at citeng.com (Rolf Kalbermatter) Date: Mon, 2 Sep 2002 10:51:18 +0200 Subject: version independant object usage counting Message-ID: Hello there, I'm fairly new in Python and have attempted to do embedding of the Python core in another application on Windows NT and succeeded so far. In doing this work I found out that Python clients (applications, modules and such) are always linked with a version specific import library which even makes a difference for debug and non-debug. In using and programming DLLs until now I was always used to attempt to remove version dependances as much as possible and so thought about implementing my own Python DLL loader to achive full weak linking to Python and possibly allow a configuration setting to specify where and which Python core DLL to use. However although this loader works quite fine now, I found out that I gained little with it because the current Python architecture is not really designed to link dynamically to it. Of course more complicated tools may be very difficult or impossible to keep version independant but in my case I just call some standard functions from the Python core DLL. The problem arises in fact with the refcounting of Python objects. The macros Py_INCREF and Py_DECREF access directly structure members in the object layout and this layout is different for debugging and non debugging versions and potentially different between Python versions as well. By adding two new API functions PyObject_AddRef() and PyObject_Release() or whatever name seems appropriate and exporting them, it would be possible to write clients which import the necessary Python API functions dynamically on there own and link to a specific Python DLL/shared library much more independant from the used Python core DLL than it is the case now. Is there a specific reason that these two API functions are not available and one is forced to use the according macros to do proper refcounting, or did I miss those functions completely? I do understand that inline code is a little faster than calling a function and I do not propose to remove the current macros at all, but rather would like to see two additional functions added which allow to do proper refcount manipulation over a functional interface instead of direct object structure layout access. Any thought about this? Rolf Kalbermatter CIT Engineering Nederland BV tel: +31 (070) 415 9190 Treubstraat 7H fax: +31 (070) 415 9191 2288 EG Rijswijk http://www.citengineering.com Netherlands mailto:rolf.kalbermatter at citeng.com From mjackson at alumni.caltech.edu Thu Sep 26 15:27:16 2002 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 26 Sep 2002 19:27:16 GMT Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> <3D934C5C.4000603@mxm.dk> <20020926.130938.1789366143.1524@cybermesa.com> Message-ID: "Jay O'Connor" writes: > In article <3D934C5C.4000603 at mxm.dk>, "Max M" wrote: > > > Pat Notz wrote: > >> @ = "at" > >> ! = "bang" > >> . = "dot" > >> * = "star" > >> > >> Is there a short (one or two syllable) pronounciation for "__" (double > >> underscore). "Underscore underscore" and "double underscore" are kind > >> of long. Somthing like "splat"? Anyone? > > > > _ = 'under' > > > > __ = 'under-under' > > > How about "underder"?? How about "dunder" (double under)? -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson Yes, but what if it were a parrot? - Graham Chapman, to John Cleese From lpgray at uop.com Wed Sep 18 15:24:48 2002 From: lpgray at uop.com (Lee Gray) Date: 18 Sep 2002 12:24:48 -0700 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <3D886F3D.9AE251F9@unice.fr> Message-ID: <96904b50.0209181124.7eb93f4b@posting.google.com> Jerome Alet wrote in message news:<3D886F3D.9AE251F9 at unice.fr>... > Perhaps this is really silly, but why don't you show Zope to your boss ? > > http://www.zope.org/ > > not really a GUI, though > > hth > > Jerome Alet I've heard of, but know nothing about Zope. I don't think it's really applicable. I need a client GUI app to have him get the feel of what's possible; and the back-end (Oracle DB) isn't going to change. Thanks though, Lee From fb at frank-buss.de Tue Sep 17 04:53:17 2002 From: fb at frank-buss.de (Frank Buss) Date: Tue, 17 Sep 2002 08:53:17 +0000 (UTC) Subject: question about dictionary type.. References: <61Jg9.16334$5r1.665293@bin5.nnrp.aus1.giganews.com> Message-ID: eugene kim wrote: > i read a python book while ago, and trying to refamiliaze myself with it > recently, your solution looks so cool.. Thanks, I'm not a Python expert, because I wrote my first line of Python code one month ago (but I already knew some other languages), so there are probably a better solution for your problem using Python. But for me it was a good idea to help in this newsgroup for learning a bit more of Python :-) > have to spend some time what u did =) The add-funtion is obvious. So looking at the main program: records = re.compile('\((.*?)\)', re.DOTALL).findall(stdin.read()) for record in records: fields = map(lambda w: upper(w), re.findall("'(.*)'", record)) add(tree, (fields[0],fields[2],fields[3]),0) add(tree, (fields[1],fields[2],fields[3]),0) "stdin.read()" reads all from stdin. ".*" matches any chars (zero or more occurence). It is written within a group (the '(' and ')'), so findall can use the matching result. Because your records are surrounded by '(' and ')' I wrote '\(' and '\)'. The "?" is needed to avoid greedy matching. Without "?" only one record would be matched, starting from the first "(" until the last ")" in the whole file. "re.DOTALL" says, that "." should match newslines, too. Next interesting expression is the map-line. "'(.*)'" matches anything between two '. It doesn't need to be non-greedy ("?"), because the line boundarys are not matched (no re.DOTALL). The result is a list of all fields. "map" iterates through all elements of the resulting list, applys the function "upper" through the lambda-inline-function to each element and returns a new list with the upper-cased elements. -- Frank Bu?, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From rpm at wag.caltech.edu Wed Sep 4 13:38:01 2002 From: rpm at wag.caltech.edu (Rick Muller) Date: Wed, 04 Sep 2002 10:38:01 -0700 Subject: Can't exponentiate zero in NumPy Message-ID: I'm hoping someone can help me track down a potential bug that one of my users is reporting. This user claims that exponentiating zero in Numeric raises an exception. It isn't clear to me whether the violating code is a single value or an array of zeros. That is from Numeric import * a = zeros(3,Float) b = 0 print a**(4./3.) print b**(4./3.) I have not been able to get back in contact with this user to double check how and when this fails, and everything works on all of the machines I have at my disposal here. Has anyone seen this before? Can anyone verify that it fails? Can anyone suggest an elegant workaround for the array case? Thanks in advance, Rick From 2002 at weholt.org Mon Sep 16 18:14:44 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Mon, 16 Sep 2002 22:14:44 GMT Subject: Best way ( easiest ) to generate RSS/RDF on MySQL-data ?? Message-ID: I got data in a MySQL-database I want to base my RSS/RDF-feeds on. The columns in the given tables doesn't have fields that correspond to RSS or RDF tags so I need to do some "mapping" of table columns into RSS/RDF-tags. Is there a module or piece of code out there that shows a dynamic and customizable way of mapping these kinds of data to RDF/RSS or even another XML-based kind of document ? I've read lots about parsing RSS/RDF but found very few resources on generating those files, -- in any programming language. It's not that the format is hard to code doing it the fast and dirty way, but that seem a bit restricted and by using RDF I want to be able to let users define custom namespaces etc. too. That's way I need a pretty dynamic method of generating these feeds. Any hints or clues on how to generate RSS/RDF-files, not even related to this problem in particular would be highly appreciated. Best regards, Thomas Weholt From emile at fenx.com Sun Sep 22 10:42:29 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 22 Sep 2002 07:42:29 -0700 Subject: COM, Word problem References: Message-ID: strat_addict: > com_error: (-2147417846, 'The message filter indicated that the > application is busy.', None, None) Google is your friend... perhaps this helps: http://groups.google.com/groups?selm=MPG.13553ec91f8cb3b98968e%40192.168 .0.28 -- Emile van Sebille emile at fenx.com --------- From DennisR at dair.com Tue Sep 17 10:59:32 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Tue, 17 Sep 2002 14:59:32 GMT Subject: using python as cgi on apache unix References: Message-ID: > ... want to move this to my unix server. Unfortunately, no matter what I > do I can not get apache on my linux box to execute any python scripts. I > get the following errors in apache: > Premature end of script headers: /var/www/html/cgi-bin/test.py What do you get when you type "test.py" at the shell prompt when logged into the cgi directory on the RH box at the command line? Do you get: --- --- Content-Type: text/html --- hello where "---" is taken as a blank line? I agree with Gerhard that the initial print "\n\n" is wrong. But your comment trying the cgi.test suggests that something else is going on. The above test may sniff out that something else. Dennis Reinhardt http://www.dair.com From martin at v.loewis.de Mon Sep 16 12:42:08 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Sep 2002 18:42:08 +0200 Subject: Py_CompileString and line numbers? References: Message-ID: Sebastian Andersson writes: > I'm parsing a config file and from there I get embedded python code > which I send to Py_CompileString, with the config file's filename given > as filename argument to Py_CompileString. Later, when errors are found > in the python code, the wrong line numbers are reported. Is there > a way to tell Py_CompileString an offset for the first line that > I give to it? No. You'll have to instantiate a tokenizer yourself, and set its lineno member. HTH, Martin From news.but.NO.SPAM at datatailors.com Mon Sep 23 07:39:48 2002 From: news.but.NO.SPAM at datatailors.com (Peter van Kampen) Date: Mon, 23 Sep 2002 13:39:48 +0200 Subject: Cookbook example, DAO error Message-ID: Hi, I am trying to run the jet2sql script from the Python cookbook but it fails. I use win2K with activepython (latest version). I have tried it on two computers both with the samen result. I have narrowed it down to a failure to enumerate the Indexes collection. Here's the (relevant part of) the traceback msg (in pythonwin): File "I:\d\Python\jet2sql.py", line 128, in getPrimaryKey for idx in currTabl.Indexes: File "c:\python22\lib\site-packages\win32com\gen_py\ 00025E01-0000-0000-C000-000000000046x0x4x0.py" , line 956, in __getitem__ return self._enum_.__getitem__(index) File "C:\Python22\Lib\site-packages\win32com\client\util.py", line 37, in __getitem__ return self.__GetIndex(index) File "C:\Python22\Lib\site-packages\win32com\client\util.py", line 53, in __GetIndex result = self._oleobj_.Next(1) com_error: (-2146825178, 'OLE error 0x800a0c26', None, None) If I run from the commandline I get [same output] pywintypes.com_error: (-2146825178, 'OLE error 0x800a0c26', None, None) Has anyone else seem this problem, or does anyone have any idea how solve it? TIA, PterK From DeepBleu at DeepBleu.org Thu Sep 5 21:11:59 2002 From: DeepBleu at DeepBleu.org (DeepBleu) Date: Fri, 06 Sep 2002 01:11:59 GMT Subject: upgrading python References: <3D777EA9.F9A96C83@ipm.fhg.de> Message-ID: The problem is how do you get such an installer to work? Also, how would the installer know of the different packages? There are literally hundreds of packages. How about the mxODBC package? Scientifc? Real? Having said that - I for one have always run into such issues (please note that I am using the word issues, not problems). I just keep track of what packages I am using and only upgrade when the need arises. It is much better to keep the Python 'generic' distribution separate from anything else. Then download an duse the packages that you need. DeepBleu "Markus von Ehr" wrote in message news:3D777EA9.F9A96C83 at ipm.fhg.de... > Hi, > > first of all I'd like programming in python. > Sometimes you need to grade up to a newer version. > I have to download everything again and install every single package, > for example: > > -win32all > -PyOpengl > -Pyserial > -Numeric > -unzip Pmw > -PIL > -py2exe > -PyXML > etc. > > So I just mentioned "only" 8 packages, additionally I have to > install the newer python version and to uninstall the old packages... > > Couldn't it be made easier? Maybe I do something wrong and > am misunderstanding how to deal with it. > > Now I wanted to grade up to tk84. It was quite hard to find > _tkinter.c, then I downloaded the tcl-sources, tk-sources, > installed MSVC6, found out that some X11 stuff is missing... > > I know that all mentioned packages are different projects but could > it be made that there's a python distribution with all packages > up2date and the installer is asking for the desired ones? > > Do you have similar experiences? > > Markus From frogger974 at yahoo.com Thu Sep 5 22:15:04 2002 From: frogger974 at yahoo.com (Matt Rickard) Date: Thu, 05 Sep 2002 22:15:04 -0400 Subject: pygtk-2 tutorial/doc? Message-ID: I'm trying to do some gtk-2 development with python, but I really can't find a good place to begin. All the tutorials I've found (python.org) are based off of old versions of python (1.x) and old versions of gtk (1.x). I'd like to find some kind of tutorial or at least some introductory documentation on programming with pygtk-2 with python 2.2. Anyone have any ideas on where I should be looking? Thanks. From igetenoughspamalreadythanksjlr at doctor.com Sun Sep 1 18:21:32 2002 From: igetenoughspamalreadythanksjlr at doctor.com (John La Rooy) Date: Mon, 02 Sep 2002 08:21:32 +1000 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: <1030962064.628232@ampungk.ozonline.com.au> Carl Banks wrote: > Gerhard H?ring wrote: > >>>which means the real time is not spent in the compile() function, but >>>in the match or find function. So basically, couldn't one come up with >>>a *human readable* syntax for re, and compile that instead? >> >>That's equally powerful? Most probably not. > > > Why not? It won't be as fast, but it should be able to do anything a > regexp can do, and would be much more versatile. > > I think the main problem is that *human readable* doesn't map really well onto regular expressions. What would the equivalent of r"(.)(.)(.)\3\2\1" This means a "palindrome of 6 characters" But it is unlikely that the human readable processor would understand that (isn't it??) It would be more likely to look like this (I haven't put too much thought into this) "anything,anything,anything,same_as_3rd,same_as_2nd,same_as_1st" or would you like to suggest something else? palindrome_6 = re.compile(r"(.)(.)(.)\3\2\1") palindrome_6 = re.compile("anything,anything,anything,same_as_3rd,same_as_2nd,same_as_1st") Sure there are some cases where the re is loaded with meta characters... hmmm OK is this about writing maintainable code or people not wanting to learn all the ins and outs of re's? John From Oschler at earthlink.net Sat Sep 14 23:24:00 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sun, 15 Sep 2002 03:24:00 GMT Subject: Will xml.dom work with HTML docs? Message-ID: Will the xml document parser module work with plain old HTML docs, if not is there a good parser module for HTML docs? thx From fredrik at pythonware.com Fri Sep 6 02:29:59 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Sep 2002 06:29:59 GMT Subject: about parse a link References: Message-ID: "koko" wrote: > if I have extracted the links on the page: > e.g: > > http://www.uic.edu/index.htm > on this page: there are > a.htm > b.htm > c.htm > http://www.uic.edu/home/e.htm > > how can I log the a.htm, b.htm, c.htm with the full web address? base = "http://www.uic.edu/index.htm" url_list = [ "a.htm", "b.htm", "c.htm", "http://www.uic.edu/home/e.htm" ] import urlparse for url in url_list: print urlparse.urljoin(base, url) prints http://www.uic.edu/a.htm http://www.uic.edu/b.htm http://www.uic.edu/c.htm http://www.uic.edu/home/e.htm From jb at cascade-sys.com Sun Sep 15 03:31:48 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Sun, 15 Sep 2002 00:31:48 -0700 Subject: How to represent sets References: Message-ID: <3D843764.8030208@cascade-sys.com> Anton Vredegoor wrote: >I would like to reopen this discussion. > I think BOTH approaches deserve to be in the library. For dense sets isomorphic with integers, the long integer implementation probably will be superior. For other, more general applications the dictionary approach may be better. Which is "better" is not a blanket decision we can make in advance. Include them both and let the user decide. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From anton at vredegoor.doge.nl Fri Sep 27 10:12:05 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 27 Sep 2002 16:12:05 +0200 Subject: watching mutables? Message-ID: Hello all, here's a function I would like to have: >>> m = [1,2] >>> m >>> [1,2] >>> from watcher import watch >>> watch(m) >>> m.append(3) >>> "hey, you changed variable m!, new value is [1,2,3]" Is this possible? How would this be called? Anton. From steve at ferg.org Fri Sep 13 08:58:00 2002 From: steve at ferg.org (Stephen Ferg) Date: 13 Sep 2002 05:58:00 -0700 Subject: Newbie Looking for direction References: Message-ID: Some thoughts... Python is a great general-purpose language. If your aim is to develop just database-type applications, using a DBMS that everyone else at your workplace has, then you are probably better sticking with one of your database packages. On the other hand, if you really want to get a taste of a real general-purpose programming language, one that is not tied to a DBMS, then Python is an excellent choice. In my experience, most of the things I do have nothing to do with databases. I write a lot of little utilities, one-time quick and dirty programs, etc. All the stuff that you'd like to be able to automate easily. And for that, you need a programming (or scripting) language like Python, just the way you (once) needed batch files or shell scripts or JCL or whatever. It is something every computer-user needs. So I would recommend that you continue to learn and use Python. But at the outset, you might want to avoid trying to do database programming with it. Play with the language a while, write some little utilities in it, get a feel for the language. Once you've done that, you can decide whether you want to go on and do database programming with it. But of course, by that time, you'll also find that Python has become an invaluable tool in your toolbox, whether or not you decide to do database programming with it. And you'll have found that your concept of what you can do with a programming language has become much broader than it was when you were programming only with languages tied to a DBMS. From bbrelin at yahoo.com Tue Sep 3 16:31:10 2002 From: bbrelin at yahoo.com (Braun Brelin) Date: 3 Sep 2002 13:31:10 -0700 Subject: What's this error mean??? Message-ID: Hello, I'm running Zope-2.5.1 on a RedHat Linux 7.3 machine. I'm trying to install the ParsedXML Product and I'm getting the following error: 2002-09-03T18:49:49 ERROR(200) Zope Couldn't install ParsedXML Traceback (innermost last): File /usr/local/Zope-2.5.1-linux2-x86/lib/python/OFS/Application.py, line 637, in install_product (Object: Zope) (Info: ParsedXML) File /usr/local/zope/lib/python/Products/ParsedXML/__init__.py, line 92, in initialize AttributeError: 'Products.ParsedXML.ParsedXML' module has no attribute 'ParsedXML' I installed the PyXML product via RPM. Can anyone tell me what the error means and how to fix this? Thanks, Braun Brelin bbrelin at yahoo.com From kwdotbenninkNOSPAM at 12move.nl Fri Sep 20 09:27:56 2002 From: kwdotbenninkNOSPAM at 12move.nl (Highwaykind) Date: Fri, 20 Sep 2002 15:27:56 +0200 Subject: Newbia alert .. working my way through Easy Python Montana Edu page, need help.. Message-ID: I'm asked ( on the website : www.honors.montana.edu\_jjc\easytut \node10.html ) to write a small programm to calculate rectangle, square and circle thingies( forgot the English word .. ) and I came up with this code : def print_options() : print "options:" print " 'p' print options" print " 'r' Calculate area rectangle" print " 's' Calculate area square " print " 'c' Calculate area circle " print " 'q' Quit" def rect (width,height): return width*height def square ( width1, height1): return width1*height1 def circle (3.14*radius**2): return 3.14*radius **2 choice = 'p' while choice != 'q': if choice == 'r': a=input ("width") b=input ("height") print "result",rect (width,height) if choice =='s': c = input ( "width") d = input ( "height") print "result",square (width1, height1) if choice == 'c ': f=input ("radius") print "result",circle if choice != 'q': options() choice=raw_input ("option") But the thing keeps telling me width is not defined, also I can;t use the ELIF command .. THink I could do with some help :) Corien -- For the correct e-mail address : remove NOSPAM and replace dot with . From op73418 at mail.telepac.pt Wed Sep 4 10:29:28 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 04 Sep 2002 15:29:28 +0100 Subject: Why read-only nested scopes? Message-ID: Hi Why is it that we cannot rebind names in outer scopes from within the inner scope? This is perplexing to me, because you can rebind global scope variables using the global directive, e.g. x = whatever def somefunction(some_args): global x x = another_whatever So why hasn't this been extended when nested scopes were introduced, e.g. by reusing the global directive or some other one? Implementation issues? Or is this line of development is frowned upon by the language designers, e.g. the BDFL? I am well aware that this opens up a can of worms but the global directive does that already, so... Thanx in advance for any enlightening comments, Gon?alo Rodrigues From thoa0025 at mail.usyd.edu.au Tue Sep 17 00:01:16 2002 From: thoa0025 at mail.usyd.edu.au (:B nerdy) Date: Tue, 17 Sep 2002 04:01:16 GMT Subject: raw post data References: Message-ID: how could i make it so when i read the stdin it still is there.. cause i use cgi.FormVariables() also cheers "Alex Martelli" wrote in message news:w_fh9.113093$pX1.4054147 at news2.tin.it... > :B nerdy wrote: > > > how would i retrieve the raw post data in cgi python scripts ? > > I think something like: > > import sys > all_posted_lines = sys.stdin.readlines() > > should do it. Raw POST'ed data should be no more and no less > than the contents of the CGI script's standard-input. > > > Alex > From loewis at informatik.hu-berlin.de Tue Sep 17 03:54:24 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 17 Sep 2002 09:54:24 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: Ian Bicking writes: > Was there some indication that Stackless would be integrated if the code > was cleaned up, documented, or otherwise simplified? I don't believe > there was, but I may be wrong. I certainly meant it that way in http://groups.google.de/groups?q=g:thl2323460570d&dq=&hl=de&lr=&ie=UTF-8&oe=UTF-8&selm=j4d72xasx0.fsf%40informatik.hu-berlin.de > Without such an indication, there is no reason to think that mere > technical changes to Stackless will lead to it being included in > standard Python. This is not how free software works. Most contributors don't ask for an advance blanket incorporation guarantee, and nobody would ever give one, for any kind of change. Instead, they just contribute the code they find useful, and then are perhaps told to modify it. If they want to make sure that the feature itself is undebated, they need to write a PEP. There are many features in Python that most maintainers won't care about (for example, I have no interest in IMAP). That hasn't stopped people to contribute those features, and hasn't stopped maintainers to incorporate them. Contributing needs patience, a skill that contributors sometimes lack. To give a few examples: - the IPv6 patches took about 15 months to integrate. For many months, the patches were unreviewed, because nobody thought to have the expertise to review them. I eventually tought myself the necessary background to review the patch, after which about 4 further iterations where necessary before the patch was installed, and about 10 changes after the patch was installed. - To build Python as a shared library on Unix, about 4 patches have been contributed over several years. Each contributor was told what the requirements for such a patch were (must be a compile-time option, must work uniformly on many systems, etc), most contributors abandoned their patch after learning these requirements. Only the most recent such patch could be incorporated, after a few iterations. Both patches were relatively small, compared to the old Stackless implementation. Since integrating Stackless will require a significant amount of time on the side of the Stackless authors, some contributor must step forward and be willing to guide the entire integration period, preferably for two Python releases after the patch has been incorporated. I don't think anybody was willing to contribute that much time in the past. Regards, Martin From bob at eleaston.com Sat Sep 7 06:32:24 2002 From: bob at eleaston.com (Bob Easton) Date: Sat, 7 Sep 2002 06:32:24 -0400 Subject: Interrupting Python References: <3d796d22@news.sentex.net> Message-ID: Yes Peter, it makes sense that PythonWin works that way by design. You are also right about running from the command prompt after development/debug is done. For this particular program, using a file semaphore is ideal since I can place it at the right point in the program to enable easy restart, something not easily done with the random ctrl-break. Thanks to all who helped clear the fog for me. -- Bob Easton "Peter Hansen" wrote in message news:3d796d22 at news.sentex.net... > Bob Easton wrote: > > Using catchCtlC.py in a command line environment works as you expect. When I > > hit Ctrl-Break, Windows displays "^C" and then a command prompt. If I hit > > Ctrl-C, the exception handler catches it and displays the results as > > specified in catchCtlC/py > > > > However, my preferred execution environment is PythonWin, not a command > > prompt. There, neither Ctrl-break, not Ctrl-C have any effect. That could > > easily be a bug with PythonWin. > > Not a bug, I think. The whole Ctrl-C/Ctrl-Break concept is only > meaningful for command-line ("console") programs, not GUI apps. > I don't use PythonWin, but my guess is it does not bother passing > ctrl-c on to the application, possibly by design. > > Can't you just run it under the console? What advantages do > you find by running it under PythonWin other than during > development? > > Also, have you looked at the msvcrt module and kbhit() ? > > -Peter > From pan-newsreader at thomas-guettler.de Sat Sep 14 06:23:44 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Sat, 14 Sep 2002 12:23:44 +0200 Subject: Skipping Parts of a For Loop Message-ID: Hi! Is there a way to skip some parts in a for loop? for i in range(3): print "i before", i i=2 print "i after", i #Results in: i before 0 i after 2 i before 1 i after 2 i before 2 i after 2 Is there a way to skip some parts? "continue" skipps one element. But how can I skip several? thomas From rolf.kalbermatter at citeng.com Mon Sep 9 04:32:43 2002 From: rolf.kalbermatter at citeng.com (Rolf Kalbermatter) Date: Mon, 9 Sep 2002 10:32:43 +0200 Subject: Embedding - Local dictionaries for local scripts In-Reply-To: Message-ID: Maybe your problem is more basic about the actual context to create, to use such Python functions just as I had in the beginning. Then something like this might work for you. I have split the actual compile and execute step because my original project has some more possibilities than this. But that should make no difference. Also you should think about proper PyThreadState implementation and protection if your host application is multithreading and could possibly call the Python core from different threads. This has been left out here for simplicity. typedef struct tagSESS { int32 magic; PySession next; char *text; PyObject *co; PyObject *dl; PyThreadState *tstate; } PySessionRec; int PySetScript(PySession session, char *lpScriptText) { if (session) { int32 len = strlen(lpScriptText); if (session->text) free(session->text); session->text = (char*)malloc(len + 1); MoveBlock(lpScriptText, session->text, len); if (session->co) { Py_DECREF(session->co); session->co = NULL; } return TRUE; } return FALSE; } int PySetData(PySession session, char *name, void* data, int16* typedescriptor) { if (session) { if (!session->dl) { /* If no local variable dictionary create new one */ session->dl = PyDict_New(); } if (session->dl) { /* Convert our data into a Python object */ PyObject *value = PyCreateData(data, typedescriptor); if (value) { /* Add the input variable to the local variable dictionary */ PyDict_SetItemString(session->dl, name, value); Py_DECREF(value); /* Return success/failure */ success = PyErr_Occurred() ? FALSE : TRUE; } } } return FALSE; } int PyExecuteScript(PySession session, int *eStart, int *eEnd, char *eText) { if (session) { if (!session->co) { /* Compile the script */ session->co = Py_CompileStringFlags(session->text, "", Py_file_input, 0); } if (session->co) { PyObject *v, *m, *dg; /* Extract the global dictionary object */ if (!(m = PyImport_AddModule("__main__"))) goto errOut; if (!(dg = PyModule_GetDict(m))) { goto errOut; } Py_INCREF(dg); if (PyDict_GetItemString(dg, "__builtins__") == NULL) { if (PyDict_SetItemString(dg, "__builtins__", PyEval_GetBuiltins()) != 0) { Py_DECREF(dg); goto errOut; } } /* Execute the script, passing in our arguments as local variables */ if (v = PyEval_EvalCode((PyCodeObject *)session->co, dg, session->dl)) { Py_DECREF(v); } Py_DECREF(dg); } /* Extract eventual error information if any */ return PyErrorInfo(eStart, eEnd, eText); } errOut: return FALSE; } int PyGetData(PySession session, char *name, void* data, int16* typedescriptor) { if (session) { if (session->dl) { PyObject *value; /* Retrieve variable value */ if (value = PyDict_GetItemString(session->dl, name)) { /* Value is borrowed reference from dict */ return PyConvertData(value, data, typedescriptor); } } } return FALSE; } > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Martin v. Lowis > Sent: Monday, September 09, 2002 9:51 AM > To: python-list at python.org > Subject: Re: Embedding - Local dictionaries for local scripts > > > chris.walsh at real-sense.com (Chris Walsh) writes: > > > PyObject* PyRun_String( > > char *str, > > int start, > > PyObject *globals, > > PyObject *locals); > > > > I have seen some stuff in comp.lang.python about creating a dict and > > adding the __builtin__ module but I have been searching now for an > > hour and cannot find it. > > > > Can anyone point me to some code which creates this dictionary? > > The globals/locals dictionary is not really different from any other > dictionary; you create them with PyDict_New. Python should > transparently add an __builtins__ into the globals dictionary if there > is none, but you can copy the __builtins__ entry just as well yourself > (via PyDict_SetItemString). > > HTH, > Martin > > -- > http://mail.python.org/mailman/listinfo/python-list From oren-py-l at hishome.net Wed Sep 18 02:08:23 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 18 Sep 2002 02:08:23 -0400 Subject: Stackless Python, eventual merge? In-Reply-To: References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> Message-ID: <20020918060823.GB81158@hishome.net> On Wed, Sep 18, 2002 at 06:44:16AM +0200, Martin v. Loewis wrote: > Greg Ewing writes: > > > Also, I believe that, even on the supported > > architectures, it plays dangerous tricks with > > the C stack. I'd prefer to see that fixed > > before making it a standard part of the > > distribution. > > They aren't really dangerous, just unconventional. And that cannot be > fixed, as it is essential to operation of Stackless. They may be dangerous in some circumstances. IIRC, if a C extension calls the Python interpreter recursively with pointers to things on its stack it can cause memory corruption. Oren From duncan at NOSPAMrcp.co.uk Tue Sep 24 05:58:14 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 24 Sep 2002 09:58:14 +0000 (UTC) Subject: instance creation References: <265e380f.0209240052.4c2988f3@posting.google.com> Message-ID: paulmg at digitalbrain.com (Paul MG) wrote in news:265e380f.0209240052.4c2988f3 at posting.google.com: > - Having two constructors seems to be illegal - or at least the second > overwrites the first. > - Assigning to 'self' in the load method seems to really not work! > - Putting the create() method outside of the class works fine - but I > want it to be a class method on Appointment, goddammit!:) Is there no > way to do this? > > Any help would be appreciated, basically i am looking for the python > idiom to do this, as my C++ and Smalltalk idiom's clearly aren't in > the grain of the language! > First off, you want to use a single function and check what arguments were passed. For example: def __init__(self, name=None, details=None, id=None): if id is not None: assert name==details==None i = open("appointment"+str(id)) tmp = pickle.load(i) self.name, self.details = tmp.name, tmp.details else: self.name = name self.details = details Then you can call the constructor using keyword arguments as appropriate: x = Appointment(id='49') y = Appointment('Me', 'Something') y = Appointment(name='Me', details='Something') # Same as above You could avoid using keyword arguments and just count the number of arguments passed in if you preferred. If you want to get rid of the extra object and copying of name and details you could just pickle the individual fields instead of pickling the whole object, or you could use the __new__ method. __init__ is called when the object already exists to complete its initialisation. __new__ is called before the object is created and allows you to modify the actual creation of the object. You have to subclass a type such as object for __new__ to work: class Appointment(object): def __new__(cls, name=None, details=None, id=None): if id is not None: assert name==details==None i = open("appointment"+str(id)) return pickle.load(i) else: self = object.__new__(cls) self.name = name self.details = details return self -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From duncan at NOSPAMrcp.co.uk Wed Sep 11 04:32:54 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Wed, 11 Sep 2002 08:32:54 +0000 (UTC) Subject: dynamism References: <66715c02.0209091923.265fe77e@posting.google.com> <3d7e209a_1@news.iprimus.com.au> Message-ID: Duncan Booth wrote in news:Xns92865CE1C916Aduncanrcpcouk at 127.0.0.1: > The code below gives these timings on my machine: > 3.84s: 1000000 x New() > 3.89s: 1000000 x New2() > 2.39s: 1000000 x Old() > 5.19s: 10000 x attributes() > 5.81s: 10000 x attributes() > 4.17s: 10000 x attributes(__main__.Old) Sorry about the bad form of following up to my own post, but I thought I had better add that the above timings are on Python 2.2.1 and I forgot to specify -O. The optimised times for 2.2.1 are: 3.77s: 1000000 x New() 3.81s: 1000000 x New2() 2.33s: 1000000 x Old() 4.94s: 10000 x attributes() 5.56s: 10000 x attributes() 3.92s: 10000 x attributes(__main__.Old) Using the latest CVS build I get rather different timings: 0.94s: 1000000 x New() 1.05s: 1000000 x New2() 1.39s: 1000000 x Old() 3.52s: 10000 x attributes() 4.36s: 10000 x attributes() 3.05s: 10000 x attributes(__main__.Old) So it appears that creating object-derived classes is now faster than creating old-style classes, although both tests are much faster than in 2.2. Setting attributes is still somewhat slower. Oh, and the -O flag on the CVS build has no measurable effect. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From b.maryniuk at forbis.lt Mon Sep 2 05:07:25 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 2 Sep 2002 11:07:25 +0200 Subject: Why it is so dramatical? Message-ID: <200209021107.25761.b.maryniuk@forbis.lt> The task: Adding a text to a text. The problem: It is tragically slow to add string to huge string. The source: -----------------8<--------------------------- import time _body = '' _data = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' START_TIME = time.time() for a in xrange(0, 0xfff): _body += _data print "'+=' operator:", time.time() - START_TIME, "sek." _body = [] START_TIME = time.time() for a in xrange(0, 0xfff): _body.append(_data) print "append() method:", time.time() - START_TIME, "sek." -----------------8<--------------------------- The usage result: -----------------8<--------------------------- *bo at oberon:(~/work/spike/benchmarks) python str_vs_list.py '+=' operator: 6.96335601807 sek. append() method: 0.0111969709396 sek. -----------------8<--------------------------- The question: Why? The other question: Is it true, that I should through all the Python life use lists and then join it into single text instead to use += operator? -- Regards, Bogdan It is a mess, pure and simple. Sucks to be away from Unix, huh? -- man perlfaq3 From paul at boddie.net Thu Sep 19 04:14:07 2002 From: paul at boddie.net (Paul Boddie) Date: 19 Sep 2002 01:14:07 -0700 Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> Message-ID: <23891c90.0209190014.26c5bb9@posting.google.com> Alex Martelli wrote in message news:... > > > > http://starship.python.net/crew/aahz/FixedPoint.py [...] > To play devil's advocate: DB-API compliant modules have long used > mxDateTime happily, for date-time values, even though mxDateTime > was not (and likely will never be) in the core. Although there's that date/time PEP that will give some kind of standard interface, thus reducing the significance of that particular decision. > Why is FixedPoint (or > Decimal or some future Currency -- whatever) different from mxDateTime > in this regard? How come DB-API compliant modules seem not to > even have felt any need to fish around for a type with which to > represent NUMERIC and DECIMAL, as they did for dates and times? It could well be that not many people do financial database programming in Python, bizarre and unlikely as that may seem. Taking a look at pyPgSQL, as the only database module I have installed that actually readily documents such things (and that should tell you something), it would seem that monetary amounts are converted to floating point numbers - surely the first thing one would want to avoid in manipulating financial data. Perhaps people use integers, or perhaps other modules provide better decimal support. > I don't know the answers, but if "help out the DB-API" is among the > arguments you plan to muster to convince the BDFL, you might > want to be prepared in case these questions get raised. No, sorry, > I won't volunteer as a paladin for this PEP -- I'll gladly help out with > code and even drafting the PEP if need be, but this isn't really my > own crusade... In that case, what do you think of this module? ;-) http://www.boddie.org.uk/python/downloads/ScaledDecimal.py I'll gladly release this into the public domain, but some commentary would be nice - I fear that I may not have implemented it as well as the "numeric gods" might like. Paul From notvalid at hotmail.com Wed Sep 25 22:08:58 2002 From: notvalid at hotmail.com (jano) Date: Wed, 25 Sep 2002 19:08:58 -0700 Subject: cgi post problem References: <9aWj9.39314$V7.10439005@twister.socal.rr.com> Message-ID: "Jeff Davis" wrote in message news:Q14k9.62350$U7.21809935 at twister.socal.rr.com... > > > These two files worked for me (see below). Let me know if you have any more > problems. > > Regards, > Jeff > > -------------py2.cgi-------------------------- > #!/usr/bin/python2.2 > import cgi > > def main(): > try: > form = cgi.FieldStorage() > input = form.keys() > > print "Content-type: text/html" > print > print(""" > 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'> > > > test > > """) > print "

",input,"

" > print "" > except: > pass > > if __name__ == "__main__": > main() > > ---------------py2.html------------------------------------------ > > > > > > > > > > > > > > > > > > jano wrote: > > > There was an error in my prior post. See ^^^^ > > > > > > "jano" wrote in message > > news:amq8av$2cum$1 at agate.berkeley.edu... > >> > >> > >> "Jeff Davis" wrote in message > >> news:9aWj9.39314$V7.10439005 at twister.socal.rr.com... > >> > Hi, > >> > > >> > It looks as though you have a lot of code. It might be helpful to try > >> > to narrow the problem further by removing a lot of the code unrelated > >> > to > > your > >> > problem, which appears to be that "keys" does not contain any items. > > After > >> > you work that out, then put the other code back in. > >> > > >> > My first impression is that you have some "weird" form element names > >> > because they contain the "/" character. That might be perfectly legal, > > but > >> > perhaps the cgi.FieldStorage class does not properly handle such > >> > element names, or perhaps it considers such names erroneous. > >> > > >> > Next, it seems that the line "keys = form.keys()" might be out of > >> alignment > >> > with the rest of the code in it's block. Perhaps it's just the way it > >> > looks after you copied your code into the post. > >> > > >> > Regards, > >> > Jeff > >> > > >> > > >> > >> > >> > >> Yes, the problem is that keys does not contain any items. The 'weird' > > names > >> are not the problem, because i tried it also with regular 1-word names > >> (no > >> slashes), with the same results. Also, the keys=form.keys() line is > >> properly indented in the code -- it was just a copy/paste problem. Here > > is > >> the code again, with the extraneous stuff stripped out: > >> > >> #!/usr/local/bin/python > >> > >> import cgitb; cgitb.enable() > >> import sys, traceback, cgi > >> > >> def main(): > >> try: > >> form = cgi.FieldStorage() > >> input = form.keys() > >> > >> print "Content-type: text/html\n\n" > >> print(""" > >> >> 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'> > >> > >> > >> test > >> > >> """) > >> print "

",keys,"

" > > > > # ^^^^ should be 'input' not 'keys', as it > > # is > > in my script. > > > >> print "" > >> except: > >> pass > >> > >> if __name__ == "__main__": > >> main() > >> > >> And the form is: > >> > >>
> >> > >> > >> > >> > >> > >> > >>
> >> > >> > >> The script, again, is currently just supposed to return the keys, which > >> I > > am > >> expecting to be Name, PartNumber, etc., but it returns only an empty > >> list. Any ideas. > >> > >> thanks, > >> > >> jano > >> > >> > >> > Jeff, did this work for you just on the command line? Or over the internet too? I get an 'internal server error' when I try to submit from your form, and I don't have access to the server logs -- it works fine from the command line, but it seems to be a parsing problem with the form data. The server is running python 2.2.1 (apache 1.3.26) on solaris 5.6. This is a different problem than my original problem -- keys() returning [] -- since I can't even get an empty list anymore, but with my original code, i get the expected list if I use method="submit" (get), and I get an empty list if I use method="post". I am about to give up and do what I need to do in Java, as I have deadlines approaching. thanks, jano From neal at metaslash.com Thu Sep 19 09:14:42 2002 From: neal at metaslash.com (Neal Norwitz) Date: Thu, 19 Sep 2002 13:14:42 GMT Subject: try import except want lineno from Exception References: Message-ID: On Thu, 19 Sep 2002 00:23:39 -0400, Ben Gerblich wrote: > I am importing module files, and want to catch an error (if any) and > print the filename and line number of the error. The "Exception ,e" does > not return, or does not have the attirbutes listed above. It only > returns e="line() takes exactly 2 arguments (3 given)" See inspect.getfile() and inspect.getlineno(). You will need a frame which you can get from sys.exc_info() Neal From ark at research.att.com Wed Sep 4 15:46:49 2002 From: ark at research.att.com (Andrew Koenig) Date: Wed, 4 Sep 2002 19:46:49 GMT Subject: Why read-only nested scopes? References: Message-ID: Gon?alo> Anyway, I've been directed to PEP 227, cheerfully obeyed, and Gon?alo> from what I have understood having read-only nested scopes Gon?alo> was more of a design decision than something else. And while Gon?alo> I can live happily with the decision (some would even say Gon?alo> happier) there is something about the "You can look at it but Gon?alo> not touch it" attitude that I dislike ;-) You can do anything to the object that the object support. What you can't do is change the binding of the name. x = [] def foo(y): x.append(y); foo(3) foo(4) foo(5) After executing this code, x is [3, 4, 5]. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From bobx at linuxmail.org Wed Sep 11 17:01:41 2002 From: bobx at linuxmail.org (Bob X) Date: Wed, 11 Sep 2002 21:01:41 GMT Subject: [FEEDBACK] Is this script efficient...is there a better way? Message-ID: I am a newbie at this and this is a script I have come up with. I am looking for pointers on any "newbie" gotchas or ways to do it better. I use this to parse a log file (30MB+) for keywords and write the lines that are found into another file. Any thoughts would be appreciated... :-) Bob #!/usr/local/bin/python -w # import the needed libs import sys, string # make sure the command line arguments are there if len(sys.argv) < 3: print "usage: fread.py [log file] [hit file]" sys.exit(1) # open the files with some error checking try: inFile = open(sys.argv[1],"r") except IOError: print "Cannot open log file!\n" sys.exit(1) try: outFile = open(sys.argv[2],"w") except IOError: print "Cannot open hits file!\n" sys.exit(1) # build list of keywords kw = [ "some", "words" ] # loop through the list and print the lines to a file for line in inFile.readlines(): for badword in kw: if line.find(badword) > -1: result = '%s %s' % (badword, line) print result # Print the result outFile.write(result) # Write the result # close the files inFile.close() outFile.close() # let me know when it's done print "Finished processing file..." From teaandbikkie at aol.com Fri Sep 6 10:42:10 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 06 Sep 2002 14:42:10 GMT Subject: example for using calldll with python2.2 References: Message-ID: <20020906104210.15840.00000001@mb-cv.aol.com> There is a link to the binary at: http://www.python.org/ftp/python/binaries-1.4/pythonwin/html/pwmodules.htm l#calldll From aleax at aleax.it Thu Sep 19 14:42:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 18:42:16 GMT Subject: Copy with __slots__ References: Message-ID: Antonio Cuni wrote: > Griebel, Peer wrote: > >> So my advice now is: Use slots! The program runs faster, uses less >> memory. And explicitly coding a __copy__ function which copies each >> attribute isn't a bad thing per se. It makes the things more explicit. > > (sorry for my bad english...) English excellent, Python less so:-) (...just kidding...) > we can make it easier by providing a metaclass that creates a __copy__ > method for us: > > class autocopy(type): > def __new__(cls, name, bases, dic): > def __copy__(self): > res = self.__class__() > for attr in dic['__slots__']: > setattr(res, attr, getattr(self, attr)) > return res > > dic['__copy__'] = __copy__ > return type.__new__(cls, name, (object,), dic) This doesn't deal with inherited __slots__. Easy to solve, mind you -- autocopy.__new__ just needs to look for __slots__ in the bases, too, and accumulate them all into a sequence on which the nested __copy__ function can loop. Some care is needed, though (I can think of several possible anomalies). Alex From TOGLIMIcuni at programmazione.it Thu Sep 19 15:01:50 2002 From: TOGLIMIcuni at programmazione.it (Antonio Cuni) Date: Thu, 19 Sep 2002 19:01:50 +0000 Subject: Copy with __slots__ References: Message-ID: Griebel, Peer wrote: > So my advice now is: Use slots! The program runs faster, uses less > memory. And explicitly coding a __copy__ function which copies each > attribute isn't a bad thing per se. It makes the things more explicit. (sorry for my bad english...) we can make it easier by providing a metaclass that creates a __copy__ method for us: class autocopy(type): def __new__(cls, name, bases, dic): def __copy__(self): res = self.__class__() for attr in dic['__slots__']: setattr(res, attr, getattr(self, attr)) return res dic['__copy__'] = __copy__ return type.__new__(cls, name, (object,), dic) Python 2.2 (#1, Feb 24 2002, 16:21:58) [GCC 2.96 20000731 (Mandrake Linux 8.2 2.96-0.76mdk)] on linux-i386 Type "help", "copyright", "credits" or "license" for more information. >>> import copy, autocopy >>> class foo(object): ... __metaclass__ = autocopy.autocopy ... __slots__ = ['x', 'y'] ... >>> f = foo() >>> f.x = f.y = 41 >>> bar = copy.copy(f) >>> print bar.x, bar.y 41 41 Anto -- "Computer science is not about computers any more than astronomy is about telescopes." -- EW Dijkstra From gerhard.haering at gmx.de Sat Sep 28 22:10:02 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 29 Sep 2002 02:10:02 GMT Subject: Need example for subclassing long in C Message-ID: I'm trying to add range checks to long and successfully did a Python implementation. Now I want to translate it to C. Could anybody offer an example of subclassing a built-in number type at the C level? Another question I have is how do I do the "long.__add__" call below at the C-level? I'd like to do it as optimized as possible. def __add__(self, other): val = long.__add__(self, other) PgInt8_checkresult(val, "addition") return PgInt8(val) -- Gerhard From David.Kastrup at t-online.de Sun Sep 22 11:42:34 2002 From: David.Kastrup at t-online.de (David Kastrup) Date: 22 Sep 2002 17:42:34 +0200 Subject: Using emacs gud/pdb python debugger under windows References: <87elbuo46g.fsf@tleepslib.sk.tsukuba.ac.jp> <87n0qiul6j.fsf@computer.localdomain> <3cs86d38.fsf_-_@online.no> Message-ID: Syver Enstad writes: > Felix writes: > > > u just need to fix a few things to make it recogonize the win32 path. > > here's how, open gud.el and search for the variable > > 'gud-pdb-marker-regexp', [...] > > Ha, ha it works, it works! (Dancing around the room) I want to hug you > Felix! I didn't think of that, obviously. So it was just pdb failing > to recognize the output from the windows version of python. The newest CVS contains this fix: apparently somebody passed it to the right people. -- David Kastrup, Kriemhildstr. 15, 44793 Bochum Email: David.Kastrup at t-online.de From dbasch at yahoo.com Mon Sep 30 17:26:28 2002 From: dbasch at yahoo.com (Derek Basch) Date: Mon, 30 Sep 2002 14:26:28 -0700 (PDT) Subject: Catching user defined exceptions from foreign modules In-Reply-To: Message-ID: <20020930212628.97334.qmail@web20805.mail.yahoo.com> Thanks for this snippit: > For class exceptions, in a try statement with an > except clause that > mentions a particular class, that clause also > handles any exception > classes derived from that class (but not exception > classes from which > it is derived). Two exception classes that are not > related via > subclassing are never equivalent, even if they have > the same name. It really helped me understand. I subclassed my 'TestError' exception from a base exception class 'Error' which was derived from the 'Exception' class. As shown in this example: http://www.python.org/doc/current/tut/node10.html#SECTION0010500000000000000000 So I could have just caught the imported modules base exception class and as long as the generated exception is a subclass of the base class it will be caught. Cool!! To bad the python book I learned from never covered this :(. I will have to add this to a bunch more modules now that I understand how to use it properly. I think I had better give the base exception classes unique names as well to avoid import conflicts. Thanks for all the help, Derek Basch > > Thanks, > > By 'built in' I meant the python built in module > exceptions: > > http://web.pydoc.org/2.2/exceptions.html > > I'll have to confess that I haven't kept fully up > on the changes (like > making all exceptions "class-based"). > > To me, "built in" tends to imply something > available without explicit > imports... > > I think the following paragraph from the document > is applicable... > > For class exceptions, in a try statement with an > except clause that > mentions a particular class, that clause also > handles any exception > classes derived from that class (but not exception > classes from which > it is derived). Two exception classes that are not > related via > subclassing are never equivalent, even if they have > the same name. > > You created a subclass exception as I recall (I > deleted the files I'd > copied so can't check). The main program could have > caught that if you > had just listed the base exception rather than the > specific subclass. > Without actually testing code (I'm rushing -- have > an appointment in 45 > mins)... > > #t1.py > from t2 import I_Fail > > try: > I_Fail(123) > except ArithmeticError, e: > print "Arithmetic Error: '%s' Occurred" % e.value > > > #t2.py > > class MyFailure(ArithmeticError): > def __init__(self, value): > self.value=value > def __str__(self): > return `self.value` > > def I_Fail(a): > if a is not None: > raise MyFailure("I_Fail received a non-null > argument") > > > > > > > Im assuming these are automatically imported > anytime the interpreter > > is fired up. I will use the 'from module import > alpha, beta, > > charlie' syntax as this seems to be the best way. > At least according > > to the ActivePython documentation/Python HOW > TO's/Do's and Dont's. > > They even have your open() idiom in the HOW TO. > > Thanks for all the help, > > Derek Basch > > > > --- In python-list at y..., Dennis Lee Bieber > wrote: > > > Derek Basch fed this fish to the penguins on > Monday 30 September > > > > 2002 > > > > > 08:59 am: > > > > to have to import user defined exceptions? I > dont > > > > rememeber having to import any of the built in > > > > exceptions. So, here is the output of the > fixed test1: > > > > > > "built-in" -> already there... > > > > > > > test2.TestError > > > > fudge > > > > > > > > Am I doing this all wrong? > > > > > > You want to use items defined in an > imported module. I see > > > > three > > > > > alternatives... > > > > > > import module > > > > > > all uses then become module.item > > > > > > from module import item1, item2, ... itemN > > > > > > only the named items are useable, but > can be used as itemM > > > > > > from module import * > > > > > > practically everything within the module > is available as > > > > item > > > > > The last is not recommended as you can encounter > unexpected > > > redefinition of names... In the last week we had > one such... > > > > > > from os import * > > > > > > replaces the Python open() (which I understand > is being phased out > > > > for > > > > > file()) with the low-level (C-style) open -- > totally different > > > arguments needed. > > > > > > -- > > > > > > > > ============================================================== > < > > > > wlfraed at i... | Wulfraed Dennis Lee Bieber > KD6MOG < > > > > wulfraed at d... | Bestiaria > Support Staff < > > > > > ============================================================== > < > > > > Bestiaria Home Page: > http://www.beastie.dm.net/ < > > > > Home Page: > http://www.dm.net/~wulfraed/ < > > > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > -- > -- > > > ============================================================== > < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee > Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria > Support Staff < > > > ============================================================== > < > > Bestiaria Home Page: > http://www.beastie.dm.net/ < > > Home Page: > http://www.dm.net/~wulfraed/ < __________________________________________________ Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! http://sbc.yahoo.com From martin at v.loewis.de Mon Sep 16 13:14:47 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 16 Sep 2002 19:14:47 +0200 Subject: problems when parsing & with xml.dom.minidom.parseString References: Message-ID: jcc at ibdosnorte.com (Juan Carlos CORU?A) writes: > Anyone knows the solution? >>> node.firstChild.childNodes[0].nodeValue u'one ' >>> node.firstChild.childNodes[1].nodeValue u'&' >>> node.firstChild.childNodes[2].nodeValue u'two' >>> node.normalize() >>> node.firstChild.childNodes[0].nodeValue u'one &two' In PyXML 0.8.1, in this case, you will already get normalized data right after parsing. HTH, Martin From tmohr at s.netic.de Sat Sep 14 23:38:35 2002 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 15 Sep 2002 05:38:35 +0200 Subject: embedding Python, several instances? Message-ID: Hi, i'd like to use Python as a scripting language for a C program and the examples in the documentation work quite well. When i now run two scripts, the definitions that were done in the first one are seen in the second one. How can i run each script in one instance of the python interpreter? Best regards, Torsten. From tdelaney at avaya.com Thu Sep 26 02:32:19 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 26 Sep 2002 16:32:19 +1000 Subject: revenge of the python puzzle Message-ID: > From: David Eppstein [mailto:eppstein at ics.uci.edu] > > I'm not going to spoil this, just point out that my cryptogram applet > http://www.ics.uci.edu/~eppstein/cryptogram/ (sorry, not written in OK - you *gotta* stop case conversions on that thing ... Tim Delaney From mark.charsley at REMOVE_THIS.radioscape.com Mon Sep 23 11:22:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Mon, 23 Sep 2002 16:22 +0100 (BST) Subject: M$SQL connections from linux References: <1032528860.599940@news.etel.ru> Message-ID: In article <1032528860.599940 at news.etel.ru>, black at flamingo.ru (Vasiliy A. Chernoivan) wrote: > Hello all > Is there some module for python which performs the task? > Is it possible at allto access data under M$SQL from linux machine? Not used it myself, but mxODBC should do the job: http://www.egenix.com/files/python/mxODBC.html -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From mhammond at skippinet.com.au Sat Sep 14 04:24:06 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Sat, 14 Sep 2002 08:24:06 GMT Subject: threads or queue for this task References: Message-ID: robin at execulink.com wrote: > I am missing something I think with the difference between the > threading and Queue modules. These could really do with some updated > docs with examples. > > I wish to have a server continually cycle (until interrupted by > keyboard, signal, or whatever). It needs to perform several (say 6) > different tasks, each of which may take significantly different > lengths of time to perform. > > My first implementation used threading.py. I wrote a dispatcher to > start each of the threads, and then wait until the thread count was > back down to 1. This I put in a while loop, and surrounded it with the > necessary exception code. > > Each cycle through the while has to wait for the slowest process to > finish before completing. During this time, the other processes just > sit around doing nothing. What I really want is for each process to > start up again when they are done, so that there are no more than 6 > going at once. In other words, I want to be sure I don't start a new > process 3 before the old process 3 is done. > > I have looked at Queue but it doesn't seem to have enough control to > make this happen. > > I am sure I am overlooking something obvious. Thanks ahead of time for > any help! It is common for threading code to look somewhat like: threads = [] for i in range(number_of_tasks): thread.append(thread_for_task) # let the threads run - just wait for shutdown for t in threads: t.join() Each thread itself contains a loop which continually look for more work to do, or exit. The queue module is useful for giving threads work to do - some other thread can queue new things, and the worker thread removes them, blocking while nothing is in the queue. Look for Aahz's threading tutorial - URL not at hand, but it can't be too hard to find. Indeed, I predict he will tell you exactly where it is ;) Hope this helps, Mark. From a_salnikov at yahoo.com Mon Sep 16 17:30:06 2002 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Mon, 16 Sep 2002 14:30:06 -0700 Subject: Anyone can tell me why? References: <1815200.1031973626@dbforums.com> <1817360.1032087013@dbforums.com> Message-ID: "hpyhpy" wrote in message news:1817360.1032087013 at dbforums.com... > > But I try,change the filename as "example.so","_example.so", > "examplemodule.so",#_#,same error......have other advise?^_^ > Hmm, there is no obvious reason why it should not run when renamed to example.so or examplemodule.so. Here is my list of possible causes: 1. You run python from directory different from where your .so lives in. Python finds everything in the well-defined places, which includes local directory. From python prompt type: >>> import sys >>> print sys.path to see the list of directories where python can find a module. Do not put your module outside of any directory in this path. 2. Your python was built without support for dynamic loading. Don't know how to check this. Ask the person who installed/configured your python. 3. Shared library was not build correctly. I'm not familiar with SCO but usually with gcc I do 'gcc -shared object.o -o whatever.so' and that works. 4. Whatever else.... Andy. From amk at amk.ca Mon Sep 30 17:42:13 2002 From: amk at amk.ca (A.M. Kuchling) Date: Mon, 30 Sep 2002 21:42:13 -0000 Subject: curses troubles References: Message-ID: In article , Kat & Huw wrote: > Now, when running this, if I hit either G or P, the applications >closes as if I'd hit Q > any idea what I'm doing wrong here? Perhaps your application is raising some exception, but the traceback isn't being displayed because of the terminal mode. The curses module contains a wrapper(func, *args) function that will set up the curses screen and call func(), which should be your main function. If func() raises an uncaught exception, wrapper() will restore the terminal mode and let the traceback be printed. Maybe that will help. --amk From ataylor at ucsd.edu Fri Sep 27 15:55:51 2002 From: ataylor at ucsd.edu (Adam Taylor) Date: 27 Sep 2002 12:55:51 -0700 Subject: Getting started References: <3D911306.7080609@ucsd.edu> Message-ID: >> Statically typed Dynamically typed Untyped >>Strongly checked ML LISP >>Weakly checked C Assembler > >I agree. So where in this spacewould YOU put Python and Perl? Python is in the same square as Lisp (which I mentioned). So is Perl. At least using this terminology... ;) > I was translating his internal vocabulary to use the term we started > with. He defines "weakly checked" only in terms of "static checking". > Since they're synonyms, this reference only supports a def of "weakly > typed" in terms of static checked languages. So I'm saying the > reference does not help us nearly as much as I would like. Okay, that's true, he does define weakly-checked only in terms of statically checked languages, which I hadn't appreciated: In reality, certain statically checked languages do not ensure safety. That is, their set of forbidden errors does not include all untrapped errors. These languages can be euphemistically called _weakly checked_ (or _weakly typed_, in the literature) meaning that some unsafe operations are detected statically and some are not detected. But the clear generalization of this (it seems to me) is to define weakly checked languages as languages in which some unsafe operations are detected and some are not detected. In other words, just delete the word "statically" from the last sentence in the quote above. Of course, it doesn't sound like any existing languages are both dynamically typed and weakly checked (and I can't think of any myself): Most untyped [read dynamically typed] languages are, by necessity, completely safe (e.g., LISP). Otherwise, programming would be too frustrating in the absence of both compile time and run time checks to protect against corruption. Adam ----- "James J. Besemer" wrote in message news:... > Adam Taylor wrote: > > >This sounds like the same thing as I said, or damn close. Am I > >missing something? > > > > Not really. Just different emphasis. > > >Yes. It seems to me that Table 1 in Cardelli: > > > > Typed Untyped > >Safe ML LISP > >Unsafe C Assembler > > > >Might be better like this: > > > > Statically typed Dynamically typed Untyped > >Safe ML LISP > >Unsafe C Assembler > > > >(Python would also be in the (Safe,Dynamically typed) position.) > > > >Although safety and strongly-checked are not the same thing, this > >table is also correct: > > > > Statically typed Dynamically typed Untyped > >Strongly checked ML LISP > >Weakly checked C Assembler > > > > I agree. So where in this spacewould YOU put Python and Perl? > > >>A literal reading furthermore defines "weakly typed" only in > >>terms of static checking. > >> > >> > > > >I don't understand what you mean by this. Cardelli never uses the > >term "weakly typed" himself, he only uses it that one time, to say > >that it's the term most people use for the concept that he prefers to > >call "weakly checked". > > > > I was translating his internal vocabulary to use the term we started > with. He defines "weakly checked" only in terms of "static checking". > Since they're synonyms, this reference only supports a def of "weakly > typed" in terms of static checked languages. So I'm saying the > reference does not help us nearly as much as I would like. > > >Or at > >least when people start talking about "strongly typed" vs "weakly > >typed" languages, that first thing to get straight is which axis > >they're talking about. > > > Fair enough. > > --jb From Phil.Rittenhouse at dspfactory.com Wed Sep 4 17:43:23 2002 From: Phil.Rittenhouse at dspfactory.com (Phil Rittenhouse) Date: Wed, 4 Sep 2002 17:43:23 -0400 Subject: Installing Python 2.2.1 on WinNT Message-ID: Thanks for the help Trent. I have the lastest NT service pack installed (sp6a). I'm not sure what DLL could not be loaded, the error message just gives a bunch of garbage for the DLL name. I suspect that it's trying to load a non-existant DLL for some reason. I am using the python.org installer, and I suspect the problem lies in the WISE code. To see if the problem was related to permissions, I tried installing, while logged in as administrator, and it still threw up the warning dialog about installing without admin privileges. So, clearly, something's wrong with the detection of administrator privileges. The ActivePython install worked fine, but we'd rather ship the install from python.org if possible. I'd like to hear from any other NT 4.0 users that have tried installing Python 2.2. Is it just me? Thanks! Phil Trent Mick State.com> cc: python-list at python.org Subject: Re: Installing Python 2.2.1 on WinNT 30/08/2002 07:47 PM > I've run into a (actually two) problem installing Python 2.2.1 on > Windows NT 4.0. At the end of the install, it throws up an error > "Could not load the DLL library $%#%^$. The specified module could > not be found." Do you have the latest service pack and fixes from MSDN for your NT box? I have found that getting the latest updates often fixes some "Could not load the DLL library" and "Page fault in..." and "Invalid entry point in" errors. What DLL could not be loaded? Are you running the python.org installer? You could also try ActivePython: http://www.activestate.com/Products/ActivePython/ Cheers, Trent -- Trent Mick TrentM at ActiveState.com From umop at psyon.org Wed Sep 18 17:04:12 2002 From: umop at psyon.org (Eric Arnold) Date: Wed, 18 Sep 2002 14:04:12 -0700 Subject: Regex question Message-ID: Hi folks, I'm trying to figure out why this is not working, and wonder if there are any regexperts out there who can give me a pointer. The string I'm capturing is as follows: Name:AAA,BBB,CCC where I'd like to extract the following data: : Name : AAA : BBB : CCC this is the regular expression I wrote to do so: (?.*):(?([^,]*(?=,))|((?<=,)[^,]*))+ I tried it with the (?<=,) as another (?=,) too, but no luck. I imagine that the problem is that when the (?=) is used once, it can't be used with the second group, but I don't know a way around that. Thanks! Eric From m2 at plusseven.com Fri Sep 20 07:42:55 2002 From: m2 at plusseven.com (Alex Polite) Date: Fri, 20 Sep 2002 13:42:55 +0200 Subject: debugging "Too many open files" In-Reply-To: References: Message-ID: <20020920114255.GB1710@matijek.plusseven.com> On Thu, Sep 19, 2002 at 07:27:53PM +0200, Martin v. L?wis wrote: > Depends on what you mean by "pointing to". It is extremely rare that a Symlink. My thinks? > process opens /dev/hdc, since that requires superuser permissions; I Well. I was running this as root. > know of no case where a program opens /dev/hdc more than once. > > So by "pointing to", you probably meant something else. Care to > provide precise data? What did you do, how did the computer respond, > how do you interpret this response? Looking closer into the matter I realised that /dev/hdc (my dvdplayer) was not valid device, since the ide-cd kernel module wasn't loaded. I loaded the module, restarted the python process and now everything is working fine. So thanks a lot for the pointers Martin. No the next step would be to have python check that /dev/hdc is a valid device and throw an exception if it's not. Any idea how that should be done? alex -- Alex Polite http://plusseven.com/gpg/ From marklists at mceahern.com Thu Sep 26 12:56:05 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 26 Sep 2002 11:56:05 -0500 Subject: design question In-Reply-To: <1ha6pukqdqell8f31q1k7rtor2rv5ogjs0@4ax.com> Message-ID: [Gon?alo Rodrigues] > I know I am being a little vague in my question, but does anyone have > any ideas? Open-source code where this "same problem" has been tackled? Have you considered metaclasses? Do you need a concrete Wrapper for each class? Why not a generic wrapper that wraps any given class? // m From imbosol at vt.edu Tue Sep 3 14:39:25 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 3 Sep 2002 14:39:25 -0400 Subject: Design question.... parent/child class References: <3d74b021$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: Gumuz wrote: > hi all, > > i have a SessionManager class, which contains a list of Session > objects(instantiated from a Session class). I have a design problem. > > Each session object has a small 'queue' of messages for the specific > session. How can a session send a message to another session without having > some kind of parent-reference to the SessionManager object? > > i am a bit puzzled, or is this parent-reference not such a bad idea after > all? If you can, make the function that transfers a message a member of SessionManager class, instead of Session. (Or, if that's not how your program is set up, have the function that transfers a message take your SessionManager instance as an argument, or something like that. The idea is to access the sender or receiver through the SessionManager class.) If you can't, think about how easy it would be to change your code so that you could. And if it's not too hard, do it. Abstractly, you want to operate on two siblings in your hierarchy. You should want to take advantage of the hierarchy; therfore, your operation should belong to the parent, which contains both sibling nodes. If you want to do this operation without the help of then parent, then you're circumventing (or at least not taking advantage of) the hierarchy structure. -- CARL BANKS http://www.aerojockey.com From news at NOSPAMmajid.fm Mon Sep 9 22:36:36 2002 From: news at NOSPAMmajid.fm (Fazal Majid) Date: Mon, 09 Sep 2002 19:36:36 -0700 Subject: Aristotle and Python References: Message-ID: James J. Besemer wrote: >> Larry Wall Wrote: >> >> "Python is cool to look at small bits of, but I think the "outline" >> syntax breaks down with larger chunks of code. I'm with Aristotle on >> the structure of discourse--a story should have a beginning, and >> middle, and an end. So should blocks" > Typically, he substitutes a cute particle of rhetoric for a meaningful > response. That's funny, I hadn't read Larry's article as I am not all that interested in Perl (dropped it for Python in 94, haven't looked back since), but I set out an Aristotle comparison at about the same time. One of the good things about Python is that it is non-aristotelian: http://www.majid.info/radio/2002/09/07.html#a30 -- Fazal Majid From dwelch91 at nospam.attbi.com Sat Sep 21 01:31:53 2002 From: dwelch91 at nospam.attbi.com (dwelch) Date: Sat, 21 Sep 2002 05:31:53 GMT Subject: newbie seeks advise. References: <77c84db2.0209192137.51167ebb@posting.google.com> <3D89F605.4030303@nospam.attbi.com> <3D8AB73E.2322DDAC@alcyone.com> Message-ID: <3D8B441E.304@nospam.attbi.com> Erik Max Francis wrote: > dwelch wrote: > > >>Simple way, probably not optimal: >> >> >>> max_element = max(list(data)) >> >>> max_element >>74 >> > > max works on any sequence, there's no need to preconvert the tuple to a > list. > > Yes, of course you are correct (that would be inconceivably inconsistent for Python). However, when I first looked at using max() with a tuple on 2.2.1 on WinXP, it didn't work. I got a TypeError stating that max() requires a sequence type. Now, I am trying it on Mandrake 8.2 with 2.2.1, it and it works. Hmmmm.. not sure what is going on here, I will have to double check when I am on my XP box again. Don From sross at connectmail.carleton.ca Tue Sep 24 23:36:01 2002 From: sross at connectmail.carleton.ca (Sean Ross) Date: 25 Sep 2002 03:36:01 GMT Subject: Removing all occurences of a character from a string. References: Message-ID: Thank you Justin. How about this, then: I have a list of lists of these strings and I want to apply replace to each string in the list of lists. So, say: attr = [ ["'gill-attachment'", "'a'", "'d'", "'f'", "'n'"],["'gill-spacing'", "'c'", "'d'", "'w'"], ["'gill-size'", "'b'", "'n'"]] I can do the following: for i in xrange(0, len(attr)): for j in xrange(0,len(attr[i])): attr[i][j] = attr[i][j].replace("'","") to get what I want; which is: [ ['gill-attachment', 'a', 'd', 'f', 'n'],['gill-spacing', 'c', 'd', 'w'], ['gill-size', 'b', 'n']] Is there a nicer way to do this? Sean "Justin Shaw" wrote in message news:DL9k9.201596$216.7001230 at bin4.nnrp.aus1.giganews.com... > > How can I remove the single quotes so that "'Hello World'" becomes "Hello > World"? > > Try this one: > > >>> s = "'Hello World'" > >>> print s.replace("'", "") > Hello World > >>> > > Justin > > > I have a string, say "'Hello World'", where Hello World is in single > > quotes(i.e., 'Hello World'). How can I remove the single quotes so that > > "'Hello World'" becomes "Hello World"? > > Thanks > > Sean Ross > > > > > > From aleax at aleax.it Wed Sep 25 18:13:25 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 22:13:25 GMT Subject: readlines() and "binary" files References: <3d90cacf$0$30457$afc38c87@sisyphus.news.be.easynet.net> <9r8k9.46422$V7.11170409@twister.socal.rr.com> <3d91de2d$0$30457$afc38c87@sisyphus.news.be.easynet.net> Message-ID: <9yqk9.143972$ub2.3161265@news1.tin.it> Justin wrote: ... > at a time, so that's rather overkill. If anyone can think of a more > economical way of doing it (short of defining my own iterator), I'd > be interested. Pity you ruled out defining your own iterator -- in Python 2.2.1...: from __future__ import generators def splitby(fileobj, splitter, bufsize=8192): buf = '' while True: try: item, buf = buf.split(splitter, 1) except ValueError: more = fileobj.read(bufsize) if not more: break buf += more else: yield item + splitter if buf: yield buf I think it's more or less the simplest approach. Alex From leafnode-usenet at schabi.de Thu Sep 19 09:32:05 2002 From: leafnode-usenet at schabi.de (Markus Schaber) Date: Thu, 19 Sep 2002 15:32:05 +0200 Subject: linux python ideas References: <3D88E578.6010001@diespammerdieuselesspython.com> Message-ID: <20020919153205.6fd58389.leafnode-usenet@schabi.de> Hallo, Rob Andrews schrieb: > Any suggestions would be appreciated, since my notes are pretty > generic so far. I held such a presentation here in Ulm (Germany), you can see the German data at http://ulm.ccc.de/~schabi/python/index.html - this file is identical to the presentation, just use Opera 6 or later and press F11 (or use any other CSS presentation mode capable browser) Gru?, Markus From gerhard.haering at gmx.de Fri Sep 27 12:01:44 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Fri, 27 Sep 2002 18:01:44 +0200 Subject: DBI cursor behaviour with multiple statements? In-Reply-To: <7e964d1d.0209270137.568a3f3@posting.google.com> References: <7e964d1d.0209270137.568a3f3@posting.google.com> Message-ID: <20020927160143.GA1055@lilith.ghaering.test> Hi Henrik, * Henrik Weber [2002-09-27 02:37 -0700]: > I'm trying to write a DBI2 compliant module for Microsoft Access > databases. Ok. Then the Database SIG's mailing lists is the appropriate place to ask. You'll find that almost all module authors and many users are subscribed there. > Now I'm not quite sure how to interpret the DBI2 specification when it > comes to the execution of multiple data returning statements with the > same cursor. The behaviour is undefined for more than one DQL statement. And .nextset() isn't meant for this case, either. In fact, I asked the same question on the SIG's mailing list some time ago: Date: Tue, 28 May 2002 21:36:47 +0200 To: Python DB-SIG Mailing List Subject: [DB-SIG] Multiple Statements Message-ID: <20020528193647.GA902 at lilith.my-fqdn.de> ... and was referred to a discussion about a year ago (then), where the consensus was what I summarized above. Here's the SIG's mailing list: http://python.org/sigs/db-sig/ Btw. an updated form of the specification several interesting "optional features" is available as PEP 0249. -- Gerhard From mcherm at destiny.com Mon Sep 16 12:22:13 2002 From: mcherm at destiny.com (Michael Chermside) Date: Mon, 16 Sep 2002 12:22:13 -0400 Subject: Skipping Parts of a For Loop References: Message-ID: > Thomas Guettler wrote: >>Is there a way to skip some parts in a for loop? >> [...] >>"continue" skipps one element. But how can >>I skip several? Andrew Henshaw wrote: > While not really answering your question... In my opinion, it would be > better to use a while loop for that purpose. The code would be much > clearer. I agree with Andrew. I think the cleanest and most readable way to do it would be as follows: i = 0 while i < UPPER_BOUND: do_some_processing() if condition: i += AMOUNT_TO_SKIP do_more_processing() i += 1 It makes it very explicit that you are skipping several values of i, and any programmer could read this code and understand what it's doing. It would be even BETTER if you used a meaningful name for i (perhaps "line_number", or "record_id"... use something appropriate to what you're doing). -- Michael Chermside From henrik.motakef at web.de Sat Sep 28 16:11:38 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 28 Sep 2002 22:11:38 +0200 Subject: What does Python fix? References: <3d95fb09@news.vip.fi> Message-ID: <87ptuxub5x.fsf@pokey.henrik-motakef.de> Pekka Niiranen writes: >>Shrug. Lisp trades one form of complexity for another. By reducing >>the solution to a universal grammar, they increase the symbolic load >>on the user, who is awash in a page full of very similar symbols. >>This is intimidating in particular to novices, for whatever reason, >>who are instantly alienated. Without sweeping in novices, you lack >>a grass roots movement, and without a grass roots, a language is dead. >> >>The parts of lisp that really matter to the community have since >>been adopted in part by many other languages. Lisp is dead. Long live >>Lisp. > Sure, Python's syntax looks nice, but to use another language to get > performance (i.e speed) ? That sucks. Let's not forget that Python's syntax (most of all the significance of whitespace) is considered strange at least by about all novices. In both cases - significant whitespace and lots of irritating superflous parentheses - people don't just get used to it, but tend to like it after a while. Another rather cool feature of lisp that python lacks are macros, btw, or in general the uniform handling of code and data. > I have a feeling Python might renew peoples interest to various lisps. That would be nice. The one thing lisp lacks is a huge community, manifesting itself in lots of ready-to-use libraries, tutorials etc. I guess the mere existence and visibility of Python (and Ruby, for example) is a Good Thing - there's choice again, and when people are thinking about what language they should use, it's not just the question "should I use C or Perl" (or, depending on the platform you are socialized on, "should I use C++ or Visual Basic") any more - it is more obvious that there are a lot of high-level languages one could use, and that they differ significantly. That doesn't only help the highly visible languages like Python, but also the more obscure ones like Lisp, or Objective Caml for example. > After studying Python for 2 years I myself have > recently switched to DrScheme because I have no interest > relearning C to write extensions to Python. > > What an eye opener it has been to study scheme... Ack. Learning Lisp (I prefer Common Lisp over Scheme myself, but IMHO you should know both) is something any programmer should do sometimes. Of course, learning and using Python isn't a bad thing, either... Regards Henrik From jpm at papercut.org Mon Sep 9 20:17:55 2002 From: jpm at papercut.org (Joao Prado Maia) Date: Mon, 9 Sep 2002 20:17:55 -0400 (EDT) Subject: [ANN] Papercut 0.9.0 - python nntp server Message-ID: Papercut is a multi-threaded news server written in Python. Its main objective is to integrate existing web based message board software (Phorum [http://phorum.org] is the most supported one) with an Usenet front-end. However, its extensibility enables developers to write their own containers for the storage of the Usenet articles (messages). That means that the code is extensible enough that _you_ could write new containers to integrate the news server with other web message board projects or even with other ways to store the messages. The source code is available freely under the BSD license, which means you can do whatever you like with it. I do welcome any and all contributions to the project :) A quick description of the changes on this release: - Mostly a lot of testing regarding the NTTP authentication code. The authentication stuff should be pretty much rock solid and it was tested successfully using the following Newsreaders: Mozilla Newsreader, Netscape 4.79 Newsreader, Outlook Express and Knode (KDE's default newsreader). More information and download instructions can be found on the project site -> http://papercut.org Cheers, Joao Prado Maia From bloke at ii.net Sun Sep 15 11:15:09 2002 From: bloke at ii.net (Rob Hall) Date: Sun, 15 Sep 2002 23:15:09 +0800 Subject: confused with class inheritance References: <3d83fa2c$0$24041@echo-01.iinet.net.au> Message-ID: <3d84a3ed$0$24051@echo-01.iinet.net.au> Doh From phil at river-bank.demon.co.uk Thu Sep 19 08:27:27 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Thu, 19 Sep 2002 13:27:27 +0100 Subject: Is there a widget or program for a database browsing In-Reply-To: <3D89DA60.8878.8D30C74@localhost> References: <3D89DA60.8878.8D30C74@localhost> Message-ID: <200209191327.27196.phil@river-bank.demon.co.uk> On Thursday 19 September 2002 1:08 pm, A wrote: > Hi, > In my program users will search a database and I need to display choosen > record(s ) in a nice graphical way. Is there a module( program), that I > could use together with Python, that could easily show the database > record(s) and take care of all thinks during browsing? Thanks for help. > Ladislav PyQt - check out the examples in the examples3/SQL directory. Phil From thp at cs.ucr.edu Sun Sep 22 22:13:55 2002 From: thp at cs.ucr.edu (thp at cs.ucr.edu) Date: Mon, 23 Sep 2002 02:13:55 +0000 (UTC) Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <%8ci9.138477$5r1.5541622@bin5.nnrp.aus1.giganews.com> Message-ID: Terry Reedy wrote: + "daniel w. moore" wrote in message + news:33b491f.0209181820.17b6ea70 at posting.google.com... +> It's occurred to me after some brainstorming on the subject that the +> C/perl construct +> +> a ? b : c +> +> can be arranged like this in python: +> +> (a and [b] or [c])[0] + If you *know* that b will evaluate as True (perhaps because it is a + non-null constant, then this can be simplified to 'a and b or c'. I + first used this several years ago. But why use grotesque hacks in the first place? "a ? b : c" is a well-established syntax for conditional expressions. Why doesn't Python simply adopt it? Tom Payne From alex at ivascu.comNoSpam Sat Sep 28 01:01:13 2002 From: alex at ivascu.comNoSpam (Alex Ivascu) Date: Sat, 28 Sep 2002 05:01:13 GMT Subject: windows xp command prompt References: <576c1752.0209271411.6d7bb4c4@posting.google.com> Message-ID: Did you install perl, etc. while the command prompt window was open? try starting another window.... just a thought... Alex Ivascu "mike henley" wrote in message news:576c1752.0209271411.6d7bb4c4 at posting.google.com... > i have installed the activestate perl, python, tcl, and pragmatic > programmer's ruby. when i go to the command prompt on windows xp and > type perl for example... (or python, ruby... etc) i get the following > message. > > 'perl' is not recognized as an internal or external command, > operable program or batch file. > > in the control panel| system | advanced | environment variables | Path > i have > > C:\ruby\bin;C:\Python22;C:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOW S\System32\Wbem > > does anyone know what i should do to fix this problem? (apart from the > obvious of restarting the machine) From stefanus.arief at ai.astra.co.id Mon Sep 23 04:17:22 2002 From: stefanus.arief at ai.astra.co.id (Arief) Date: Mon, 23 Sep 2002 15:17:22 +0700 Subject: os module and sys module~ In-Reply-To: <20020923080057.955.qmail@web21310.mail.yahoo.com> Message-ID: Based on Python documentation: sys.path is "A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, or an installation-dependent default". os.path is "Common pathname manipulations". So in simple words, sys.path shows you only the search path where you imports modules (using "import" statement). The os.path is collection of functions that manipulate directory, file or path name. Mostly os module handles Operating System functions. ----- Arief -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org]On Behalf Of black Sent: Monday, 23 September 2002 3:01 PM To: python-list at python.org Subject: os module and sys module~ Hi, all~ I couldnt tell the difference between them immediately, and some same method confused me much, for example they both have "path" attribute but what's the difference ? From Oschler at earthlink.net Fri Sep 6 22:06:04 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Sat, 07 Sep 2002 02:06:04 GMT Subject: Multiple Python Apps on Linux Message-ID: If I run several single-threaded Python apps simultaneously, each launched as their own process running on Linux, are they truly independent or will Python's "global library lock flag" come into play like it does for a single Python app that is multi-threaded? thx From fperez528 at yahoo.com Fri Sep 27 18:01:06 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Fri, 27 Sep 2002 16:01:06 -0600 Subject: Better terminal for windows? References: <3D94B037.2020202@motorola.com> Message-ID: Chris Liechti wrote: >> So some of ipython's nicest functionality (full support for tab >> completion for both objects and files, and color-enhanced >> information, tracebacks and even syntax highlighted source info) are >> gone under Windows. >> >> If you know of a way to fix this, patches are welcome :) > > well there is ansi.sys. if that driver is loaded the terminal undestands > ansi escapes. long ago i used it under win95. it's still there in win2k but > don't know how to use it. it the old days you needed to load it in > config.sys. Thanks for the tip. I'll include it in the docs for the next release, for the benefit of Win users. Maybe I'll hear from them and get that part fixed (I don't use Windows myself). Cheers, f. From nhodgson at bigpond.net.au Tue Sep 24 21:56:50 2002 From: nhodgson at bigpond.net.au (Neil Hodgson) Date: Wed, 25 Sep 2002 01:56:50 GMT Subject: Pythonwin (win32all build 148) on Python 2.2.1 on Win2K, bogus syntax e References: Message-ID: Aaron Dimsdale and Alex Moser: > Pythonwin barfed on the quote marks marked by carets, returning: "Failed to run script - > syntax error - invalid syntax". Try turning on View | End-of-line markers to see if you have non-standard line endings such as pure carriage returns, which cause just this sort of error. On Windows, you want line endings to be carriage return + line feed. Neil From emile at fenx.com Fri Sep 6 10:32:32 2002 From: emile at fenx.com (Emile van Sebille) Date: Fri, 6 Sep 2002 07:32:32 -0700 Subject: Privacy and Inheritance References: <3D776CC2.CA928E38@fluent.com> Message-ID: "Mark Moales" wrote in message news:3D776CC2.CA928E38 at fluent.com... > Dennis, > > I think the point of the double underscores is to create "private" > attributes similar to C++'s or Java's private keyword. In other words, > only the class that defines the attribute can access it. Subclasses and > others can't. We use a single underscore here to denote "protected" > attributes, or attributes that are accessible by subclasses. However, > the only way to enforce this in Python is by having well behaved > programmers ;-) Here's an example: Just watch out for coincidental reuse of __privateVar in subclasses: class BaseClass: def __init__(self): self.publicVar = 'Foo' self._protectedVar = 'Bar' self.__privateVar = 'Spam' def showme(self): print self.__privateVar class SubClass(BaseClass): def aMethod(self): print self.publicVar print self._protectedVar # Can't do this because it's private # print self.__privateVar self.__privateVar = 'Ham' a = SubClass() a.showme() a.aMethod() a.showme() -- Emile van Sebille emile at fenx.com --------- From loewis at informatik.hu-berlin.de Fri Sep 27 08:59:39 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 27 Sep 2002 14:59:39 +0200 Subject: Unicode (inc. Japanese) in Python and TK References: Message-ID: gtaylor at lowebroadway.com (Garry Taylor) writes: > I'm just seeking a little reassurance regarding use of unicode in > Python, before I write my program, and then later find out I'm going > to have to re-write in Java or something. Basically, am I going to run > into any brick walls by doing the following: It will all work out well if you are willing to adjust your understanding of character sets, and Unicode, in the process of developing this application. > 1) Parsing XML with unicode characters. XML, per se, does not have 'unicode characters'. XML is typically stored in files, or other byte sequences. Those byte sequences have an encoding. If the encoding is known to Python, you can parse the document. Python will represent the strings as Unicode objects to you. > 2) Measuring unicode characters using TK I'm not sure whether this is possible. > 3) Printing unicode to a file Same comments as 1): If you know what encoding you want to use in the file, and if Python supports that encoding, it will work. "unicode" is not an encoding; "utf-8" and "ucs-2" are. Regards, Martin From calvin at xmission.com Tue Sep 3 19:01:17 2002 From: calvin at xmission.com (calvin) Date: 3 Sep 2002 16:01:17 -0700 Subject: Mac os X 10.2 readline Message-ID: <7bc40a7a.0209031501.77819c51@posting.google.com> Readline is not built in the default python 2.2 installed with Mac os X 10.2 Is there an easy way to rebuild it from /usr/lib/python2.2/config ? Or do I have to download the source and rebuild it, yet again? thanks -calvin From shalehperry at attbi.com Fri Sep 6 18:08:29 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 6 Sep 2002 15:08:29 -0700 Subject: Larry Wall's comment on python... In-Reply-To: <200209062206.g86M6UVm092251@mail.hcsmail.com> References: <200209062206.g86M6UVm092251@mail.hcsmail.com> Message-ID: <200209061508.29893.shalehperry@attbi.com> On Friday 06 September 2002 15:06, mmaddox at hcsmail.com wrote: > > Having read Wall's comments on Slashdot, I think he is really just mildly > complaining about ridiculously long page-widths in his editor, not really > slashing Python seriously. He's just giving some props to his own baby at > the expense of another. (He had to say something, right?) You must agree > that Python can lead you to horizontal scrolling in your editor - the bane > of user interface design. > that was the original poster's point. When you start side scrolling it is time to refactor. I find that I write python in much the same physical style as I wrote in C so this has always been how I approached coding. However not everyone has. From max at alcyone.com Sat Sep 14 18:16:16 2002 From: max at alcyone.com (Erik Max Francis) Date: Sat, 14 Sep 2002 15:16:16 -0700 Subject: newbie-question: abstract classes References: <3D839852.2060405@snafu.de> Message-ID: <3D83B530.100873B6@alcyone.com> "T. Kaufmann" wrote: > I want to create an abstract class but it doesn't work. > What' s wrong here? > > class Abstract: > > def __init__(self): return As others have pointed out, it's strange to have an explicit return statement in .__init__. Better would be to use pass when the .__init__ method is truly empty; otherwise it's not necessary. > class Concrete: You don't say how it doesn't work, but one obvious issue here is that Concrete doesn't derive from Abstract. This should read: class Concrete(Abstract): ... An idiom I use for abstract classes is to have its .__init__ method check to make sure that it truly is something other than the base class. class Abstract: def __init__(self): if self.__class__ is Abstract: raise NotImplementedError def method(self): raise NotImplementedError class Concrete(Abstract): def __init__(self): Abstract.__init__(self) def method(self): print "in Concrete.method" Now even trying to create an instance of the Abstract class will result in an exception. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ A man that studieth revenge keeps his own wounds green. \__/ Francis Bacon Sade Deluxe / http://www.sadedeluxe.com/ The ultimate Sade encyclopedia. From fb at frank-buss.de Sun Sep 1 04:57:42 2002 From: fb at frank-buss.de (Frank Buss) Date: Sun, 1 Sep 2002 08:57:42 +0000 (UTC) Subject: Crossword generator References: Message-ID: Tim Roberts wrote: > These are only pseudo-crosswords. Like most automatic crossword > generators, it doesn't worry about symmetry, and it only crosses a few > words here and there. > > Creating a challenging, interesting, and legitimate crossword puzzle > is very, very difficult. Few humans can do it well, and it will be a > while yet before they can describe their own algorithms in such a way > that it can be automated. I don't think so. Perhaps there are no program in Python, but here is an example for a program, which looks like it produces crossword puzzles with symmetry and lots of words crossing, and really fast online as a CGI script: http://www.wordfit.com/dlframe.html -- Frank Bu?, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From martin at v.loewis.de Wed Sep 11 18:43:13 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 12 Sep 2002 00:43:13 +0200 Subject: SuSE 7.3 Yast2-able Python 2.2.1? References: Message-ID: "Robert Oschler" writes: > I have the feeling that the lack of yast2's help, especially when it comes > to SuSEConfig, is somehow causing other apps not to be able to find the > version of OpenSLL that definitely _is_ installed on my system (0.9.6) If you can't satisfy the dependencies, you can try installing building the source RPM. I'd recommend to update to SuSE 8.0, which comes with Python 2.2 Regards, Martin From aleax at aleax.it Sun Sep 15 03:33:50 2002 From: aleax at aleax.it (Alex Martelli) Date: Sun, 15 Sep 2002 07:33:50 GMT Subject: two or more whitespace regular expression? References: Message-ID: eugene kim wrote: > i used this.. > > words = string.split(line, '['+string.whitespace > +']'+'['string.whitespace+']+') > > which didn't work.. The split method of a string (and the old split function in module string, which internally just invokes the split method) takes a string, not a regular expression. To use regular expressions, you must import re first. Then, for example: import re twoormorewhites = re.compile(r'\s\s+') words = twoormorewhites.split(line) Alex From awinston at scn.org Mon Sep 9 00:59:18 2002 From: awinston at scn.org (Alan Winston) Date: Sun, 8 Sep 2002 21:59:18 -0700 Subject: Pysol Solitaire for Windows wanted References: <2MPe9.47925$Jo.5395@rwcrnsc53> Message-ID: "Alan Winston" wrote in message news:alh591$sqa$1 at brokaw.wa.com... > [From rec.games.playing-cards -- crossposted to comp.lang.python] > > PySol requires Python because it is a Python program (hence the "Py" in > "PySol") and Python is an interpreted language. > > I have done the Google exercise several times over recent months, and have > never gotten a working Windows installable, only the pyc files, which > briefly open a Python window, display some messages (presumably errors) then > close again before I can read the messages. > > It hasn't been quite a compelling enough problem for me to have resolved it, > since I have assumed that if I plunge in, the Windows install package will > show up almost simultaneously with completion. but I would be rather > interested in having the software working. > > The PySol card images are gorgeous, and I consider having the working > software worth having just to play with them, although my computer gameplay > is almost exclusively PalmOS. > > -- > Alan Winston > Seattle > > > > "Tom Sloper" wrote in message > news:2MPe9.47925$Jo.5395 at rwcrnsc53... > > > > "PORK SODA" wrote... > > > I only seem to be able to find the macOS version at the moment. > > > > > > Go to google.com and for your keyword search string type "pysol windows > > download" - you will find several download sites. Looks like you may also > > need to download some other software called python for some reason. > > > > > > -- > > Tom Sloper - Game Designer, Producer, Consultant, Author, Speaker. > > Sloperama Productions. Services for game developers and publishers; > "Making > > Games Fun, And Getting Them Done." http://www.sloperama.com/business.html. > > 21 web pages of helpful free information and bulletin boards for game > > industry aspirants; a new article every month. > > http://www.sloperama.com/advice.html. > > The Maj Exchange. Over 100 web pages of free information and bulletin > boards > > about the games of mah-jongg and hanafuda. > > http://www.sloperama.com/majexchange/ > > Los Angeles, CA 90066, USA. > > Tel: (310) 915-9945, Fax: (310) 745-0925, Cell: (310) DIG-SURF > > tomster at sloperama.com > > > > > > From wweexxsseessssaa at telusplanet.net Sun Sep 29 15:18:30 2002 From: wweexxsseessssaa at telusplanet.net (John Hall) Date: Sun, 29 Sep 2002 19:18:30 GMT Subject: Why does QT Windows need Visual Studio? Message-ID: <3ljepusnje8iuca90im2r9vceja5tfc5l7@4ax.com> I was about to download the Windows non-commercial version of QT, but noticed that it requires MS Visual Studio, so didn't. This requirement surprises me - is there a way around that? I have the Visual Studio CDs and key, but can't install it. I was wanting to get away from Visual Basic etc for all the usual reasons, but after a lot of thrashing about trying other tools, decided I would try VB just once more for a small project. Began the install, but it hung. Now I can't use VB because it's not installed, though it appears on the start menu. I can't re-install it because it IS installed (or perhaps because it's NOT installed - my mind turned to mush about then). I can't remove it because it's Not installed. I don't want to reinstall Win 2000 Pro from scratch just to play with something that is obsolescent. I'm working on an app in Rekall (Windows beta) but need to step outside the main-stream Rekall stuff for a small but complex portion. This will be coded in Python & QT (like Rekall itself), but I thought I should work on that completely outside of Rekall initially, and integrate if when (or if) it works. -- John W Hall Calgary, Alberta, Canada. "Helping People Prosper in the Information Age" From agenkin at cdf.toronto.edu Wed Sep 4 00:17:05 2002 From: agenkin at cdf.toronto.edu (Arcady Genkin) Date: Wed, 4 Sep 2002 04:17:05 GMT Subject: MD4 and DES for unicode strings (samba passwd file manipulation) Message-ID: I'd like to manipulate on Samba's password file from Python in order to set/change samba passwords. Samba stores the password encrypted two ways: with DES algorithm, and hashed with MD4[1]. I found and installed 'pycrypto' module[2], which provides the above algorithms. And yet I can't create the right crypted strings: >>> from Crypto.Hash import MD4 >>> >>> m = MD4.new() >>> m.update( u'111222333' ) >>> m.hexdigest().upper() 'A672E5EDFDAD90A15228E0AEC2AA9161' >>> # SAMBA-encoded password "111222333": >>> samba 'B66B458E27BD714F99A05EE3C479FBF1' Perhaps the problem lies with Unicode encoding? Samba's man page (see the link below) says that the string is obtained by taking MD4 hash on the password, represented as a string of 16-bit little-endian unicode characters. Any other ideas? Any help greatly appreciated. Footnotes: [1] http://www.samba.org/samba/docs/man/smbpasswd.5.html [2] http://www.amk.ca/python/code/crypto.html -- Arcady Genkin : CDF sysadmin : http://cdf.toronto.edu/~agenkin/contact.html guilt is the cause of more disauders than history's most obscene marorders (E.E. Cummings) From marklists at mceahern.com Mon Sep 23 22:47:53 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 23 Sep 2002 21:47:53 -0500 Subject: confusion about opening files In-Reply-To: Message-ID: [I wrote] > This is a FAQ. You should probably find the Python FAQ and read > it. Short story: Don't use 'from x import *' unless you know > what you're doing. I should have read the post I was replying to more carefully. I saw the "integer required" error and didn't notice that the OP was using os.open. So the 'from x import *' was a red herring. As Erik Max Francis pointed out, the OP should use open instead of os.open. My apologies. Cheers, // mark - From a_salnikov at yahoo.com Wed Sep 4 22:47:57 2002 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Wed, 4 Sep 2002 19:47:57 -0700 Subject: Why read-only nested scopes? References: Message-ID: "Gon?alo Rodrigues" wrote in message news:m7ncnugbkm0qghf66qcub6e37b64fesdkq at 4ax.com... > On 04 Sep 2002 20:38:30 +0200, loewis at informatik.hu-berlin.de (Martin v. > L?wis) wrote: > > >Gon?alo Rodrigues writes: > > > >> >Gon?alo Rodrigues writes: > >> > > >> >> So why hasn't this been extended when nested scopes were introduced, > >> >> e.g. by reusing the global directive or some other one? > >> > > >> >I think the main reason is that nobody could propose an acceptable > >> >syntax. Reusing the global directive does not work. > >> > >> Can you explain why it does not work? > > > >Consider > > > >x = 1 > > > >def foo(): > > x = 2 > > def bar(): > > x = 3 > > def baz(): > > global x > > x = 4 > > > >If you invoke baz(), which of the variables is changed? How do you > >denote that you want to change the others? > > I think that crawling up the scope hierarchy and stopping at the first x > that one finds (in the above case, the one defined in bar) is a sensible > solution. This solution would have one big drawback. Suppose you wrote one day def foo(): x = 2 def bar(): y = 3 def baz(): global x x = 4 # intention here is to change x in foo() and then few days later you add x to bar(): def foo(): x = 2 def bar(): x = 3 # added code y = 3 def baz(): global x x = 4 # intention here is to change x in foo() and suddenly it stopped working. You go into debugger, spend couple of hours and then "suddenly" realize why it should not be this way :) Andy. From henrik.motakef at web.de Sun Sep 15 14:25:05 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 15 Sep 2002 20:25:05 +0200 Subject: Will xml.dom work with HTML docs? References: <877khntzvt.fsf@pokey.henrik-motakef.de> Message-ID: <871y7vnm9q.fsf@pokey.henrik-motakef.de> loewis at informatik.hu-berlin.de (Martin v. L?wis) writes: > Alternatively, see PyXML. It parses an HTML document into a DOM > tree. It does so by knowing the HTML DTD, ie. it silently inserts > missing closing tags whereever needed. Does it do so by using an actual DTD, or is HTML-specific knowledge hardcoded in it? I.e. could this feature be used with other document types? Regards Henrik From tebeka at cs.bgu.ac.il Wed Sep 25 04:26:37 2002 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 25 Sep 2002 01:26:37 -0700 Subject: Removing all occurences of a character from a string. References: Message-ID: <33803989.0209250026.719df7b4@posting.google.com> Hello Sean, > I have a string, say "'Hello World'", where Hello World is in single > quotes(i.e., 'Hello World'). How can I remove the single quotes so that > "'Hello World'" becomes "Hello World"? import re re.sub("'", "", "'Hello World'") HTH. Miki From phr-n2002b at NOSPAMnightsong.com Thu Sep 19 04:02:33 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 19 Sep 2002 01:02:33 -0700 Subject: shared mem & semaphores module References: Message-ID: <7xr8fqquee.fsf@ruckus.brouhaha.com> Alex Martelli writes: > Thomas Guettler wrote: > ... > > AFAIK there is no module for shared memory. > > mmap comes reasonably close. mmap has no provision at all for semaphores. Try: http://gigue.peabody.jhu.edu/~mdboom/omi/source/shm_source/shm.html I wish the standard library would include this. From shifflett at nps.navy.mil Tue Sep 17 14:24:16 2002 From: shifflett at nps.navy.mil (D. Shifflett) Date: 17 Sep 2002 11:24:16 -0700 Subject: Signals for GtkEntry widgets References: <6qqg9.509135$Aw4.21217664@bin2.nnrp.aus1.giganews.com> Message-ID: I have found that the 'activate' event/signal occurs when the Enter key is pressed in a GtkEntry widget. Here is a snippet: # field for text from user usertext = GtkEntry() usertext.connect("activate", userinput) Thanks for your help David Shifflett "Alistair Thomas" wrote in message news:<6qqg9.509135$Aw4.21217664 at bin2.nnrp.aus1.giganews.com>... > In article , "David > Shifflett" wrote: > > > I am trying to find which signal is emitted when the user presses Enter > > while in a GtkEntry widget. > > The signal is key_press_event. Which returns a GdkEvent object. The > keyval attribute tells you which key was pressed. > > I use Glade and my sample code is based on my own module which uses libglade, > hope this helps: > > import gtk, GDK > > # My own module based on libglade: > import window > > class text_entry ( window.open ): > > def __init__ ( self, title = 'Enter text:', text = '' ): > window.open.__init__ ( self, 'text_entry' ) > self.add_handlers ( { 'on_key_press' : self.key_press, > 'closed' : self.closed } ) > self.get_widget ( 'text_entry' ).set_title ( title ) > self.modified = 0 > self.text = text > a = self.get_widget ( 'text' ) > a.set_text ( text ) > a.grab_focus () > gtk.mainloop () > > def key_press ( self, widget = None, event = None ): > if event.keyval in [GDK.Return, GDK.KP_Enter] : > self.text = widget.get_text () > self.modified = 1 > self.close () > gtk.mainquit () > > def closed ( self, widget = None ): > gtk.mainquit () From grabiller at 3dvf.net Mon Sep 30 03:50:28 2002 From: grabiller at 3dvf.net (Guy Rabiller) Date: Mon, 30 Sep 2002 09:50:28 +0200 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <874rc8d9c9.fsf@nospam.eml.cc> <3d976fbc$0$23666$91cee783@newsreader02.highway.telekom.at> <8428na.7vj.ln@ix.netcom.com> <3d979184$0$20332$79c14f64@nan-newsreader-03.noos.net> Message-ID: <3d980247$0$23236$79c14f64@nan-newsreader-03.noos.net> you are right, thx for correcting me. I meant it works on w2k console etc.. -- guy rabiller 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net "Dennis Reinhardt" wrote in message news:KAOl9.1635$vX6.52299899 at newssvr21.news.prodigy.com... > > > python -v script.py 2>output.txt > > yes it works on MS-DOS too. > > Stderr redirect works as shown on Windows 2000 (which is not DOS!), but does > not work for Windows 98 and earlier. > > -- > > Dennis Reinhardt > > http://www.dair.com > > From bokr at oz.net Tue Sep 3 13:49:59 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Sep 2002 17:49:59 GMT Subject: Design question.... parent/child class References: <3d74b021$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: On Tue, 3 Sep 2002 14:56:21 +0200, "Gumuz" wrote: >hi all, > >i have a SessionManager class, which contains a list of Session >objects(instantiated from a Session class). I have a design problem. > >Each session object has a small 'queue' of messages for the specific >session. How can a session send a message to another session without having >some kind of parent-reference to the SessionManager object? > >i am a bit puzzled, or is this parent-reference not such a bad idea after >all? > Seems like the Session class is in a good position to keep track of the list of session objects instantiated from it. I.e., the __init__ method could add sessions to a directory or list maintained as a class variable (a variable associated with the class, not each instance, but accessible from all instances (and via the class name unless you prevent it)). If you gave names or id numbers to sessions when they were created, you could then access one session from another by name. E.g., (I'm not recommending this verbatim. It's just a quick example to give ideas. Maybe you don't need a separate SessionManager class, depending on what you really want to do and how you want to factor things. >>> class Session: ... sessions = {} ... def __init__(self, name, *etc): ... if name in self.sessions: ... raise KeyError,'Session name "%s" already used.' % name ... self.name = name ... self.sessions[name] = self ... self.etc = etc ... self.msg_queue=[] ... def accept_msg(self, msg): ... print 'I am "%s," and I accepted message "%s."' % (self.name, msg) ... def send_msg(self, dest, msg): ... print 'I am "%s," sending "%s" message "%s"' % (self.name, dest, msg) ... self.sessions[dest].accept_msg(msg) ... >>> s1 = Session('one', 1,2,'stuff') >>> s2 = Session('two') >>> s2.send_msg('one','Hi from instance s2') I am "two," sending "one" message "Hi from instance s2" I am "one," and I accepted message "Hi from instance s2." >>> s3 = Session('two') Traceback (most recent call last): File "", line 1, in ? File "", line 5, in __init__ KeyError: Session name "two" already used. Note that the s1 and s2 variables weren't really necessary to access the sessions, since they were recorded by name in the session directory: >>> Session.sessions['one'].send_msg('two','Hi from session "one"') I am "one," sending "two" message "Hi from session "one"" I am "two," and I accepted message "Hi from session "one"." >>> Session('three') <__main__.Session instance at 0x007D5B70> >>> Session.sessions['two'].send_msg('three','Hi from 2') I am "two," sending "three" message "Hi from 2" I am "three," and I accepted message "Hi from 2." You could define class methods to implement various session management functions, so you could write e.g. Session.status() and get back or print a report with status for each session, etc., etc. The instance data is also available, of course: >>> vars(s1) {'etc': (1, 2, 'stuff'), 'name': 'one', 'msg_queue': []} >>> vars(s2) {'etc': (), 'name': 'two', 'msg_queue': []} >>> vars(Session.sessions['three']) {'etc': (), 'name': 'three', 'msg_queue': []} and thus as attributes, e.g., >>> s1.etc (1, 2, 'stuff') >>> s2.etc () >>> Session.sessions['one'].etc (1, 2, 'stuff') >>> Session.sessions['two'].etc () Regards, Bengt Richter From duncan at NOSPAMrcp.co.uk Fri Sep 6 11:01:31 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 6 Sep 2002 15:01:31 +0000 (UTC) Subject: Difference between static method and a function as a class at tribute? References: Message-ID: sismex01 at hebmex.com wrote in news:mailman.1031321469.8366.python- list at python.org: > Any "plain" executable found as an attribute of a class > object, upon creating an instance of that class, is bound > to the instance as a method. If not, then calling > "inst.testmethod()" should display an empty tuple. That isn't actually what happens. An unbound or bound method is created from the function when you actually reference it, not when you create an instance of the class. A good way to see this is: >>> class C: pass >>> def f(x): pass >>> C.method = f >>> inst = C() >>> p = inst.method >>> q = inst.method >>> print p > >>> print q > >>> print id(p), id(q) 9472384 9252640 >>> Each access of inst.method actually gets a *different* bound method. >>> r = C.method >>> s = C.method >>> print id(r), id(s) 9252512 9222064 The unbound methods are also created when you access them. So again you get a different one each time. > I suspect that staticmethod(func) and classmethod(func) > wrap the function in a proxy which first extracts some > info from the actuall call (say, the instance's class) > and pass *whose* arguments to the real function. As of Python 2.2, when you try to get access an object which is stored in the class (not in the instance), the object's __get__ method is called. In the case of a function, its __get__ method creates a bound or unbound method as appropriate. staticmethod and class method wrap the function in an object with a different __get__ method: >>> f.__get__(None, C) >>> f.__get__(inst, C) > staticmethod's __get__ simply returns the original function: >>> staticmethod(f).__get__(None, C) >>> staticmethod(f).__get__(inst, C) classmethod's __get__ creates a method bound on the type of C instead of on C: >>> classmethod(f).__get__(None, C) > >>> classmethod(f).__get__(inst, C) > -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From bloke at ii.net Wed Sep 18 07:51:16 2002 From: bloke at ii.net (Rob Hall) Date: Wed, 18 Sep 2002 19:51:16 +0800 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <6_Ph9.479711$q53.16315681@twister.austin.rr.com> Message-ID: <3d8868b1$0$28683@echo-01.iinet.net.au> > Matter of taste, really... I do prefer Tkinter, because I find it far > simpler than other GUI toolkits. But then, I've been into Tk for some years > now, and maybe I'm too used to it. > Yes I agree. It is a matter of taste to some extent. I evaluated both, coming from a position of not knowing either, and wx seemed much simpler to me. Also, PythonCardPrototype is an excellent system for using wx. It puts a lot of the hard work in a separate file, letting you concentrate more on the application logic. > The first time I've looked at wxWindows and seen what's needed to open a > simple window, it just made me run away screaming ;-). I did that with tkinter. I ran, and ran. Then I found wx. I thought it wasn't so bad. Then when I looked at tk again, it didn't seem too bad either. I settled on wx for the following reasons... - I needed to settle on something, and pretty soon - wx has a native look and feel - wx is fast - compiled C++, whereas tkinter is a script. I found it to be almost unacceptably slow in some instances. - PythonCardPrototype would simplify things even further. Rob From peter at engcorp.com Wed Sep 18 23:14:25 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Sep 2002 23:14:25 -0400 Subject: Minimal debug/rep functionality References: Message-ID: <3d894106@news.sentex.net> Mark wrote: > Hello all, > > In a nutshell, what I'd like to do is develop a utility that would print out > every line in a python program as the program executes (I may even just > want to print line numbers). I can see hints of how to do this in pdb (and > more directly in the underlying bdb class) and also in the code module. > > So, > > 1) Should I try and inherit a class and override some methods or should I > just pull out the relevant code and hand spin a small interpreter. > > 2) Anyone have a 20 liner solution for this? Sorry, I couldn't find a solution that was larger than six lines: >>> def trace(frame, event, arg): ... if event == 'line': ... print '%s: %s' % (frame.f_code.co_filename, frame.f_lineno) ... return trace ... >>> import sys >>> sys.settrace(trace) Well, if you want to print the actual line of source you could probably stretch it out to eight or ten lines... although I think you need only one more line for the simplest approach. ;-) -Peter From gerhard.haering at gmx.de Sat Sep 21 16:12:21 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: Sat, 21 Sep 2002 22:12:21 +0200 Subject: mySQL and Python 2.2 In-Reply-To: <000801c2619d$64c3aba0$f8ffa8c0@lindstrom> References: <000801c2619d$64c3aba0$f8ffa8c0@lindstrom> Message-ID: <20020921201221.GA3576@gargamel.ghaering.test> * Greg & Janet LINDSTROM [2002-09-21 13:33 -0500]: > Hello- > I am trying to convert from gadfly to mySQL for my database needs on > my Windows 98 box. I have installed mySQL and it works (I have > created my tables and can manipulate them manually), and have > downloaded mySQL-python-0.9.1, but when I python setup.py build, I > get an error about cl.exe not existing (and, sure enough, it > doesn't :-). At http://sourceforge.net/project/showfiles.php?group_id=22307 download and install MySQL-python-0.9.1.win32-py2.2.exe instead. I haven't gotten around to building 0.9.2, yet. > I'm running Windows 98 with Activestate Python2.2. Any help you > could supply (including code snippets of how to get connected to > MySQL once I get it running) would be appreciated. Look in the examples and docs directory of the source distribution that you downloaded. You should be able to find what you're looking for there. -- Gerhard From a-steinhoff at web.de Sat Sep 21 06:59:41 2002 From: a-steinhoff at web.de (Armin Steinhoff) Date: 21 Sep 2002 03:59:41 -0700 Subject: PyQt setup on Linux Mandrake 8.2 References: <3D8B4898.20808@nospam.attbi.com> Message-ID: dwelch wrote in message news:<3D8B4898.20808 at nospam.attbi.com>... > I would like to setup PyQt 3.4 on my Mandrake 8.2 box. I am having > difficulty, and I am worried that if I do the wrong thing, KDE will go > belly-up on me since it is Qt based. > > First, question is: why isn't QTDIR defined by default? PyQt works with Qt2.x.x and Qt 3.x.x ... so YOU have to choose the correct directory. >Is QTDIR a > runtime setting or a development setting? Both .. > So I set QTDIR to /usr/lib/qt2 (that seems to be where the libqt2 RPMs > files are). Next question is: Since I have libqt2 already on my system, > how do I add the Qt development pieces without screwing up Qt/KDE? Is > /usr/lib/qt2 even the correct location? Yes ... if you want to use only the latest version of Qt 2.x.x > When I run SIP 3.4 build.py, it complains about tmake not being > available. Is tmake included with Qt2 development files? It's available at the Trolltech homepage or its mirrors. > SIP doesn't > seem to have any docs, so I'm not sure how to proceed. Nomally you haven't to care about SIP .. > Also, my RPM manager says that I have libqt2-devel (2.3.1-29mdk) > installed. No tmake listed in the files, though. And, PyQt-devel > (2.5-1mdk) is also listed as installed, but there aren't any .py files > included, only .sip files (I found this curious). Corious ... there must be examples included. I would suggest to dowload the latest version of Qt from the Trolltech homepage, just for a simple and clean recompilation. And do the same with SIP and PyQt from the Riverbank homepage ... It seems to be better to forget that outdated stuff provided by the Mandrake distribution ... Armin > > Installing software on Linux makes me feel like such an idiot! > > Any help or pointers would be much appreciated. > > Don From kkuroda at crl.ucsd.edu Fri Sep 20 02:00:26 2002 From: kkuroda at crl.ucsd.edu (Kow Kuroda) Date: Thu, 19 Sep 2002 23:00:26 -0700 Subject: Larry Wall's comment on python... Message-ID: <7E6A03F4-CC5E-11D6-B1E5-00050287C0A6@crl.ucsd.edu> On Thursday, September 19, 2002, at 09:32 PM, Courageous wrote: > >> Well, Python code may look awkward --- if not awk-like --- >> if you don't know how to customize the tab width in your >> editor of choice. > > Well, there's your problem already. One should use spaces > and not tabs in Python code. Otherwise, any python file where > tabs and spaces are mixed is also a choice of which indentation > level other viewers of the code MUST use in their editors. That's > heinous. Well, that's not my job; it's the job of tabnanny.py. Kow From loewis at informatik.hu-berlin.de Tue Sep 24 14:06:00 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 24 Sep 2002 20:06:00 +0200 Subject: Solaris 64 bit compilation References: Message-ID: phoebe_1 at att.net (Holden Caulfield) writes: > > > "./Include/pyport.h", line 480: #error: "LONG_BIT definition appears > > > wrong for platform (bad gcc/glibc config?)." > > > > So what value has SIZEOF_LONG in pyconfig.h? [...] > To answer your questions: > - pyconfig.h does say 8 as SIZEOF_LONG That raises the question then why the error in pyport.h is produced. LONG_BIT comes from limits.h, and, if _LP64 is defined, is 64. So I'm still uncertain what you did to provoke this error. > - 'curses' modules does not compile. > - 'dbm' modules compiles fine but core dumps during test. > So, I disabled these modules in 'setup.py' and built it and ran the > make test. curses fails for me as well, since it finds a 32-bit ncurses installation; dbm also core dumps here. > test test_time failed -- Traceback (most recent call last): > File "./Lib/test/test_time.py", line 46, in test_mktime > time.mktime, (999999, 999999, 999999, 999999, > File "/apps/python/build/Python-2.2.1/Lib/unittest.py", line 279, in > failUnlessRaises > raise self.failureException, excName > AssertionError: OverflowError This is a known bug (#460357), which has been fixed in CVS. > 2) > test_gettext > test test_gettext crashed -- exceptions.OSError: [Errno 20] Not a > directory: 'xx/LC_MESSAGES/gettext.mo' I believe this also has been fixed in CVS. > Are there any plans to support 64-bit python executable/module on > solaris platforms for future versions? Building python in 64-bit mode on Solaris works already. Some modules may still not work; patches are welcome. > Is anyone even interested in the configure.in patches? I don't really see a need, since it works fine without the patches. Regards, Martin From fgeiger at datec.at Wed Sep 4 14:22:20 2002 From: fgeiger at datec.at (F. GEIGER) Date: Wed, 4 Sep 2002 20:22:20 +0200 Subject: Does BlackAdder really suck? References: Message-ID: "Gerhard H?ring" schrieb im Newsbeitrag news:slrnanci6i.1s8.gerhard.haering at haering.opus-gmbh.net... > I just checked out the BlackAdder demo and was quite disappointed. > BlackAdder crashed my NT box, when I ran it the 1st time. Never fired it up again... > I expected that this is a tight integration of Python and PyQt. But it > looks like it's just Qt Designer embedded in the IDE, while still having to > run pyuic manually. I don't know if at least the debugger is any good, > because the demo was quite limited. > > Is there any usable commercial IDE for GUI design? BlackAdder and > PythonWare Pro seem to be the only candidates (yes, I did check out Boa). Did you have a look at wxDesigner? Regards Franz GEIGER From gerhard.haering at gmx.de Tue Sep 24 16:05:15 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 24 Sep 2002 20:05:15 GMT Subject: Using internet modules to download files References: <3ab719f7.0209241142.1bf5987@posting.google.com> Message-ID: Stuart wrote in comp.lang.python: > I have a slight problem. The college which I attend has broadband > access for everyone, but unfortunately insists upon placing a firewall > between the pupils and downloads, therefore this fast connection is > wasted upon retrieving HTML files. So the "firewall" restricts you to downloading HTML documents only? Are you not able to view any images in a browser? Can you not download any .exe, .zip, .tgz files? > I merely want to use the broadband to download a few more python > libraries, such as win32all, as my home pc doesn't have internet > access. > > I have been experimenting with Python's internet protocols, in > particular with trying to retreive files while bypassing the firewall. > I am not sure, however, which modules to use (i am a relative python > neophyte). I first tried with urllib, but that unforunately merely > routes you throught the webbrowser, which of course, promptly blocks > any attempt. No, urllib doesn't use any webbrowser. It may be that you'll have to instruct it to use a proxy server (and it sounds like your "firewall" has one). Did you try urllib.urlretrieve, yet? Using it like this: urllib.urlretrieve("http://python.org/", "pydotorg.html") will download the http://python.org entry page as the file pydotorg.html. At least here ;-) > Are then any modules which will bypass the > browser/firewall, and allow you to download a file directly through > the script? Any advice (especially samples of code) would be greatly > appreciated. See the above one-liner. -- Gerhard From pieroul at attglobal.net Mon Sep 30 23:30:42 2002 From: pieroul at attglobal.net (Pierre Rouleau) Date: Mon, 30 Sep 2002 23:30:42 -0400 Subject: Is there a docutils / reStructuredText system for C++ source code available? References: <3D98D9D9.8000009@attglobal.net> Message-ID: <3D9916E2.5030006@attglobal.net> David Abrahams wrote: > "Pierre Rouleau" wrote in message > news:3D98D9D9.8000009 at attglobal.net... > >>I have been using docutil and reStructuredText for Python code and it >>works great. Pydoc does a superb job of helping in setting up an >>internal web site that provides documentation for our Python code, let >>alone the ability to run doctest test and show auto testing of python >>documentation on line! >> >>That works great for our Python code. Now i want to do the same thing >>for our C++ code. Since Python has been partly implemented in C / C++ >>i tough there might already exist some tools for parsing C++ and some >>comments (given some formatting conventions) and generate the same kind >>of output the html tool of docutil does. >> >>Does any one know any thing that resembles that? > > > See http://synopsis.sf.net > > -- > ----------------------------------------------------------- > David Abrahams * Boost Consulting > dave at boost-consulting.com * http://www.boost-consulting.com > > Thanks! I also found another tool called Doxigen at http://www.stack.nl/~dimitri/doxygen/ Anyone has experience with it? -- Pierre Rouleau From pedronis at bluewin.ch Fri Sep 6 11:43:45 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Fri, 6 Sep 2002 17:43:45 +0200 Subject: Python and Jython inconsistencies when encoding strings References: Message-ID: <3d78ce33$1_3@news.bluewin.ch> Martin v. L?wis wrote in message j4ofbbclfp.fsf at informatik.hu-berlin.de... > >>> s > u"\u0153" > > Now, U+0153 is LATIN SMALL LIGATURE OE. It so happens that \x9c (what > the terminal sends) is U+0153 in CP 1252 (which is the ANSI code page > on your Windows installation). This might be a bug in Java, which > assumes that bytes sent by the terminal are in the ANSI code page, > when they are really in the OEM code page. no it's more the Jython parser that does that, things can be fixed running Jython as jython -Dpython.console.encoding=cp850 on the other hand output seems buggy for: print s.encode("cp850") [I have reported that on our SF bug tracker] > > Does anybody know what is causing this inconsistency? Is there any way to > > avoid it? > > Yes. Don't use the console. sticking to ascii there can avoid some troubles :). regards From loewis at informatik.hu-berlin.de Wed Sep 4 12:47:34 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 04 Sep 2002 18:47:34 +0200 Subject: Why read-only nested scopes? References: Message-ID: Gon?alo Rodrigues writes: > So why hasn't this been extended when nested scopes were introduced, > e.g. by reusing the global directive or some other one? I think the main reason is that nobody could propose an acceptable syntax. Reusing the global directive does not work. Regards, Martin From b.maryniuk at forbis.lt Tue Sep 10 09:16:48 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Tue, 10 Sep 2002 15:16:48 +0200 Subject: UNIX processes In-Reply-To: <20020910083924.A4265@phy.duke.edu> References: <200209101233.05796.b.maryniuk@forbis.lt> <20020910083924.A4265@phy.duke.edu> Message-ID: <200209101516.48432.b.maryniuk@forbis.lt> On Tuesday 10 September 2002 14:39, Michael Stenner wrote: > 1) use the program "ps", which does the right thing for any given > os/kernel and presents a fairly standardized report, or Yes. Especially, if it is not for Linux only. > 2) pick the os(s) that you care about, and write your own code to do > it directly. On linux, that can be done pretty nicely through the > /proc/ filesystem ("man proc"). Yes, I know this. Seems that no more way to do. :( -- Regards, Bogdan Apologies for taking up the bandwidth with the apology. Anything else I can apologise for ...... er no can't think of anything, sorry about that. Andy Hunt (Member of British Olympic Apology Squad) From fredrik at pythonware.com Wed Sep 4 03:14:08 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Sep 2002 07:14:08 GMT Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: <4pid9.5883$e5.1033514@newsb.telia.net> Bengt Richter wrote: > I agree about new syntax, but I wouldn't mind having a re.help(regexp) function > for interactive use that would just explain in 'English' what the regexp expression > stands for. you can ask SRE to dump the internal parse tree to stdout: >>> sre.compile("[a-z]\d*", sre.DEBUG) in range (97, 122) max_repeat 0 65535 in category category_digit turning this into 'English' is left as an exercise etc. From tmohr at s.netic.de Sun Sep 15 00:29:34 2002 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 15 Sep 2002 06:29:34 +0200 Subject: Tkinter in PyRun_SimpleString(char* s) Message-ID: Hi, it doesn't seem to be as easy as i thought to load a script from a C program and execute it, if i import Tkinter, it fails: Traceback (most recent call last): File "", line 31, in ? File "", line 27, in __init__ File "/usr/lib/python2.1/lib-tk/Tkinter.py", line 2249, in __init__ Widget.__init__(self, master, 'frame', cnf, {}, extra) File "/usr/lib/python2.1/lib-tk/Tkinter.py", line 1750, in __init__ BaseWidget._setup(self, master, cnf) File "/usr/lib/python2.1/lib-tk/Tkinter.py", line 1725, in _setup _default_root = Tk() File "/usr/lib/python2.1/lib-tk/Tkinter.py", line 1476, in __init__ baseName = os.path.basename(sys.argv[0]) AttributeError: 'sys' module has no attribute 'argv' The script i try to run is the example from the latest library documentation of Tkinter. The C program looks like this, it is also a slightly changed example. It seems there are some initialisations missing, what do i need to do to set it all up properly? Best regards, Torsten. int main(int argc, char** argv) { // routine to load a file f = slFileLoad("script.py", 0); Py_SetProgramName(argv[0]); Py_Initialize(); PyRun_SimpleString(f->address); Py_Finalize(); return EXIT_SUCCESS; } From tismer at tismer.com Fri Sep 20 09:33:08 2002 From: tismer at tismer.com (Christian Tismer) Date: Fri, 20 Sep 2002 15:33:08 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: <3D8B2394.4000202@tismer.com> Martin v. Loewis wrote: > Christian Tismer writes: > > >>>Academically, I don't think the results are unpredictable, as >>>micro-thread switch occur at predictable points in processing. >> >>Yes, right now, but this will change pretty soon. > > > You mean, tasklet switches will occur at unpredictable times? > > This sounds like a bad idea. Old Stackless had pre-emptive scheduling, and everybody was happy with it. Microthreads were the major application. I need to support this again, but in a much more fine-grained implementation. It is (again) the user's decision whether he allows free scheduling of certain code. Some people love it, some people hate it. I don't care, but support it all. ... >>I have to do rigid locking of every unknown piece of code, until >>somebody explicitly claims some code to be switchable. > > > This, again, sounds terrible. I doubt it will help, and users will > complain. I don't think it makes sense to continue this discussion in a public forum. Let's sit together with a beer at some time, and you will see what I have in mind. I'm not aiming at complaining users. Instead, they will get the same safe default behavior as with the old version, only better. My fault is to provide a flare gun without a locking bolt. Will to whatever it needs to fix this. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From aleax at aleax.it Wed Sep 25 18:04:32 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 22:04:32 GMT Subject: Python Compiling References: <80a8af7d.0209250113.28ae4c72@posting.google.com> Message-ID: Lulu of the Lotus-Eaters wrote: > Alex Martelli wrote previously: > |Or Haskell, www.haskell.org -=- HUGS inteprets it, the Edinburgh > |compiler compiles it. Scheme has _many_ interpreters and compilers > |too. Hey, so does Visual Basic... it's quite the thing these days. > > Wrong Scottish city, I'm afraid. Alex probably means the GLASGOW Perfectly right, and thanks to you and the many others who mailed me about it for catching out my silly mistake:-(. The Edinburgh compiler is for *STANDARD ML*; the Glasgow compiler is for *HASKELL*. Whether I mixed up Scottish cities or major functional programming languages, it was still a silly error to make, and I apologize to Scotland, FP enthusiasts, and the readership at large. Alex From marklists at mceahern.com Thu Sep 12 10:48:20 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 12 Sep 2002 09:48:20 -0500 Subject: Is there a portable way to copy files in Python? In-Reply-To: <3D80A78B.5030206@impathnetworks.com> Message-ID: [Pierre Rouleau] > Subject: Is there a portable way to copy files in Python? Have you tried shutil? // m - From gerhard.haering at opus-gmbh.net Tue Sep 3 12:59:40 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 3 Sep 2002 16:59:40 GMT Subject: Servizi Internet References: <3bl9nu8924gihfj2nlpog874vfm73qqbh9@4ax.com> Message-ID: Ben Jamin wrote: > excuse me but aren't commercial promotion and such things forbidden on > newsgoups? You can't really forbid things, because you have (almost) no means of sanctioning people on usenet. The only means you have is complain to their ISP (abuse@{name_of_ISP}). Wrt. to the post you noticed, it's certainly against netiquette and the charta of this newsgroup to post off-topic commercial spam here. Announcements of Python-related commercial offerings are IMO on topic. -- Gerhard From duncan at NOSPAMrcp.co.uk Mon Sep 16 12:05:37 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 16 Sep 2002 16:05:37 +0000 (UTC) Subject: CFP: UK Python Conferece 2003 Message-ID: *** Call for Participation *** UK Python Conference 2003 April 2-3 2003 Holiday Inn, Oxford The UK Python Conference 2003 is being held in conjunction with the larger ACCU conference. The conference will include two days of papers arranged in 90 minute speaking slots with either one or two tracks. The audience is highly technical and will include experts in many fields of computing, some of whom may know little or nothing about Python. Talks will be welcomed on any aspect of Python, but we are especially interested in the following: - Commercial applications for Python - Cross-language talks Speakers are welcome from the UK or the rest of the world, however our budget for overseas speakers may be limited. To submit a proposal, send an email message to duncan at rcp.co.uk by 2nd October 2003. In your message, please include the following: - Speaker name and affiliation - Contact address - Presentation title - A one paragraph abstract -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From gerhard.haering at gmx.de Wed Sep 18 17:24:25 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: Wed, 18 Sep 2002 23:24:25 +0200 Subject: Python as shared library on Unix In-Reply-To: References: Message-ID: <20020918212425.GA6514@gargamel.ghaering.test> * Rolf Kalbermatter [2002-09-18 22:48 +0200]: > Under Linux I see no option to build a python.so.2.2.1 or similar to link my > application to with the dl* functions. There isn't any except in Python 2.3-CVS and Python's patched from various distributors. Debian's Python builds a shared library, for example. OTOH you don't really need to have a shared library to embed Python. Just link statically against libpython{major}{minor}.a. -- Gerhard From spoermeg at voldelig.com Tue Sep 17 19:43:42 2002 From: spoermeg at voldelig.com (Terje Johan Abrahamsen) Date: Tue, 17 Sep 2002 18:43:42 -0500 Subject: Source code References: <4qLh9.1185$%U1.52435185@newssvr21.news.prodigy.com> Message-ID: "Don Bennett" wrote in message news:4qLh9.1185$%U1.52435185 at newssvr21.news.prodigy.com... > Terje Johan Abrahamsen wrote: > > If I would like to write some code that would not be possible for > others to > > read, after I distribute the program, would Python be suitable? > > Yes. > > > I know that > > there are a few programs like Py2Exe, that creates .exe files. But, I > also > > saw this: > > > > -------------------- > > A zip-compatible archive is built, containing all files from this > > directory as well as your script, and appended to a custom python > > interpreter supplied with py2exe. > > -------------------- > > > > Doesn't sound like it is protected very well. Is there some > alternative to > > Py2Exe that can do the job, or should I look for a compiled language > > instead? > > > Take a look at Tools/freeze.py. > > With this tool, you can compile your python files in to C files, and > then link the C files with the python interpreter to create a > stand-alone executable that represents your program. Thanks... I will check that out... From gerrit.muller at philips.com Mon Sep 23 06:19:56 2002 From: gerrit.muller at philips.com (Gerrit Muller) Date: Mon, 23 Sep 2002 12:19:56 +0200 Subject: How to get memory usage on Windows? References: Message-ID: <3D8EEACC.FBE54A37@philips.com> <...snip...> >> Have a look at \Python22\Lib\site-packages\win32\Lib\win32pdhutil.py, <...snip...> > >I will have to try this at work, on a windows2000 machine. > > That's what I'd do. > > Another option would be using calldll > (see http://www.nightmare.com/software.html). This is more dangerous, > but will most probably work on any win32 system. > The original routine based on win32pdhutil.py works on windows2000! May be I have to try the nightmare route at home :-) thanks Gerrit -- -------------------------------------------------------------------- Gerrit Muller Philips Research Laboratories Eindhoven Building: WDC 2 - 007 Prof. Holstlaan 4 Phone: +31 40 27 45242 5656 AA Eindhoven Fax: +31 40 27 45033 The Netherlands mailto:gerrit.muller at philips.com http://www.extra.research.philips.com/natlab/sysarch/index.html From johnroth at ameritech.net Tue Sep 3 18:20:57 2002 From: johnroth at ameritech.net (John Roth) Date: Tue, 3 Sep 2002 18:20:57 -0400 Subject: Would you like a Snobol pattern matcher? (Re: Making regex suck less) References: <3d725881.345921@news.t-online.de> <3D740DFC.1040009@something.invalid> Message-ID: "Carl Banks" wrote in message news:al30tq$aud$1 at solaris.cc.vt.edu... > John Roth wrote: > > I don't know much about Snobol, unfortunately. > > I think my biggest issue here is that we shouldn't > > reinvent the wheel unless there is a good reason. > > In other words, Larry is taking Perl in a specific > > direction. Assuming we want to make major > > changes to regex, > > I don't think anyone wants to make changes to regular expressions, per > se. I think this discussion is about adding a higher level syntax to > regular expressions, that makes them more readable and versatile, for > cases where that's important. One of the things Perl has right now is the ability to use spaces within regular expressions via a suffix flag. In Perl 6, this will become standard, and will include the ability to include comments! Apocalypse 5 is well worth reading. Larry sets out why he decided to redesign regular expression syntax. Much of the reason was exactly what you specify: it's hard to read, hard to understand, and has picked up lots of cruft over the years. Making regular expressions "more versatile" is a great idea. There's lots of things I'd like to do. However, everything you load onto the poor thing makes it that much more complex, hard to understand, hard to read and errorprone. At some point, the mess has to be redesigned. Since Python's re syntax isn't currently as complex as Perl's (I think) it might not be there yet. > > is there any _good_ reason > > for doing something conceptually different and > > consequently adding to the cacophony? > > I think there is a good reason to have a higher level syntax. It > serves a purpose heretofore unserved: that complex regular expressions > no longer have to be unbearably unreadable. > > I could live without it, though. > > > -- > CARL BANKS > http://www.aerojockey.com From tismer at tismer.com Fri Sep 27 20:45:39 2002 From: tismer at tismer.com (Christian Tismer) Date: Fri, 27 Sep 2002 17:45:39 -0700 Subject: Is Boost Python version 2 ready? References: Message-ID: <3D94FBB3.6060100@tismer.com> David Abrahams wrote: > "Robert Oschler" wrote in message > news:MvZk9.12124$Lg2.3584877 at news2.news.adelphia.net... > > >>Is Boost Python version 2 ready for primetime yet? > > > I'd say so, except for docs. We're not making any interface-breaking changes > at this point, so anything you write will continue to work for some time to > come. I'm finishing the last feature before release as we speak, and > everything's been passing all tests on a wide range of platforms for quite a > while. Docs will be finished over the next week or so. I have been asked whether Boost will be compatible with Stackless (or vice versa:). Who else could answer that better than you? ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From spam at ob_scure.dk Sun Sep 8 03:42:25 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Sun, 08 Sep 2002 09:42:25 +0200 Subject: Using Python to call a DCOM server - "'Class not registered" References: <3D787D95.9000907@ob_scure.dk> <5%ce9.1272$_l1.2960@news-server.bigpond.net.au> <3D7A1359.4010607@ob_scure.dk> Message-ID: <3D7AFF61.7070005@ob_scure.dk> Mark Hammond wrote: > Thomas Jensen wrote: > >> Is it safe to say that "ActiveX DLL" = InprocServer32 and "ActiveX >> EXE" = LocalServer and that I need the later to use DCOM? (I have some >> existing components that I'd rather keep as DLL - don't know why >> really? :-) > > > Yep. InProcServer32 means that the COM object is implemented in a DLL, > and loaded into the calling process. LocalServer means it is an > executable, and loaded into a separate process and IPC used across > boundaries. For DCOM, there is no way the object can be loaded into the > same process, so executable based servers must be used. Ok, I see. Then I guess the LocalServer approach has much more overhead on local calls than InProc32? Searching for "unregister localserver" I found your book "Python Programming on Win32" on O'Reilly :-) If I can find it in Denmark, I think I'll buy it! /Thomas -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From irmen at NOSPAMREMOVETHISxs4all.nl Mon Sep 16 13:18:08 2002 From: irmen at NOSPAMREMOVETHISxs4all.nl (Irmen de Jong) Date: Mon, 16 Sep 2002 19:18:08 +0200 Subject: pyro & parallel processing References: Message-ID: Syver Enstad wrote: > Robin Becker writes: > >>Has anyone used pyro to do symmetric parallel processing. The pyro >>framework is nice with master slave type applications, but the remote >>objects don't seem to be able to message back to their invoker. > > They can, checkout the callback examples in the Pyro distro. Basically > what happens is that you pass a Pyro proxy as a parameter to the a > method on the Pyro object. This is a good way of letting the 'other' Pyro object call methods on one of your 'own' (or 'local') objects. It is a more symmetric way but you have to pass callback object proxies as parameters. The other - fully symmetric - way, is to build some Pyro objects on both sides and register them all with the Name Server. This way everybody can discover the other's objects by themselves. You won't need to pass callback object proxies around. Note that this requires a Pyro server (daemon) on all nodes, but that is no different from the callback object solution. Irmen de Jong PS the Pyro mailing list is usually a better place to ask questions about Pyro, see http://lists.sourceforge.net/lists/listinfo/pyro-core From sonnenbu at informatik.uni-bonn.de Wed Sep 25 16:29:17 2002 From: sonnenbu at informatik.uni-bonn.de (Frank Sonnenburg) Date: Wed, 25 Sep 2002 22:29:17 +0200 Subject: Newbie References Question References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> Message-ID: I forgot the most important part of the example: >>> p=Point(3,4) >>> f=Figure(p) >>> f Figure, def. by (3,4) >>> p.set(99,-5) >>> f Figure, def. by (99,-5) Frank From chris.gonnerman at newcenturycomputers.net Sun Sep 29 22:19:10 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Sun, 29 Sep 2002 21:19:10 -0500 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> Message-ID: <001701c26827$cb21d300$ba01010a@local> ----- Original Message ----- From: "Paul Rubin" > "Chris Gonnerman" writes: > > >>> .70 * .05 > > 0.034999999999999996 > > > > Rounded to two decimals, that's 0.03; but done in proper > > decimal numbers, the answer should be 0.035, rounded to 0.04 > > using either "classic" or "banker's" decimal rounding. > > ... > > So, Bengt, how do I do this right using only floats? I can't. > > I have to have decimal arithmetic to get the right answer. > > How about just adding a small amount before rounding at the end? > > >>> (.70 * .05) + .000000001 > > rounds to the right thing. Cool. Now PROVE that's right in all cases. Like I said, decimal arithmetic is STILL the only choice. Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From martin at v.loewis.de Wed Sep 4 03:21:42 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Sep 2002 09:21:42 +0200 Subject: Makefile.pre.in ?? installing postgresql --with-python References: Message-ID: eugene kim writes: > ./configure --with-python gives me this error (postgresql7.1.3 config) > > configure: error: The Python extension makefile was expected at > `/usr/local/lib/python2.2/config/Makefile.pre.in\' The Makefile.pre.in procedure for building extension modules is not supported anymore. Extension authors should use distutils. If you don't want to write a setup.py for postgresql, you can probably work around this by disabling the relevant section of postgresql's configure.in, and building the extension manually - you should look at their Setup file to find any additional options they want to use for the Python extensions. Regards, Martin From nbecker at fred.net Mon Sep 9 20:53:56 2002 From: nbecker at fred.net (nbecker at fred.net) Date: 09 Sep 2002 20:53:56 -0400 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <4pid9.5883$e5.1033514@newsb.telia.net> Message-ID: IMHO, the thing that I really miss in making regex's understandable, is that you can't include one regexp into another. If you could, it would be much easier to write clear expressions. Flex, for example, allows this. From mertz at gnosis.cx Thu Sep 19 17:10:44 2002 From: mertz at gnosis.cx (David Mertz, Ph.D.) Date: Thu, 19 Sep 2002 17:10:44 -0400 Subject: finding last match in a file Message-ID: |..find the last line which matches a certain experssion. ...Is there |some way to read through the file backwards and simply find first match |starting from the end of the file. I provide one solution in my _Text Processing in Python_ book (forthcoming as dead trees, available now as ASCII). The book itself is at: http://gnosis.cx/TPiP/ In chapter 2, I have a section titled: PROBLEM: Reading a file backwards by record, line, or paragraph I'm sure improvements are possible (it's meant to point to the approach, not necessarily be the final code). But what I do should be pretty efficient (as I mention, for 2.2+, I'd rather use 'yield'). Yours, David... -- ---[ to our friends at TLAs (spread the word) ]-------------------------- Echelon North Korea Nazi cracking spy smuggle Columbia fissionable Stego White Water strategic Clinton Delta Force militia TEMPEST Libya Mossad ---[ Postmodern Enterprises ]-------------------------- From cliechti at gmx.net Sat Sep 7 16:31:25 2002 From: cliechti at gmx.net (Chris Liechti) Date: 7 Sep 2002 22:31:25 +0200 Subject: Simulating "getopt" in functions (newbie) References: Message-ID: Thorsten Kampe wrote in news:aldm7h$1orqou$1 at ID-77524.news.dfncis.de: > Hi, > > I want to simulate a "getopt"-like behaviour within a _function_. This > is to avoid having to define two functions: "function" and > "slightly_different_function". > > If the function was a standalone program, it would work like this > ("v" for "verbose"): > > $ function.py 5 > 1 > > $ function.py -v 5 > The result is: 1 > > I've thought of this to simulate it in a function: > def function(a, b=None): > if b == "v": > print "The result is: 1" > else: > print "1" > >>>> function(5) > 1 > >>>> function(5, "v") > The result is: 1 > > So: what is the "pythonic", "natural" way to do this in Python? your idea is right. i would however vary the details: if you just want to swich something then somthing: def function(a, verbose=0): or you could use the presence of a file object in a param: def function(a, output=None): if output is not None: output.write("The result is:) print "1" and i wouldn't use string parameters directly like you did. i someone makes a typo within that string you wont get errors, but if you use a variable as indirection you get a name error: VEROSE="v" function(23, VEROSE) and using numbers instead of string would be more efficient. chris -- Chris From marklists at mceahern.com Wed Sep 11 18:10:42 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 11 Sep 2002 17:10:42 -0500 Subject: I must be an idiot, please pity me! In-Reply-To: Message-ID: [newbie] > But it doesn't seem to work like that. I don't know about all the mind readers out there, but you really haven't given us any helpful information. Are you getting an error? What are the symptoms of failure? What are you expecting to happen? Why not try to simplify what it is you're trying to do and share *that* code? For instance, the functions in each of your modules--do they take a database connection as a parameter? Have you tried stuffing everything into one module--just to see if it works? Etc. // m - From enoch at setim.org Sat Sep 7 11:17:08 2002 From: enoch at setim.org (Enoch) Date: Sat, 7 Sep 2002 17:17:08 +0200 Subject: untrusted dynamic module: win32api Message-ID: Hi, I'm a Softimage|XSI user, a 3D graphic software that support ActiveX Scripting on win32 platforms. This software integrate a 'NetView', an integrated internet explorer. To be able to communicate between the NetView and XSI I have to create the XSI.Application object. Works fine with VBScript and JScript, however I'm running into a problem trying to make it work with Python. Basicaly I have to include in my html page the following code: But when I load this page into the NetView ( or even in an external brother ) I have this error message: 'ImportError: untrusted dynamic module: win32api' Is there any way to 'force' the import ? Sorry if this has been discussed earlier, I'm relatively new to Python. Tia. Guy. 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net From imbosol at vt.edu Wed Sep 11 15:25:09 2002 From: imbosol at vt.edu (Carl Banks) Date: Wed, 11 Sep 2002 15:25:09 -0400 Subject: function pointer References: Message-ID: Gerhard H?ring wrote: > David Brown wrote: >> Functions are first-order objects (is that the right term?) > > It is. First-class objects. -- CARL BANKS http://www.aerojockey.com From tdelaney at avaya.com Thu Sep 19 19:47:15 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 20 Sep 2002 09:47:15 +1000 Subject: Minimal debug/rep functionality Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > Hmmm... I didn't see any implication that speed was even remotely > a concern for the OP. After all, he did ask to *print* each line > as it executed. What could possibly be slower than that? > (I doubt he would care to deal with the volume of information > generated when using this with a large program anyway... needs > a way to turn it on and off, at least.) Very true - hence my qualification. The speed comes into effect when tracing a long-running process - for example, while using the "standard" two coverage tools (trace.py and coverage.py) performance was unacceptably slow for coverage of some unit tests here (well, once I'd hacked them to actually allow unittest to determine what was a test case ...). > My standard comments about Python speed and Knuth's comments about > premature optimization apply... Oh yeah. Unfortunately, tracing becomes a real bottleneck if done wrongly - I've achieved two orders of magnitude improvement since I first started on this tool - both in performance and memory use. > I'm looking forward to seeing your tool though, Timothy. :) I'd love it to eventually become part of the core - I *expect* I'll be able to release it (but of course, it's up to my employer ...). It's doing everything I want now except for determining exactly which zero-count lines can be safely ignored (comments, multiline expressions). Oh - and I haven't got an actual "trace as you go" mode (which is the topic of this thread ;) but that will be easy to add. And I haven't got any path coverage analysis yet - the data is captured, but no analysis is performed. And it currently does a relatively primitive text-only coverage dump. And ... :) Tim Delaney From observer at NOSPAM.space.pl Thu Sep 5 06:30:13 2002 From: observer at NOSPAM.space.pl (Johann) Date: Thu, 05 Sep 2002 12:30:13 +0200 Subject: urgent: binary driver for MySQL/Windows Message-ID: 1. I am using the latest MySQL ODBC driver. 2. I created ODBC entry in my Windows2K and I can connect to the external database (test connection was OK) 3. I CANNOT connect to the same database using odbc.odbc('mydsn') because it works as ODBC at intranet user not authorized with Windows Server 2000. Shit. I have no idea how to fix it so I tried the same with Perl using DBI and DBD-MySQL and IT WORKS! But.. I wanted to use Python. So, how to make Python work with MySQL? Is there any (other than odbc) way to connection to MySQL? I found in DB-SIG MySQL module. But it is only source, binaries are for Linux. I need windows binary driver for my local Win2K workstation. I tried to compile it with Cygwin, but it failed. :( I am lookin' for MySQL binary driver for Windows2K (for Active Python I am using) -- Johan From howard at eegsoftware.com Wed Sep 4 18:34:08 2002 From: howard at eegsoftware.com (Howard Lightstone) Date: Wed, 04 Sep 2002 22:34:08 GMT Subject: Python parser for cross references Message-ID: I would like to use Source Navigator to (re)examine a largish application. It parses the C, C++,assembly and Python jobs I am working right now and has outputs that *statisfy* the naive QA people who think tables and diagrams are *documentation*. The Python parser for it was written by Thomas Heller (thank you very much). However, it does not emit cross reference information. Of course, I first thought "why not just add one?". I can see why Mr. Heller did not. A cross reference parser has to track scope....and determine function calls within argument lists.....and track just 'name' references which are passed around...and on and on. Is there a (C) parser for Python around which does a "just-good-enough" parsing job to be adapted for this? I think it just needs the scope (name) and enough logic to recognize what kind of token it has found. Of course, the gui guts of SN are written in Tix, Tcl, and ITcl .... oh well, back to those again. Thanks Howard Lightstone From aleax at aleax.it Thu Sep 19 03:42:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 07:42:37 GMT Subject: [Help]: mailbox classes References: Message-ID: J. Li wrote: > Hi, > > I am trying to extract a message from a unix mailbox file. Python does > provide few classes for easy and uniform access. So it says! After > having read the libiary references, I went nowhere. > > Can anyone give me an example as how to use these mailbox classes and Say I want to know how many messages from GvR are in my inbox: [alex at lancelot alex]$ python Python 2.2.1 (#2, Jul 15 2002, 17:32:26) [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from mailbox import UnixMailbox as MB >>> inbox = MB(open('/home/alex/Mail/inbox')) >>> from_guido = [x for x in inbox if x.get('from').find('Guido van Rossum')>-1]>>> len(from_guido) 108 >>> Further, let's remove those such messages that are in the python-dev mailing list: >>> gvr_notdev = [x for x in from_guido if x.get('sender').find('python-dev')==-1] >>> len(gvr_notdev) 5 >>> etc, etc. > what is it relationship with email.message classes. Not much, intrinsically -- the items in a mailbox object by default are rfc822.Message instances. But you can pass as the second argument to the constructor a factory with a compatible interface, which should let you get email.Message instances instead, if that's what you want. Alex From bfarwick at juno.com Mon Sep 23 14:22:33 2002 From: bfarwick at juno.com (brrrent) Date: 23 Sep 2002 11:22:33 -0700 Subject: cursor positioning and color References: Message-ID: <1b6dca50.0209231022.6fae7f6d@posting.google.com> TuxTrax at fortress.tuxnet.net (TuxTrax) wrote in message news:... > Being new to python, I would like to know how one goes about such > tasks as precise cursor positioning and output to screen in color. > Hi Mathew, Curses is the way to go when using Linux/Unix. Wconio is the way to go when using Microsoft. You can find in the Vaults of Parnassus. If you have any trouble locating it, let me know, I can email it to you. Small library, works well. All the best, brrrent :snip > > Cheers, > > Mathew From bdesth at nospam.free.fr Thu Sep 12 00:25:59 2002 From: bdesth at nospam.free.fr (laotseu) Date: Thu, 12 Sep 2002 00:25:59 -0400 Subject: I must be an idiot, please pity me! References: Message-ID: <3D801757.1020901@nospam.free.fr> newbie wrote: > Hello all. I'm getting very desperate now, so I have to ask for some help. > I'm working on a small project and have slipped into what must be > namespace hell. > > I have a few controlling CGI scripts that use functions from other modules > to build parts of a page. Each function in these other modules contains > the SQL processing and HTML building code grouped by related data. The > idea being I can reuse the functions in the other scripts. All works fine, > providing each modules connects to the database as a stand alone job, or I > pass a database connection object thing to each and every function. I > suspect that both of these are wrong, due to the ugliness or nasty system > overhead of the datbase connections. > What I thought I should be able to do is: > > CGI1.py: > > import mod1, mod2 > > connect to database > > create part of page using mod1.functiona > create part of page using mod1.functionb > create part of page using mod2.functionz > > close database > > > But it doesn't seem to work like that. I've trawled though google and deja > for days (plus a couple of new rider books), and no one seems to hit this > problem. I must have a HUGE misunderstanding somewhere. I know mod1 and > mod2 cannot see CGI.py namespace, but there must be a way of sharing the > database connection, mustn't there? > > Help or a kick up the bottom would be really appreciated here! > > Sammy. Creating a db connection in each function for sure not be very efficient.But what's wrong with passing the database connection to the functions in mod1, mod2, and modXXX ??? Anyway, you can make it simpler, like this : in each module, - create a global db_connection variable - add an init() function, that takes a db_connection as argument and assign it to the module's global db_connection variable - and don't forget to call this function before any other. Another, more OO way to do this would be to rewrite your modules as classes, each getting a db_connection argument in it's __init__(), and then, in the main script, create the needed objects. This second solution is somewhat safer with threading (if each thread creates it's own connection and it's own objects...) HTH Laotseu From spoermeg at voldelig.com Tue Sep 17 19:30:29 2002 From: spoermeg at voldelig.com (Terje Johan Abrahamsen) Date: Tue, 17 Sep 2002 18:30:29 -0500 Subject: Source code References: Message-ID: "Gerhard H?ring" wrote in message news:mailman.1032152058.11043.python-list at python.org... > * Terje Johan Abrahamsen [2002-09-15 23:31 -0500]: > > If I would like to write some code that would not be possible for > > others to read, after I distribute the program, would Python be > > suitable? I know that there are a few programs like Py2Exe, that > > creates .exe files. But, I also saw this: > > > > -------------------- > > A zip-compatible archive is built, containing all files from this > > directory as well as your script, and appended to a custom python > > interpreter supplied with py2exe. > > -------------------- > > py2exe contains Python byte code. Python byte code can be transformed > into Python source code, but all comments are lost. > > > Doesn't sound like it is protected very well. Is there some > > alternative to Py2Exe that can do the job, or should I look for a > > compiled language instead? > > You should perhaps reconsider if and why you need to hide your source > code. If I am going to sell my programs, I do not want somebody else to take my sourcecode, change a few things, and sell it themselves. From DeepBleu at DeepBleu.org Fri Sep 20 19:17:03 2002 From: DeepBleu at DeepBleu.org (DeepBleu) Date: Fri, 20 Sep 2002 23:17:03 GMT Subject: pyrhon and oracle References: <5b8834c2.0209201412.50e77861@posting.google.com> Message-ID: What Oracle package are you using? DCOracle2? Something else? DeepBleu "hellprout" wrote in message news:5b8834c2.0209201412.50e77861 at posting.google.com... > hi , i just want to have some detail about python and oracle > what ca i use to query oracle with python ? > > i jsut want a little exemple > > thanks From peter at engcorp.com Tue Sep 10 15:52:07 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 10 Sep 2002 15:52:07 -0400 Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> <6afb9d2c.0209091641.1d9b652e@posting.google.com> <3d7d6fd5@news.sentex.net> Message-ID: <3D7E4D67.67E42022@engcorp.com> Syver Enstad wrote: > > Peter Hansen writes: > > > Search for Mark Hammond's "win32all" package and install it, or > > install the ActiveState distribution of Python which has it already > > included. win32ui is one of the modules included in that package. > > Just to confuse further, win32all is not a python package. It's a > distribution of python modules and packages. What I mean is that > win32ui is a module that is not in a package, although it is included > in the win32all distribution. I think I'll quit now, before I make > things clearer. ;-) Oops, my apologies for starting the confusion. I stupidly used conventional meanings for "module" and "package" instead of reserving those for their specific Python meanings. Substitute something "extensions" for package, and maybe "DLL wrapper" or "library interface" for module in my above message and maybe it becomes a little clearer. Or not. If not, well, we're already all confused enough that this won't hurt much. :) -Peter From yaipa at aol.com Thu Sep 19 13:01:23 2002 From: yaipa at aol.com (yaipa) Date: 19 Sep 2002 10:01:23 -0700 Subject: linking extension modules w/ "ld" on Solaris - to be expected? References: Message-ID: <8d148763.0209190901.6276b37e@posting.google.com> Skip Montanaro wrote in message news:... > On a Solaris machine I configured Python (2.1.3 at the moment, but 2.2.1 is > in the wings) using: > > ./configure --with-gcc=mycc --with-cxx=mycc > > where "mycc" is a shell script which decides whether or not to invoke Sun's > C or C++ compiler. Some (but not all) 3rd party extension modules need to > be compiled with C++, but I don't want to force all to be C++-compiled. > (Gcc is not an option here.) > > I noticed in the configure output that LDSHARED got set to "ld -G". Is this > typical for Solaris when building with a non-gcc compiler? Skip, I've tried compiling both Python 2.1.1 and 2.2.x on Solaris 8 and 9 with gcc 2.9x and 3.x in my path. I consistently get the same build error each time, so it is likely that there is some *switch* I am not setting somewhere. When trying to compile Python I simply run configure/make as 'root' without modification. Configure runs without error, but the build dies part way through claiming several 'function declaration isn't a prototype'. Is there a site which covers building Python in a Solaris environment or maybe you could post a few pointers? configure 'head' ---------------------- creating cache ./config.cache checking MACHDEP... sunos5 checking for --without-gcc... no checking for --with-cxx=... no checking for c++... c++ checking whether the C++ compiler (c++ ) works... yes checking whether the C++ compiler (c++ ) is a cross-compiler... yes checking for gcc... gcc checking whether the C compiler (gcc ) works... yes checking whether the C compiler (gcc ) is a cross-compiler... no checking whether we are using GNU C... yes checking whether gcc accepts -g... yes checking how to run the C preprocessor... gcc -E checking for AIX... no checking for minix/config.h... no checking for Cygwin environment... no checking for mingw32 environment... no checking for executable suffix... no checking for --with-suffix... checking for case-insensitive build directory... no checking LIBRARY... libpython$(VERSION).a checking LINKCC... $(PURIFY) $(CC) checking LDLIBRARY... libpython$(VERSION).a checking for ranlib... : checking for ar... no checking for aal... no checking for a BSD compatible install... /opt/sfw/bin/ginstall -c checking for --with-pydebug... no checking whether gcc accepts -OPT:Olimit=0... no checking whether gcc accepts -Olimit 1500... no checking whether pthreads are available without options... no checking whether gcc accepts -Kpthread... no make trace follows ------------------ .... # first sign of error in the make. gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Python/pythonrun.o Python/pythonrun.c Python/pythonrun.c: In function `initsigs': Python/pythonrun.c:1348: warning: function declaration isn't a prototype Python/pythonrun.c: In function `PyOS_getsig': Python/pythonrun.c:1448: warning: function declaration isn't a prototype Python/pythonrun.c: In function `PyOS_setsig': Python/pythonrun.c:1470: warning: function declaration isn't a prototype gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Python/structmember.o Python/structmember.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Python/symtable.o Python/symtable.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Python/sysmodule.o Python/sysmodule.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Python/traceback.o Python/traceback.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Python/getopt.o Python/getopt.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Python/dynload_shlib.o Python/dynload_shlib.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Python/thread.o Python/thread.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Modules/config.o Modules/config.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -DPYTHONPATH='":plat-sunos5:lib-tk"' \ -DPREFIX='"/usr/local"' \ -DEXEC_PREFIX='"/usr/local"' \ -DVERSION='"2.2"' \ -DVPATH='""' \ -o Modules/getpath.o ./Modules/getpath.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Modules/main.o Modules/main.c gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -o Modules/gcmodule.o Modules/gcmodule.c gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -c ./Modules/threadmodule.c -o Modules/threadmodule.o gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -c ./Modules/signalmodule.c -o Modules/signalmodule.o ./Modules/signalmodule.c:89: warning: function declaration isn't a prototype ./Modules/signalmodule.c: In function `signal_signal': ./Modules/signalmodule.c:213: warning: function declaration isn't a prototype ./Modules/signalmodule.c:215: warning: function declaration isn't a prototype ./Modules/signalmodule.c:226: warning: function declaration isn't a prototype ./Modules/signalmodule.c: In function `initsignal': ./Modules/signalmodule.c:333: warning: function declaration isn't a prototype ./Modules/signalmodule.c:337: warning: function declaration isn't a prototype ./Modules/signalmodule.c:356: warning: function declaration isn't a prototype ./Modules/signalmodule.c:358: warning: function declaration isn't a prototype ./Modules/signalmodule.c: In function `finisignal': ./Modules/signalmodule.c:562: warning: function declaration isn't a prototype ./Modules/signalmodule.c:570: warning: function declaration isn't a prototype gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -c ./Modules/posixmodule.c -o Modules/posixmodule.o ./Modules/posixmodule.c: In function `posix_fstatvfs': ./Modules/posixmodule.c:4389: warning: passing arg 2 of `fstatvfs64' from incompatible pointer type ./Modules/posixmodule.c: In function `posix_statvfs': ./Modules/posixmodule.c:4416: warning: passing arg 2 of `statvfs64' from incompatible pointer type gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -c ./Modules/_sre.c -o Modules/_sre.o gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -c ./Modules/newmodule.c -o Modules/newmodule.o gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -c ./Modules/symtablemodule.c -o Modules/symtablemodule.o gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -c ./Modules/xxsubtype.c -o Modules/xxsubtype.o if test -f buildno; then \ expr `cat buildno` + 1 >buildno1; \ mv -f buildno1 buildno; \ else echo 1 >buildno; fi gcc -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DHAVE_CONFIG_H -DBUILD=`cat buildno` -o Modules/getbuildinfo.o ./Modules/getbuildinfo.c rm -f libpython2.2.a ar cr libpython2.2.a Modules/getbuildinfo.o gmake: ar: Command not found gmake: *** [libpython2.2.a] Error 127 Viking1# Thanks, any help greatly appreciated. Alan Haffner From m.faassen at vet.uu.nl Fri Sep 6 16:54:32 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 6 Sep 2002 20:54:32 GMT Subject: Timothy Rue References: <898662b7d85d2c966c0bd45d563d5d2d@xganon.com> Message-ID: Donn Cave wrote: > Quoth xganon : > | Does Timothy Rue still Troll here? > | If not, how did you get rid of him? > | We need him out of our group now, > | maybe we could get him into a Perl > | group for a while and let them deal > | with him? Which group is that anyway? :) Seems like you and Tim have been posting on comp.sys.amiga misc. Apparently you were looking for a Tim Rue FAQ at the time, and the thread has a link, FAQ posted in '99! http://groups.google.com/groups?q=tim.rue.faq&start=10&hl=en&lr=&ie=UTF-8&scoring=d&selm=7r5lrp%24ftj%241%40ns2.dialnet.net&rnum=15 Fun, fun.. > If the problem is only that he posts to your group, then your > group is way ahead of comp.lang.python. When he was here, a > number of regulars utterly lost touch with whatever common sense > they may ordinarily possess, and it went on for what seemed like > months. If you don't want to engage in his discussion, then don't. > I think you'll find that it works as well as anything. I am a regular and I didn't have any common sense anyway. I had great fun watching Tim Rue in action, though. Perhaps the Python Secret Underground got to him, but since it doesn't exist that is somewhat unlikely. I'm a fan of the ruebot. Did you know it was a rogue timbot? It doesn't say so in the FAQ, but it's true. Perhaps this is secret PSU information, in which case they would really not want me to say that in addition he From Hobbes2176 at yahoo.com Thu Sep 19 00:16:33 2002 From: Hobbes2176 at yahoo.com (Mark) Date: Thu, 19 Sep 2002 04:16:33 GMT Subject: Minimal debug/rep functionality References: Message-ID: Okay, here's my first stab: from bdb import * class Mdb(Bdb): def user_call(self, frame, args): name = frame.f_code.co_name if not name: name = '???' def user_line(self, frame): import linecache name = frame.f_code.co_name if not name: name = '???' fn = self.canonic(frame.f_code.co_filename) line = linecache.getline(fn, frame.f_lineno) print '+++', frame.f_lineno, name, ':', line.strip() def user_return(self, frame, retval): None def user_exception(self, frame, exc_stuff): self.set_continue() This is copied out of bdb.py and modified from the Tdb class. To use it, you simply: import mdb # contains definition of Mdb import foo # contains function to trace m = mdb.Mdb() m.run('foo.main()') # main() is the method I'd like to trace and out pops a list like (things are a hair cleaner if the input is done from a file instead of interactively): +++ My next wish is to NOT have it step into functions .... this isn't a real biggie but it would help eliminate some (soon to be) volumious output. Regards, Mark From marco at sferacarta.com Fri Sep 6 11:54:30 2002 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 6 Sep 2002 17:54:30 +0200 Subject: ttySx In-Reply-To: <20020906152418.GA6937@sferacarta.com> References: <200209061708.25677.b.maryniuk@forbis.lt> <20020906152418.GA6937@sferacarta.com> Message-ID: <20020906155430.GA7147@sferacarta.com> On Fri, Sep 06, 2002 at 05:24:18PM +0200, Marco Mariani wrote: > Here it is. > Of course, the code is old and sucks. If you have problems with lock > files, I don't want to know :-) I forgot an example. Hope it helps. import modem import sys if len(sys.argv)==3: command = sys.argv[2] serial = sys.argv[1] else: sys.exit(1) mod = modem.Modem(serial) if not mod.open() and not mod.term_init(): mod.set_speed(2400) if not mod.sendline(command): for i in mod.answer: print i mod.purge() sys.exit(0) mod.purge() sys.exit(1) From bloke at ii.net Fri Sep 27 21:44:55 2002 From: bloke at ii.net (Rob Hall) Date: Sat, 28 Sep 2002 09:44:55 +0800 Subject: Problem with ClientCookie References: <3d946d0f$0$10364@echo-01.iinet.net.au> <8b5e42a6.0209271211.4f0c6d9f@posting.google.com> Message-ID: <3d950984$0$11916@echo-01.iinet.net.au> Thankyou. That did the trick. I had also sent a copy of the message to the author of the package. I must confess, John (the author) was very prompt and helpful. I will send him the solution also. Rob From stasZ at linuxisbeter.nl Wed Sep 18 08:41:51 2002 From: stasZ at linuxisbeter.nl (stasZ) Date: Wed, 18 Sep 2002 14:41:51 +0200 Subject: Writing linux term color codes to a file References: Message-ID: On Wed, 18 Sep 2002 03:09:37 +0200, Andrei Kulakov wrote: > Hello, > > I ran into a bit of a problem here.. I'm making a small app that > visually creates bash prompts (just for fun of it), and at one point it > has to write the prompt to .profile, optionally with linux terminal > color codes, like \[044;\]m or something like that (you know what I'm > talking about). They don't come out right *in* the file. I tested the > simple case where I'd have a few such codes in a string in python prompt > and I'd look at it and it looks fine, but as soon as I write it out to a > file and look at the file, it's "cooked". > > I hope you know what I mean, if anyone wants I can post direct pastes. > > Looks like write() does some sort of processing on the text; is there > any way to turn that off? >>>prompt = r'\[044;\]' >>> prompt '\\[044;\\]' >>> f = open('/home/foo/prompt,'w') >>> f.write(prompt) >>> f.close() $ more prompt \[044;\] I think your problem is solved if you use a raw string (r'spam'). With a raw string the backslash is just a backslash. Stas Z -- A computer scientist is someone who, when told to 'Go to Hell', sees the 'go to', rather than the destination, as harmful. From spam07 at thack.org Mon Sep 23 15:41:18 2002 From: spam07 at thack.org (Tapio Kelloniemi) Date: Mon, 23 Sep 2002 19:41:18 GMT Subject: Non-interpreted Python? References: <3D8F65A4.38124945@engcorp.com> Message-ID: Re: Non-interpreted Python? Peter Hansen wrote: >Tapio Kelloniemi wrote: >> >> I'm new to Python and would like to know, wheter it is possible to >> compile Python code to binary executables (and on which platforms)? > [--] >There are other approaches, but there's no point describing them until >you explain *why* you want to do this. What are your requirements? I'm using Linux and searching for a good high-level language to use in my projects. I don't have any special ideas, it depends on language. I don't like the idea of using any interpreted language, but have heard so much good about Python. I have used mostly C before and so it would be best to give up my speed requirements. >> Or better, if it is possible to compile code into object format and then >> link with C/C++/whatever code. > >Python has excellent facilities for embedding in applications written >in C/C++. Check the documentation for the relevant sections. I have thought of writing some parts of programs in Python (some kind of library) and then be able to use it in C++/Ruby/anything else, if it is possible. -- Tapio From mhuening at zedat.fu-berlin.de Wed Sep 18 14:57:14 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 18 Sep 2002 18:57:14 GMT Subject: BibTeX module? References: Message-ID: Gerhard H?ring wrote in news:slrnaoh2i3.25g.gerhard.haering at haering.opus-gmbh.net: > Did you try Google? It suggests > http://canvas.gnome.org:65348/pybliographer/ > Yes, I did. But Pybliographer is a full-fledged bibliography application, which is an overkill for my purpose. I just need a simple Python-module to work with some BibTeX and/or Endnote/Refer files. Thanks, Matthias From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Fri Sep 27 14:52:41 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Fri, 27 Sep 2002 20:52:41 +0200 Subject: well-formed xml References: Message-ID: <3d94a8ee$1@news.mt.net.mk> > from xml.dom import minidom > s = "search" > # ^ > # - seems to be the problem > # > # maybe it thinks I'm trying to reference the &q entity? In XML the & character must be encoded as & -- ?????? Speak softly and carry a cellular phone. From jepler at unpythonic.net Fri Sep 20 15:27:55 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 20 Sep 2002 14:27:55 -0500 Subject: Python 2.2.1 compatible with Tcl/Tk 8.4? In-Reply-To: References: Message-ID: <20020920192746.GC9734@unpythonic.net> python2.3a0 (CVS) seems to work fine with Tcl/Tk8.4. However, I don't believe any special steps were taken to make it compatible. Thus, I suspect 2.2.1 will work fine too. You will have to recompile Python, though, to make the upgrade. Jeff From henrik.motakef at web.de Mon Sep 23 05:17:07 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 23 Sep 2002 11:17:07 +0200 Subject: os module and sys module~ References: Message-ID: <87znu9jca4.fsf@pokey.henrik-motakef.de> black writes: > I couldnt tell the difference between them immediately, and some > same method confused me much, for example they both have "path" > attribute but what's the difference ? The sys module basically refers to the Python system itself, the os module is about the operating system Python runs on. Regards Henrik From hwlgw at hotmail.com Sun Sep 29 07:18:07 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 29 Sep 2002 04:18:07 -0700 Subject: Help please with menubars References: <000f01c266f3$2903dbc0$2502a8c0@emily.ewndsr01.nj.comcast.net> Message-ID: [Chad Netzer] > That was almost exactly what the code I posted did... Hmmmph; Here is > a revision that exits when you click on the "Exit" entry in the > menubar, WITHOUT dropping down a menu. There is no visible difference between such an ``Exit'' entry (calling a function directly) and a normal dropdown menu entry. Do you know how to display ``Exit'' like a Button? ''' Give your very best today. Heaven knows it's little enough. ''' From skip at pobox.com Fri Sep 13 15:35:18 2002 From: skip at pobox.com (Skip Montanaro) Date: Fri, 13 Sep 2002 14:35:18 -0500 Subject: transform list of int in a list of string?? In-Reply-To: References: <-1483717605.1031940885180.JavaMail.nobody@webmail2.brturbo.com> Message-ID: <15746.15862.413159.408138@12-248-11-90.client.attbi.com> Skip> y = [int(n) for n in x] Steve> Skip of course meant Steve> y = [str(n) for n in x] Steve> in his second example. Yes he did. Thanks for catching the bug. S From tim.hochberg at ieee.org Thu Sep 26 15:39:14 2002 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Thu, 26 Sep 2002 19:39:14 GMT Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> <3D934C5C.4000603@mxm.dk> <20020926.130938.1789366143.1524@cybermesa.com> Message-ID: "Jay O'Connor" wrote: > How about "underder"?? Or maybe "dunder"? -tim From alex.andru at gmx.net Mon Sep 9 15:08:32 2002 From: alex.andru at gmx.net (Alex Andru) Date: Mon, 9 Sep 2002 21:08:32 +0200 Subject: ldap compile problem? Message-ID: hallo, i have downloaded the python ldap driver but have problems to make build on my mandrake 8.1 linux? does anybody have an idea what is wrong? i get the same err message also on cygwin? thanks for help, alex [alex at io python-ldap-2.0.0pre05]$ python setup.py build running build running build_py warning: build_py: file Lib/ldap.py (for module ldap) not found not copying Lib/ldap/__init__.py (output up-to-date) not copying Lib/ldap/async.py (output up-to-date) not copying Lib/ldap/functions.py (output up-to-date) not copying Lib/ldap/sasl.py (output up-to-date) not copying Lib/ldap/schema.py (output up-to-date) not copying Lib/ldap/ldapobject.py (output up-to-date) not copying Lib/ldap/modlist.py (output up-to-date) not copying Lib/ldapurl.py (output up-to-date) not copying Lib/ldif.py (output up-to-date) warning: build_py: file Lib/ldap.py (for module ldap) not found running build_ext building '_ldap' extension skipping Modules/LDAPObject.c (build/temp.linux-i686-2.1/LDAPObject.o up-to-date) skipping Modules/common.c (build/temp.linux-i686-2.1/common.o up-to-date) gcc -O3 -fomit-frame-pointer -pipe -mcpu=pentiumpro -march=i586 -ffast-math -fno-strength-reduce -fPIC -DHAVE_LDAP_START_TLS_S -DLDAPMODULE_VERSION=2.0. 0pre05 -IModules -I/usr/local/openldap2/include -I/usr/include/python2.1 -c Modules/constants.c -o build/temp.linux-i686-2.1/constants.o Modules/constants.c: In function `LDAPinit_constants': Modules/constants.c:159: `LDAP_SCOPE_DEFAULT' undeclared (first use in this function) Modules/constants.c:159: (Each undeclared identifier is reported only once Modules/constants.c:159: for each function it appears in.) error: command 'gcc' failed with exit status 1 From fperez528 at yahoo.com Thu Sep 26 20:05:00 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 26 Sep 2002 18:05:00 -0600 Subject: indexing and searching pdf files References: Message-ID: Rajarshi Guha wrote: > My question - is there already something like this with python? > Another question which is slightly off topic is, does anybody know of any > articles/pages that talk about indexing text files efficiently - index > generaion algorithms etc? It doesn't directly discuss algorithms, but the following page is an _excellent_ overview of the problem: http://freshmeat.net/articles/view/286/ Please post here any findings you may make on the python/indexing front. This is a problem I expect to have to deal with in a few months, so having it solved for me ahead of time would be most pleasant :) Full-text indexing of PostScript would also be nice, with provisions for automatic indexing of gzipped and bz2 compressed files. While we are at it, it would be nice to index code in at least C, C++, Fortran, Mathematica and Python and build tables of classes/functions defined in each file for the index database. Mmmhhh, what else? Ah, if a .ps/.pdf has an associated .lyx/.tex file, that should be indexed instead, with the abstract, author, keywords, etc. fields properly recognized. A search interface with a basic webserver would be enough. That would be a start. Not asking too much, am I? Cheers, f. From fredrik at pythonware.com Wed Sep 4 03:14:10 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Sep 2002 07:14:10 GMT Subject: Tkinter is extremely slow in drawing plots.... why??? References: <3D6E4A62.56DF6302@earthlink.net> Message-ID: <6pid9.5886$e5.1033593@newsb.telia.net> Joseph A. Knapka wrote > You can create the entire plot as a single canvas item, > however, which might speed things up considerably. > Assuming "dataset" is just a list of 2-tuples, > then this should work: > > def flatten(l): > import operator > return reduce(operator.add,map(list,l),[]) > item = canvas.create_line(*flatten(dataset),fill="black") > > That code will give you a smooth line connecting > all of your data points. The "flatten()" is just > to convert your [(x1,y1),(x2,y2),..] into an > unstructured [x1,y1,x2,y2], which is what create_line() > wants. create_line flattens its arguments all by itself (and in recent versions, this is done by a really fast C function). in other words, this should work: item = canvas.create_line(dataset, fill="black") From gmuller at worldonline.nl Sat Sep 21 16:39:15 2002 From: gmuller at worldonline.nl (GerritM) Date: Sat, 21 Sep 2002 22:39:15 +0200 Subject: How to get memory usage on Windows? Message-ID: I am building an access log analyzer. For the first version I did not worry about performance or memory use, the first exploration was about what is practical information to extract and how to present. For current result see http://www.extra.research.philips.com/natlab/sysarch/GaudiStatistics.html and http://www.extra.research.philips.com/natlab/sysarch/weblog/index2002.over.h tml For the second version memory use becomes an issue. The brute force version keeps all information simultaneously in memory, without any size optimization. This results now in memory use of about 250 MByte (measured via very coarse windows resource tool), which scales linear with the amount of (ever increasing) input. I would like to be able to measure more specific how much memory is used per phase and/or per function. Is there any function returning this information. I noted that on Unix the resource module gives access to this kind of information, but I could not find any Windows alternative. regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From whisper at oz.net Sat Sep 28 18:17:05 2002 From: whisper at oz.net (David LeBlanc) Date: Sat, 28 Sep 2002 15:17:05 -0700 Subject: Getting started In-Reply-To: <3D956756.7010502@cascade-sys.com> Message-ID: > I recall a Lisp implementation from long ago that did not distinguish > between integers and machine addresses. When applying a function to an > arg list, if the function name evaluated to a number the interpreter > blithely JSRed to that address. This was a Feature, in that it was how > system built-ins were linked with the higher level stuff. User code did > not normally do this and it was not a big issue in practice. However it > WAS a loophole that allowed type errors to occur, as it allowed code to > jump to any random address in the system. > > But I think the generalization holds for most dynamic languages. > > Regards > > --jb In fact, the names of some Lisp funtions came from the machine registers of the same name: car (current address register) and cdr (current data register) are the only ones I recall offhand. Dave LeBlanc Seattle, WA USA From jetman516 at hotmail.com Thu Sep 12 16:57:14 2002 From: jetman516 at hotmail.com (The Jetman) Date: 12 Sep 2002 13:57:14 -0700 Subject: Python for DOS lives ? Message-ID: I did a search for Python 4 DOS just moments ago, on Google. No joy. I already knew the last iteration of Python4DOS (Python-DX) went belly-up sometime ago. Then I got the thought to check out DJ Delorie's site (the author/maintainer of DJGPP.) I found the following mail archive msg: http://www.delorie.com/archives/browse.cgi?p=djgpp/2002/05/19/15:30:25 The bottom line is: http://phaseit.net/Python/python-djgpp.221.tar.gz !!!! The above mail announcement is from a May of this year, so it may be well along. Haven't had a chance to test it, probably won't for a day or so, but I need it, so I'll definitely touch base in the next couple of days, if anyone else is interested. According to the author of the port, it's working but isn't quite ready for prime-time....Jet From roy at panix.com Thu Sep 5 11:47:52 2002 From: roy at panix.com (Roy Smith) Date: 5 Sep 2002 11:47:52 -0400 Subject: Why Python? References: <4f49d232.0209050418.7668c21@posting.google.com> Message-ID: Laotseu wrote: > Now you should *also* learn other languages. But you'd better go with > a lo level languages and a functionnal one - C and Lisp could be good > choices. I guess it depends on why you're learning languages. If you're learning languages to get a paying job as a programmer, lisp would be a horrible choice. If you're learning languages to study computer science, lisp is looking a lot better. From ajs at ix.netcom.com Mon Sep 16 23:44:41 2002 From: ajs at ix.netcom.com (Arthur) Date: Mon, 16 Sep 2002 23:44:41 -0400 Subject: Not sure how to phrase this question Message-ID: <001501c25dfc$8e7b6b30$9865fea9@arthur> Emille writes - >I don't think you need __new__, or if you do, you'll want to read up on >the existing documentation and prior discussions. Oh... I couldn't find >the docs. There are some usage examples in the demo/newmetaclasses, but >they only seem to exist in cvs. All this probably has a bit to do with >the lack of response you mention Yeah, if *I* need __new__ I know there is going to problems. Seems there is indeed a simple solution which works with the infrastructure I had already created - the obvious one that dawned on me after having made my original post. My "factories" work simply as functions. def Intersection(*args,**kw): dowhatigottodo if its the right thing to do under the circumstances: return PlaneIntersetion(args[0],args[1] else: do what makes more sense based on args. class PlaneIntersection(new or old,shouldn't matter): def __init__(self,plane,line): self.plane = plane self.line = line takeitfromthere i=Intersection(planeinstance, lineinstance) #or Intersection(lineinstance,planeinstance ) the dowhatigottodo routine handles the ordering issues print i.__class__ >>class '__main__.PlaneIntersection' As you suggest, this is probably just one of a number of ways to go, but seems to work most simply for picking up from where I happen to be right now. There is something to be said, though, for sort of discovering this stuff, rather than learning it in the textbook sense. As Terry posts suggests, this is probably mundane standard procedure. But, at least I have a pretty good sense now of why. Art From peter at engcorp.com Sun Sep 22 12:51:59 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 22 Sep 2002 12:51:59 -0400 Subject: Smalltalk vs. Python and COM was Re: Byte Magazine and Smalltalk References: <3d87a686@tobjects.> <3d87dd7c$1@tobjects.> <20020918.115128.1605894428.1527@cybermesa.com> Message-ID: <3d8df525$1@news.sentex.net> (Cross-posting removed to avoid language wars.) Pino Gargiulo wrote: > For this project I was considering Smalltalk and Python. The first so I > could be some real stuff done and Python because apparently it permits > quite easy access the the mysterious (to me) m$ APIs. I really would > want to stay awar from VC++, and I'm looking for some quite turnaround > evironment since I'll be learning COM on the job. Could you please explain why you don't think Python could be used for "real stuff"? Do you have some other code already written in Smalltalk with which you're trying to stay compatible, or do you have a library in Smalltalk that you must use for this job? I don't see any reason to use two languages on a project where one will do the job. -Peter From tjreedy at udel.edu Wed Sep 18 09:24:42 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 18 Sep 2002 13:24:42 GMT Subject: Earing money with Python software (was: More on Protecting Source Code) References: <4jt7ma.fse.ln@lenashee.goebel-consult.de> <8a6ba1da.0209180206.2d47f2bd@posting.google.com> Message-ID: "Richie Hindle" wrote in message news:8a6ba1da.0209180206.2d47f2bd at posting.google.com... > For library code (and tools like bridgekeeper which have a library > component), my approach is to release a single version under two > licenses, one free (as in both speech and beer) for use in Open Source > projects and one with a fee for use in closed source projects. Perhaps we should call this a Chameleon license: the software takes on the 'color' of its use-environment. TJR From mgerrans at mindspring.com Tue Sep 17 02:34:25 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Mon, 16 Sep 2002 23:34:25 -0700 Subject: [FEEDBACK] Is this script efficient...is there a better way? References: <4ZRf9.1782$Lg2.248733@news2.news.adelphia.net> <3hSf9.168947$l_4.98525@atlpnn01.usenetserver.com> <8PSf9.1796$Lg2.257378@news2.news.adelphia.net> Message-ID: Well, since every other aspect of this little script has been beaten to death, I'll add my 2.0*pow(10,-17) Kongbucks on the error messages: I make a habit of including as much useful context information as I can, so for instance, instead of: ... except: print 'Failed to open log file.' I might have something like: ... except: print 'Failed to open %s for output.' % logFileName This usually makes me a lot happier when the silly thing does fail (and especially when someone else is using the script and I discover that they don't have access to the same network resource I do, or don't have the same configuration, etc.). The traceback module is handy if you want to display even more information from the exception. - Matt From skip at pobox.com Thu Sep 19 10:35:54 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 19 Sep 2002 09:35:54 -0500 Subject: strong/weak - dynamic/static [Was: Getting started] In-Reply-To: References: Message-ID: <15753.57546.804290.415645@12-248-11-90.client.attbi.com> Mark> I don't have any practical use for the following, but it seems to Mark> demonstrate that what you said is not true... [ snip bit about setting __class__ ] That doesn't make Python weakly typed. You have to be explicit about the change. An example of weak typing would be a = "3.14159" + 7 Python raises a TypeError exception because it doesn't allow you to (can't concatenate strings and ints or quietly coerce strings to numbers and perform addition). Perl, assigns the floating point value 10.14159 to a. -- Skip Montanaro - skip at pobox.com The need for gutters to be cleaned is directly proportional to how hard it happens to be raining at the moment. From tjreedy at udel.edu Thu Sep 19 00:12:43 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Sep 2002 04:12:43 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> Message-ID: <%8ci9.138477$5r1.5541622@bin5.nnrp.aus1.giganews.com> "daniel w. moore" wrote in message news:33b491f.0209181820.17b6ea70 at posting.google.com... > It's occurred to me after some brainstorming on the subject that the > C/perl construct > > a ? b : c > > can be arranged like this in python: > > (a and [b] or [c])[0] If you *know* that b will evaluate as True (perhaps because it is a non-null constant, then this can be simplified to 'a and b or c'. I first used this several years ago. TJR From jepler at unpythonic.net Mon Sep 16 16:25:05 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 16 Sep 2002 15:25:05 -0500 Subject: difflib optimization -- wow (tim peters?) Message-ID: <20020916152504.A7537@unpythonic.net> wow, what a speedup! thanks, whoever it was (tim?) $ time python2.3 -O ~/pyunidiff.py foo.c foo2.c > /tmp/pat real 0m5.457s user 0m4.640s sys 0m0.110s $ time python2.2 -O ~/pyunidiff.py foo.c foo2.c > /tmp/pat real 3m14.042s user 3m7.480s sys 0m1.180s foo.c and foo2.c are ~300k long C files from different releases of a piece of software. the diff produced is nearly 250k. pyunidiff is at http://unpythonic.net/~jepler/pyunidiff.py tim, I only need another factor of 30x and it'll beat diff(1) -u in wall time (or 5x to beat diff(1) -u -d). It already gives files about 5% shorter on the files I've tried (or on par with diff -u -d). I notice that the diff produced from 2.2 is marginally smaller, another 1.5% or so. The price to pay for the optimization? Jeff From emile at fenx.com Thu Sep 26 20:09:21 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 26 Sep 2002 17:09:21 -0700 Subject: This is driving me insane! References: <20020926235643.37002.qmail@web20806.mail.yahoo.com> Message-ID: Derek Basch > http://www.geocities.com/dbasch/insane.txt > > I would expect to get: > [0, 0] > [0, 0] > [[0, 0]] > > but I am getting: > [0, 0] > [0, 0] > [[1, 1]] > Please post the code that is using the class. As it is, there are only two print statements in the class, so how you're getting three output lines at all is in question... -- Emile van Sebille emile at fenx.com --------- From phil (at) linux2000.com Tue Sep 24 18:20:10 2002 From: phil (at) linux2000.com (Phil Edwards) Date: Tue, 24 Sep 2002 23:20:10 +0100 Subject: Shadow password handling Message-ID: <3d90e36d$0$123$7b0f0fd3@reader.news.newnet.co.uk> Hi: Does anybody know of a Python module which will allow username/password credentials to be validated ona Linux box which is configured to use md5 and/or shadow passwords? The application is a web portal which requires certain virtual sites on a Cobalt RaQ to be accessible only to particular users. Just in case anybody mentions .htpasswd files, the end user wants to be able to do all the username/password maintenance via the RaQ admin interface... :-( From gerhard.haering at gmx.de Thu Sep 5 19:17:11 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Fri, 6 Sep 2002 01:17:11 +0200 Subject: What database should I use In-Reply-To: References: Message-ID: <20020905231711.GB1229@lilith.ghaering.test> * Lutz Schroeer [2002-09-05 21:46 +0000]: > "A" wrote in > news:mailman.1031257921.29400.python-list at python.org: > > > I am going to program a small application (in Python and wxPython) > > which consists about 2000 - 3000 records . Can you please recommend > > which database is the best for that. I use Windows. > > Maybe MS Access or FoxPro or MySQL or better? > > I want to keep the program as small as possible. > > From your question I derive that you want to run the program on an MS > Windows system. > > Access seems to be the best solution. I disagree. Access requires a lot of setup (win32 extensions if you want to use it via ADO, mxODBC if you want to use ODBC and have a maintained module at the same time.) For databases this small, I'd even consider using shelve or something else from the Python standard library. PySQLite OTOH is Open Source, and the underlying SQL engine is reasonably fast and has good support for SQL. > [with Access] But keep in mind, that you're stuck to Billy's system. Yes, and for no good reason, if you go this way. Better alternatives exist, even several Open Source ones. -- Gerhard From sismex01 at hebmex.com Thu Sep 12 13:07:49 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 12 Sep 2002 12:07:49 -0500 Subject: [ANN] PySQLite 0.3.0 released Message-ID: > > "Gerhard H?ring" wrote in message > news:slrnao0e6p.23c.gerhard.haering at haering.opus-gmbh.net... > > A Python-DB API 2.0 compliant extension module that connects to > > SQLite databases. > ... > > row = cursor.fetchone() > > > > while row != None: > > print "%14s, %15s, %19s, %8s, %25s" % tuple(row) > > row = cursor.fetchone() > > Does anyone know whether there are any plans to update the Python-DB > API to the new iterator protocols, so that the above could be written > more simply something like > > for row in cursor: > print "%14s, %15s, %19s, %8s, %25s" % tuple(row) > ? > > Terry J. Reedy > You can already do it, using iter(): for row in iter(cursor, None): print .... -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From fgranger at alussinan.org Fri Sep 20 13:27:11 2002 From: fgranger at alussinan.org (=?ISO-8859-1?Q?Fran=E7ois_Granger?=) Date: Fri, 20 Sep 2002 19:27:11 +0200 Subject: [Help]: mailbox classes References: <1fitpvg.gi8n0y1iem93tN%fgranger@alussinan.org> Message-ID: <1fitpz7.1h4nj4m19gs2x5N%fgranger@alussinan.org> Fran?ois Granger wrote: > Alex Martelli wrote: > > > J. Li wrote: > > > > > Hi, > > > > > > I am trying to extract a message from a unix mailbox file. > ... > > > > > what is it relationship with email.message classes. > > > > Not much, intrinsically -- the items in a mailbox object by > > default are rfc822.Message instances. But you can pass as > > the second argument to the constructor a factory with a > > compatible interface, which should let you get email.Message > > instances instead, if that's what you want. > > email does not handle the unix mailbox properly. It sees only the first > message. > > I was going the way you suggest by first using mailbox.UnixMailbox, then > i'd like to pass each message given by the next() method to email for > further analysis. But this is way over my current level of understanding > of Python objects and classes. .... after some thought and some trial and errors, I came with this solution. I don't like it, it look bad. def main(): fp = file(folderfile) folder = mailbox.UnixMailbox(fp, factory=email.message_from_file) while 1: mail = email.message_from_file(fp) print mail if not folder.next(): break #mail = email.message_from_file(fp) if __name__ == '__main__': main() -- "Ce qui est gratuit ne vaut pas cher" - inconnu From tjreedy at udel.edu Sun Sep 15 00:35:03 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 15 Sep 2002 04:35:03 GMT Subject: two or more whitespace regular expression? References: Message-ID: "eugene kim" wrote in message news:am12a3$qo0$1 at newsreader.mailgate.org... > i used this.. > > words = string.split(line, '['+string.whitespace > +']'+'['string.whitespace+']+') > > which didn't work.. > thanks What weres 'line' and 'words'? From see_reply_address at something.invalid Wed Sep 25 22:08:27 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 26 Sep 2002 14:08:27 +1200 Subject: Larry Wall's comment on python... References: <3D7958DB.50903@nospam.free.fr> <3D87402E.6020700@thinkware.se> Message-ID: <3D926C1B.7080204@something.invalid> Jacob Hallen wrote: > Please note that I didn't say anything about block > delimiters or parentheses in this. I think they were put into programming > languages to make it easy to write fast compilers. I'm not sure you should lump parentheses in with block delimiters in that statement. They've been in use by mathematicians for centuries before compilers were invented, and, used in moderation, I don't think they have any adverse effect on readability. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From dsavitsk at e-coli.net Mon Sep 9 12:51:11 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Mon, 09 Sep 2002 16:51:11 GMT Subject: random.shuffle question Message-ID: <3k4f9.7500$yt3.3831288@newssrv26.news.prodigy.com> why does this not work to shuffle part of a list? >>> l = [1,2,3,4,5,6,7,8,9] >>> random.shuffle(l[4:8]) >>> print l [1, 2, 3, 4, 5, 6, 7, 8, 9] and more importantly, is there a better way to do this? -d From shalehperry at attbi.com Sat Sep 7 17:29:26 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Sat, 7 Sep 2002 14:29:26 -0700 Subject: Larry Wall's comment on python... In-Reply-To: <1549197.0PZNOebDTH@cartman> References: <1549197.0PZNOebDTH@cartman> Message-ID: <200209071429.26401.shalehperry@attbi.com> On Saturday 07 September 2002 13:46, yka wrote: > Kow Kuroda wrote: > > Well, Python code may look awkward --- if not awk-like --- > > if you don't know how to customize the tab width in your > > editor of choice. For example, vi and emacs indent by 8 > > characters by default, which I suspect is too wide for Python. > > Some code with deep nesting wouldn't look very nice with > > this default. > > > > Kow > > Well at vim :set ts=4 makes more fitting actually emacs defaults to 4 space indenting and does not bother with tabs. I find that code which plays games with how large a tab is always looks ugly unless viewed in the same editor it was written in. From sross at connectmail.carleton.ca Tue Sep 17 19:59:54 2002 From: sross at connectmail.carleton.ca (Sean Ross) Date: 17 Sep 2002 23:59:54 GMT Subject: Splitting a list of strings Message-ID: Hi. I need to read a list of strings from a file, weed out the comments and separate "attribute" descriptions from the data. I have a working implementation, but I'm interested in finding out if there's a better way to do it. Here's the code: def getDataAndAttributes(filename): "Filters *.arff file into lists of data and attribute strings" lines = open(filename).readlines() # All lines beginning with "@'" are attributes, except the last one. attributes = [str for str in lines if str[0] == "@"] # Remove attributes from lines, so we don't process them again to find data. lines = [str for str in lines if not str in attributes] attributes = attributes[:-1] # Filter comments out to get data. data = [str for str in lines if not str[0]=="%" ] return (data, attributes) What I'm interested in knowing is, can I extract all of the "attribute" strings from lines in such a way that I get my list of "attribute" strings, but all of those strings have been removed from lines as well, all at the same time? i.e., without filtering the list a second time. As I've stated, the code above works, but I'm concerned that it may be sub-optimal. Thanks, in advance, for your suggestions, Sean Ross From gregory.p.green at boeing.com Mon Sep 23 15:43:37 2002 From: gregory.p.green at boeing.com (Greg Green) Date: Mon, 23 Sep 2002 19:43:37 GMT Subject: Python COM and variable number of arguments References: Message-ID: Mark Hammond writes: > You could also try passing with pythoncom.Missing or pythoncom.Emtpy > in place of the positional arguments. You may need to experiment to > see what one works - it depends on the COM object. Mark, Thanks. pythoncom.Empty did the trick. I didn't know about either one of those. -- Greg Green From peter at engcorp.com Mon Sep 16 22:07:14 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 16 Sep 2002 22:07:14 -0400 Subject: stdin on Win32 References: <3d865d34$0$22177$afc38c87@news.optusnet.com.au> Message-ID: <3d868e43$1@news.sentex.net> nobody wrote: > This works on Linux, but not Win32. Win32 just gives me EOF.. > > # echo foo|test.py > > where test.py is: > > import sys > > print sys.stdin.readline() Which flavour of Win32? Win98 needs you to explicitly invoke Python and pass the test.py name as a command line option. Also, I believe there are problems with non-Win98 Win32 with respect to redirection and the feature you are trying to invoke. Checking the archives for this might give some detail. -Peter From pan-newsreader at thomas-guettler.de Tue Sep 17 13:46:59 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Tue, 17 Sep 2002 19:46:59 +0200 Subject: File upload script References: <3D871F7E.C313ADD2@student.uib.no> Message-ID: On Tue, 17 Sep 2002 14:26:38 +0200, Steinar Dragsnes wrote: > Hi! > > I'm a complete newbe in python and have never written anything more > advanced then the classical Hallo World example. I have already > programmed an applet where users should be able to upload images and or > other files from their local pc. This is of course not possible due to > the applet security model (sandbox) in Java. But I can start a > python-script from the running java applet which can do the actual file > upload for me and save the file to a specific directory on the apache > server. > > Since the applet that needs the information about what file has been > uploaded into what node, I need a way to send back information to the > applet calling the script. I wonder if this is possible at all? Usually > scripts generate html-pages and call applets from there on they fly, > with the right paranemer tag values. Is this possible when the applet is > already running? Would it not destroy the applet context? I am not a java applet expert, but one thing should be possible: the Java applet can open an URL on the webserver. This server-side generated page contains information which file was uploaded to the server > My main problem is that I do not know how I can pass the parameters of > type String; sessionID, userID and nodeID, from the appleten to the > called python-script. I need to know how to write a function that will > receive these parameters. The python script below is written by a > colleague of mine, and he is now on a sick-leave....and I need to figure > this out soon.... > > In the java code I call the upload.py script like this: > java.net.URL url=new > java.net.URL("http://"+ip+"/cgi-bin/upload.py"); > applet.getAppletContext().showDocument(url,"_blank"); Try something like this: url="http:/foo/upload.py?id=" + id + "&nodeID=" + nodeID .... thomas From boud at valdyas.org Thu Sep 26 05:10:06 2002 From: boud at valdyas.org (Boudewijn Rempt) Date: Thu, 26 Sep 2002 11:10:06 +0200 Subject: unicode woes References: Message-ID: <3d92d120$0$76313$e4fe514c@dreader4.news.xs4all.nl> Ulli Stein wrote: > > Some weeks ago the management decided to deploy unicode so that we can > handle every charset uniformly. The problem which showed at first: we > realized that we cannot change the encoding in site.py afterwards, i.e. we > have to specify the encoding all the way. Use a sitecustomize.py file that contains: import sys sys.setappdefaultencoding=sys.setdefaultencoding Then, in the application starter script use: if hasattr(sys, 'setappdefaultencoding'): sys.setappdefaultencoding('utf-8') elif sys.getdefaultencoding() != 'utf-8': print 'Warning: encoding not set for unicode - see ReadMe file' That should solve a lot of your problems. Then you need to carefully determine how the data that enters and leaves your application should be encoded. For instance, you might be getting data from files, databases, network or paste operations. If that data is many different encodings, you need to check the encoding at every entry point. And whenever you write data, you need to be aware of the encoding. But at least _inside_ your application all data will be utf-8, which makes it easy to handle. Don't be too sanguine about the unicode handling of Java, by the way. Lots of room for hard-to-find unicode-related bugs there. > It got worse and worse because > the unicode encoding spread like a virus through all the source code. > Simple Exceptions which we wanted to print to the console throw another > Exception: > UnicodeError: ASCII decoding error: ordinal not in range(128) Other people will be able to tell you why it was a good design decision to make it difficult to set a default application encoding different from ASCII. I'm still not convinced, but that might be just my denseness. -- Boudewijn Rempt | http://www.valdyas.org From solonas73 at hotmail.com Tue Sep 17 03:05:52 2002 From: solonas73 at hotmail.com (Solon Kazantzidis) Date: 17 Sep 2002 00:05:52 -0700 Subject: upload/download to a palm os device with python References: <24165ed4.0209160304.7a3c08af@posting.google.com> Message-ID: <24165ed4.0209162305.3925451e@posting.google.com> Hello, thank you for the information. Grzegorz Makarewicz wrote in message news:... > sf.net/projects/pilot-link - for Palm palms with http://www.pyrite.org/ > for offline database manipulations. > > wincerapi for Windows CE devices I tried to locate the pilot-link package. It is nomore at sourcefourge. Now you can find it at: www.pilot-link.org I downloaded the pilot-link-0.11.4.tar.gz file. Configured/Build/Installed then build the python module pisock but somehow I miss a documentation or examples for its usage. Any ideas where to find programming examples which show the usage of the pisock lib ? Thanks for your postings, Solon. From wlfraed at ix.netcom.com Mon Sep 30 13:55:59 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Mon, 30 Sep 2002 10:55:59 -0700 Subject: Catching user defined exceptions from foreign modules References: Message-ID: Derek Basch fed this fish to the penguins on Monday 30 September 2002 08:59 am: > to have to import user defined exceptions? I dont > rememeber having to import any of the built in > exceptions. So, here is the output of the fixed test1: > "built-in" -> already there... > test2.TestError > fudge > > Am I doing this all wrong? You want to use items defined in an imported module. I see three alternatives... import module all uses then become module.item from module import item1, item2, ... itemN only the named items are useable, but can be used as itemM from module import * practically everything within the module is available as item The last is not recommended as you can encounter unexpected redefinition of names... In the last week we had one such... from os import * replaces the Python open() (which I understand is being phased out for file()) with the low-level (C-style) open -- totally different arguments needed. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From jb at cascade-sys.com Thu Sep 26 02:19:06 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 25 Sep 2002 23:19:06 -0700 Subject: Getting started References: <00a801c26511$4e084750$df7e4e18@brianspiv1700> Message-ID: <3D92A6DA.3020501@cascade-sys.com> Brian Quinlan wrote: >>Some use "weak typing" to mean any type system where the typing can be >>foiled by casts; >> >> > >What does "foiled by" mean in this context? > Bypassed or otherwise defeated. A "cast" in C or C++ is a way to override the type system. Sometimes this is meaningful and useful but it also can result in catestrophic type errors. Types are otherwise pretty secure in C++ except the "cast" mechanism "foils" the type system and thus allows type errors to occur. An earlier example was: CEdit* edit = (CEdit*)GetDlgItem( ID_EDIT ); This fetches a pointer to user interface "dialog item" from the existing GUI. Such objects may be of different types. GetDlgItem() returns a pointer to a generic CWnd type, which is the super class to all the possible window objects.. The (CEdit*) is a cast says to convert the pointer from whatever it may have been (one for a generic windows object) to specifically be an Edit Box object. If all goes well then this works just fine. However, if the dialog item happens NOT to be an edit box, say if it was a list box instead, then the resulting object pointer would point to the wrong object type and likely result in a fatal error when list box operations are applied to the edit box object. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From misterxx at uni-koblenz.de Mon Sep 2 04:39:23 2002 From: misterxx at uni-koblenz.de (Oleg Seifert) Date: Mon, 02 Sep 2002 10:39:23 +0200 Subject: wie greife ich mit Python auf die c-bibliotheken zu ? Message-ID: <3D7323BB.4070200@uni-koblenz.de> hallo Leute, k?nnte vielleicht jemand es mir an einem Beispiel zeigen. Ich habe als Attachments zwei kleine Anwendungen dazu geschickt. danke im Vorraus, Oleg -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: punkt.cpp URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: punkt.py URL: From sschwarzer at sschwarzer.net Wed Sep 11 17:03:15 2002 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Wed, 11 Sep 2002 23:03:15 +0200 Subject: "str.contains(part)" or alternatives? References: Message-ID: Hi Steve :) Steve Holden wrote: >> >>> s = 'Hello' >> >>> if s.contains('ll'): >>... do_something_if_found() >>... else: >>... do_something_if_not_found() >> >>Do you have other suggestions how to do the test easily without using special >>values? Should a .contains method be part of string objects in future Python >>versions? What do you think? > > I think the current proposal is to move to > > if ll in s: > > for this construct. Happy? I would like .contains more, but at least the proposal is _much_ better than "if s.find(part) != -1". :-) "if part in s" disturbs the pattern "if item in sequence" somewhat but that has already been weakened by "if key in dict" (that I like, nonetheless). Stefan From skpeternospam at ucdavis.edu Mon Sep 30 00:19:39 2002 From: skpeternospam at ucdavis.edu (Sam Peterson) Date: 30 Sep 2002 00:19:39 -0400 Subject: Subclass SGMLParser or HTMLParser? Message-ID: Hello, I've just started doing some python programming with htmllib.HTMLParser to spider a website of mine and grab all of the images and download them to disk, as well as collecting reference counts for my hyperlinks. It works pretty well, except on a few web pages that were generated with Word and most of these pages don't contain images or anchor tags and I imagine the HTMLParser module meant for XHTML documents will handle those just find once I get around to playing with it. My questions is, after having looked around on the web for examples, I've noticed that most people seem to use sgmllib.SGMLParser instead. I know that htmllib.HTMLParser is just a subclass of SGMLParser, therefore I was wondering what the pros and cons are to using one or the other. Any recommendations? Thanks in advance. -- Sam "Da Man" s/nospam/son/ -- to email me. From DennisR at dair.com Tue Sep 17 10:59:32 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Tue, 17 Sep 2002 14:59:32 GMT Subject: Windows AutoRunning Python Hello -- feedback requested References: <3D86DE3A.2040903@mxm.dk> Message-ID: > To high level to be a short learning example, In time, I can fix this. > It will probably be interresting to only a small subset of developers. That seems to be the story of my life :-) Thanks for your comments. -- Dennis Reinhardt http://www.dair.com From warkid at storm.ru Fri Sep 6 08:17:15 2002 From: warkid at storm.ru (Kerim Borchaev) Date: Fri, 6 Sep 2002 16:17:15 +0400 Subject: .py to .pyc In-Reply-To: References: Message-ID: <2678.020906@storm.ru> Hello andrea, Friday, September 06, 2002, 12:25:14 PM, you wrote: abrn> Hi everybody, abrn> I'm a python newbie and i've a problem. abrn> I want to compile a python file called File.py and i want to produce a file abrn> called File.pyc, so i do abrn> python File.py abrn> I always find the following error: abrn> Traceback (most recent call last): abrn> File "File.py", line 18, in ? abrn> import Globals, StructuredText, string, utils, re abrn> ImportError: No module named Globals abrn> Can anybody help me to find the problem? I think it's a problem of abrn> $PYTHONPATH and $PYTHONHOME but i'm not sure. abrn> Please...help! abrn> Thanx in advance abrn> Andrew You could use py_compile module like this: ##test.py############ fname = 'test_module.py' src = 'import this_module_does_not_exist\n' open(fname, 'w').write(src) import py_compile py_compile.compile(fname) print `open(fname+'c').read()` ############# so just do: import py_compile py_compile.compile('File.py') Best regards, Kerim mailto:warkid at storm.ru From tjreedy at udel.edu Sat Sep 7 18:20:04 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 07 Sep 2002 22:20:04 GMT Subject: Converting python object reference to int and back References: <3D79AC95.1000000@NOSPAMbitbuilder.com> Message-ID: "Ahmad Baitalmal" wrote in message news:3D79AC95.1000000 at NOSPAMbitbuilder.com... > Hi, > I need to keep references to python objects in a tree control's item. This is what Python does for you behind the scenes, automatically, without error, every time you assign abject to a name or slot. > The items can hold an integer as data. > How can I get an id (pointer/reference) from a python object and then > get that object back using that integer? You almost certainly do not want to do this since it amounts to duplicating, in a clumsy way, what the interpreter already does for you. Terry J. Reedy From alanmk at hotmail.com Thu Sep 26 10:06:56 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: 26 Sep 2002 07:06:56 -0700 Subject: Page describing http compression with gzip. Message-ID: Hi All, A few months ago, after spending a couple of days troubleshooting gzip compression over HTTP, I put together a page describing how to do HTTP compression in python, which included some sample code for CGI and mod_python. For completeness, I have now added some sample code for jython servlets to that page. Also, I have moved the page to a new location, namely http://xhaus.com/alan/python/httpcomp.html Lastly, I have created a facility for checking HTTP headers, at the following address http://xhaus.com/headers Sincerely, alan kennedy ---------------------------------------------- check http headers here: xhaus.com/headers email alan: xhaus.com/mailto/alan From 2002 at weholt.org Thu Sep 19 18:48:15 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Thu, 19 Sep 2002 22:48:15 GMT Subject: Suggesting a filename on a HTTP-request by sending someting in the header of the reply Message-ID: I got a simple webserver serving files, but the files are found using lookup based on ids ( like http://localhost/dl?id=10, where 10 is a key in a dictionary pointing to a file ), not their filename so when I send content-type = 'application/octet-stream' in the headers to the client I get the proper "Save as ..."-dialog, but the filename is all screwed up. It seem to be the "dl"-part of the url above. I've tried to read the RFC 2616-document and sent "Content-Disposition"-headers etc. but with no luck. What headers do I need to send for it to get the proper filename in the "Save as ..."-dialog? Say for instance that the filename I wanted the client to save the file as was "test.zip". Any hints? Best regards, Thomas From mstenner at phy.duke.edu Wed Sep 4 20:31:47 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Wed, 4 Sep 2002 20:31:47 -0400 Subject: simple xml pickle In-Reply-To: <20020904132951.A7928@phy.duke.edu>; from mstenner@phy.duke.edu on Wed, Sep 04, 2002 at 01:29:51PM -0400 References: <20020904132951.A7928@phy.duke.edu> Message-ID: <20020904203147.A9032@phy.duke.edu> On Wed, Sep 04, 2002 at 01:29:51PM -0400, Michael Stenner wrote: > The xml marshalling does almost exactly what I want, and the > modifications to make it "standalone" for Python 2.2 were very easy > (patch forthcoming) so I may just stick with that. Nonetheless, I'll > look at xml_pickle again and see what I can see. Results: With David's hint, xml_pickle.py was also fairly easy to make work with python 2.2 in a standalone fashion. Here are the patches to make both the PyXML marshaller and xml_pickle.py work as standalone files with python 2.2 (probably 2.x, but I haven't tested it). I haven't really tested either of these. I just tweeked them so that they passed their own built-in tests. generic.py.diff should be applied to xml.marshal.generic.py from PyXML 0.8. xml_pickle.py.diff should be applied to xml_pickle.py 0.51. Now I just need to decide which I want to use :) -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 -------------- next part -------------- --- generic.py.orig Wed Sep 4 20:19:58 2002 +++ generic.py Wed Sep 4 10:34:45 2002 @@ -6,7 +6,12 @@ from types import * import string -from xml.sax import saxlib, saxexts +import xml.sax +from xml.sax.handler import EntityResolver, DTDHandler, ContentHandler,\ + ErrorHandler + +class HandlerBase(EntityResolver, DTDHandler, ContentHandler,\ + ErrorHandler): pass # Basic marshaller class, customizable by overriding it and # changing various attributes and methods. @@ -20,7 +25,7 @@ return cmp(ta.__name__, tb.__name__) return cmp(a,b) -class Marshaller(saxlib.HandlerBase): +class Marshaller(HandlerBase): # XML version and DOCTYPE declaration PROLOGUE = '' DTD = "" @@ -251,7 +256,7 @@ TUPLE = {} ; LIST = {} ; DICT = {} -class Unmarshaller(saxlib.HandlerBase): +class Unmarshaller(HandlerBase): # This dictionary maps element names to the names of starting and ending # functions to call when unmarshalling them. My convention is to # name them um_start_foo and um_end_foo, but do whatever you like. @@ -314,9 +319,9 @@ def _load(self, file): "Read one value from the open file" - p=saxexts.make_parser() - p.setDocumentHandler(self) - p.parseFile(file) + p=xml.sax.make_parser() + p.setContentHandler(self) + p.parse(file) assert len(self.data_stack) == 1 # leave the instance in a steady state result = self.data_stack[0] @@ -358,9 +363,9 @@ sm, em = self.unmarshal_meth[ name ] if sm is not None: return sm(name,attrs) - def characters(self, ch, start, length): + def characters(self, ch): if self.accumulating_chars: - self.data_stack[-1].append(ch[start:start+length]) + self.data_stack[-1].append(ch) def endElement(self, name): # Call the ending method -------------- next part -------------- --- xml_pickle.py.orig Tue Sep 3 18:38:48 2002 +++ xml_pickle.py Wed Sep 4 20:18:34 2002 @@ -206,7 +206,7 @@ '\n', '\n' % (_klass(self.py_obj),id_)] - for name in dir(self.py_obj): + for name in self.py_obj.__dict__.keys(): xml_lines.append(_attr_tag(name, getattr(self, name))) xml_lines.append('\n') return string.join(xml_lines,'') @@ -226,36 +226,36 @@ # Add all the subnodes to PyObject container container = thing_from_dom(node, obj_from_node(node)) try: - id = node.attributes[('', 'id')].value + id = node.attributes['id'].value visited[id] = container except KeyError: pass elif node.nodeName == 'attr': try: - node_type = node.attributes[('','type')].value + node_type = node.attributes['type'].value except: print "node", node.attributes, repr(node.attributes) print node.attributes.keys() raise ValueError # WHAT?! - node_name = node.attributes[('', 'name')].value + node_name = node.attributes['name'].value if node_name == '__parent__' and EXCLUDE_PARENT_ATTR: # Do not pickle [xml_objectify] bookkeeping attribute pass elif node_type == 'None': setattr(container, node_name, None) elif node_type == 'numeric': - node_val = safe_eval(node.attributes[('','value')].value) + node_val = safe_eval(node.attributes['value'].value) setattr(container, node_name, node_val) elif node_type == 'string': - node_val = node.attributes[('','value')].value + node_val = node.attributes['value'].value node_val = unsafe_string(node_val) setattr(container, node_name, node_val) elif node_type == 'list': subcontainer = thing_from_dom(node, []) setattr(container, node_name, subcontainer) try: - id = node.attributes[('', 'id')].value + id = node.attributes['id'].value visited[id] = subcontainer except KeyError: pass @@ -263,7 +263,7 @@ subcontainer = thing_from_dom(node, []) # use list then convert setattr(container, node_name, tuple(subcontainer)) try: - id = node.attributes[('', 'id')].value + id = node.attributes['id'].value visited[id] = subcontainer except KeyError: pass @@ -284,7 +284,7 @@ subcontainer = thing_from_dom(node, {}) setattr(container, node_name, subcontainer) try: - id = node.attributes[('', 'id')].value + id = node.attributes['id'].value visited[id] = subcontainer except KeyError: pass @@ -292,16 +292,16 @@ subcontainer = thing_from_dom(node, obj_from_node(node)) setattr(container, node_name, subcontainer) try: - id = node.attributes[('', 'id')].value + id = node.attributes['id'].value visited[id] = subcontainer except KeyError: pass elif node_type == 'mxDateTime': - parts = node.attributes[('','value')].value.split() + parts = node.attributes['value'].value.split() node_val = apply(mx.DateTime.DateTime,map(float,parts)) setattr(container, node_name, node_val) elif node_type == 'ref': - ref_id = node.attributes[('', 'refid')].value + ref_id = node.attributes['refid'].value setattr(container, node_name, visited[ref_id]) elif node.nodeName in ['item', 'key', 'val']: @@ -310,12 +310,12 @@ # all cases, elif's are defined for mutable types. Furthermore, # there should only ever be *one* item in any key/val list, # but we again rely on other validation of the XML happening. - node_type = str(node.attributes[('','type')].value) + node_type = str(node.attributes['type'].value) if node_type == 'numeric': - node_val = safe_eval(node.attributes[('','value')].value) + node_val = safe_eval(node.attributes['value'].value) container.append(node_val) elif node_type == 'string': - node_val = node.attributes[('','value')].value + node_val = node.attributes['value'].value node_val = unsafe_string(node_val) container.append(node_val) elif node_type in ('list',array_type): @@ -331,7 +331,7 @@ subcontainer = thing_from_dom(node, obj_from_node(node)) container.append(subcontainer) elif node_type == 'mxDateTime': - parts = node.attributes[('','value')].value.split() + parts = node.attributes['value'].value.split() node_val = apply(mx.DateTime.DateTime,map(float,parts)) container.append(node_val) @@ -350,7 +350,7 @@ # Get classname of object (with fallback to 'PyObject') try: if node.attributes: - klass = node.attributes[('','class')].value + klass = node.attributes['class'].value else: klass = 'PyObject' except KeyError: klass = 'PyObject' @@ -452,7 +452,7 @@ visited[id(thing)] = 1 start_tag = start_tag + 'type="PyObject" class="%s" id="%s">\n' \ % (_klass(thing), id(thing)) - for name in dir(thing): + for name in thing.__dict__.keys(): tag_body.append(_attr_tag(name, getattr(thing, name), level+1)) elif '%s' % type(thing) == "": # SRE_Pattern objects are extension objects, so not From mertz at gnosis.cx Wed Sep 25 12:25:25 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 25 Sep 2002 12:25:25 -0400 Subject: Python Compiling References: <80a8af7d.0209250113.28ae4c72@posting.google.com> Message-ID: <1Nek9kKkX0+P092yn@gnosis.cx> Alex Martelli wrote previously: |Or Haskell, www.haskell.org -=- HUGS inteprets it, the Edinburgh |compiler compiles it. Scheme has _many_ interpreters and compilers |too. Hey, so does Visual Basic... it's quite the thing these days. Wrong Scottish city, I'm afraid. Alex probably means the GLASGOW Haskell Compiler (GHC). There's also NHC and HBC available, but GHC seems like where the real focus is. Yours, Lulu... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From sholden at holdenweb.com Wed Sep 25 09:12:54 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 25 Sep 2002 09:12:54 -0400 Subject: Getting started References: Message-ID: "James J. Besemer" wrote in message news:mailman.1032567390.29374.python-list at python.org... > > Alex Martelli wrote: > > >$a = "2.3"; > >$b = 45; > >print $a+$b; > > > >emitting 47.3 is pretty close to what I consider "weak typing". > > > > I don't see why you call this "weak typing". In Perl, the "+" operator > is defined to work with strings or numbers. Well, it seems pretty weak to me that the *operator* has to examine the types of its arguments in order to know which operation to perform. Can we say polymorphism? > It may seem more confusing > at first if you expect "+" also to be the string concatenation operator, > which it is not. In the above example, > > print $a . $b; > > will print the string "2.345". > How very intuitive. I am happy to say I have now forgotten enough Perl for this to seem totally unreasonable. I usually don't say these things about Perl because it, too, is a pragmatist's language, and Perl is fine for the things Perl is fine for. If it's working for someone I can't in all conscience disturb their busy working day to suggest they rewrite it all in Python. > This all is no different in principle from Python's: > > a = 2.3 > b = 45L > print a + b > > and getting 47.3. The "+" operator is defined for floats and also for > longs. Since they're all "numbers" it would seem really strange if they > did not interact naturally like this. But fundamentally they're > distinct types as "type( 2.3 )" and "type( 45L )" illustrate. > It seems very different to me. For example, how does the Perl "+" operator find out about a new addable type? Is Perl even able to integrate its intrinsic data objects with user-defined types? Can we say inheritance hierarchy? In Python it's easy to define methods to integrate your own classes into the language's architecture. I could never discern enough architecture in Perl to see how to do that, though I willingly accept that this deficiency might be in me rather than in Perl. > Perhaps an even better example is the "*" operator: > > print 2 * 5 # integer x integer -> integer > print [2] * 5 # list x integer -> list > print "2" * 5 # string x integer -> string > > This all makes sense even though radically different results and result > types are produced each time. It's not "weakly typed" but rather > strong, dynamic typing. The outcome is completely determined by the > operator and the types of the operands and there is no way to break the > rules. Since we know Python is strongly typed then it follows that your > Perl example must be also. Not really. Python has strongly-typed data with late binding of methods and operators. This is an organised way to obtain the results you have so far quoted. > > Anyway, why should "2" + 5 == "7" be all that much stranger than "2" * 5 > == "22222"? If the operation is unambiguous and useful what rule would > it break? Personally, I think Python would be improved slightly by > adding this conversion. It's convenient and there's ample precedent in > other languages (Awk, Snobol, Icon, Perl, etc.). But I am sure that > notion will provoke howls of protest from the True Believers. > Not at all. If I thought such a suggestion would be taken seriously I might go so far as to advise against that, but I don't see this being a religious debate. > There are a lot of reasons why Python is better than Perl but strongly > vs. weakly typed is not one of them. I don't see a material difference > in the "strength," per se, of typing between Perl and Python. They're > both "strong" and "dynamic", though Python's type model is better > thought out, particularly since object/type unification. > [C/Fortran irrelevancies] > > These types of errors are not possible in Python or Perl, which > illustrates that they're both "strong". > For some meaning of strong, I suppose, but please don't bother to define what this is. > Curiously, in Python > > print "%s" % 2.5 > > prints the string "2.5" instead of, say, raising an exception. So > there's some small precedent for treating numbers as strings in a string > "context" even in Python. > Well, considering that the %r and %s conversion types are currently documented as """ r String (converts any python object using repr()). s String (converts any python object using str()). """ it should hardly be surprising that conversions take place. Such conversions, however, are not intrinsic to the *language*, but to the *data* (where the type is significant) - Python goes so far as to expose explicitly how the conversions are performed, and they will clearly work for any object with a suitable (returns a string) __repr__() and/or __str__() method. Just to clarify the nature of this, try "%6.2f" % 2.6 and then try "%6.2f" % "2.6" and we'll see if you still feel that string formatting 'treats numbers as strings in a string "context"'. By contrast Perl seems a little muddled, and I personally think it's no accident that Wall's own writing tends to stress the significance of *context*. The rules are quite explicit in Python, clouded in Perl. Of course you must take this as a dim memory frmo one who never claimed to understand Perl that well in the first place (I used to program Perl, but I'm all right now ;-). > I'll go out on a limb and say that most "dynamic typed" languages are > also "strong" by necessity. If the user isn't keeping track of the > types then the system HAS to. An exception I can think of would be an > ancient dialect of Lisp where integers also were machine addresses and > thus callable without restriction. E.g., if a function name evaluated > to a number the interpreter performed a subroutine call to that address > instead of, say, applying a lambda. It was the mechanism through which > system builtins were accessed. However, nothing prevented a user from > "calling" an arbitrary integer and leaping off into never never land. > I seem to have lost track of what "dynamic typed" and "strong" mean. Sorry. > "Strong typing" (the "static" kind) is also the norm in Pascal and C++. > I like to think of strong typing as the norm in ANSI C but there is > still optional and thus may be considered "weak". Furthermore, C > programmers are on the "honor" system across module boundaries, as > there's no link time checking. There even are ways to cheat in C++, so > some might still class it as a "weakly typed" language. Of course, with > discipline, it's possible to avoid the pitfalls and always use the > strong typing facilities of C and with effort enjoy most of the benefit. > It's also possible to enjoy some of the benefits of prison by simply refusing to go outside. Your very confession of C's and C++'s weaknesses highlights the fact that even "strongly typed" languages have problems enforcing the rules (whose value I anyway challenge except for the specific promotion of execution efficiency). Python is just a bit less anal :-) > >I > >find it very hard to produce substantial, large programs using > >weakly-typed languages. > > > Given my definition of "weakly typed," I agree it's more difficult than > in strongly typed languages. > > On the other hand, isn't it the case that much of Python is implemented > in C, which is weakly typed? So "weakly typed" makes it harder but not > impossible, at least not for some. > You can write structured programs in assembler. This does not make it the ideal vehicle for a GUI-based commercial accounting system. Python is an object-oriented environment implemented in C. Ultimately C is compiled into machine code. What's your point? Once the Turing completeness of von Neumann architectures is accepted the rest is merely linguistic anthropology: what a system can do is, ultimately, more important to its users than how it does it (which is a significant concern of the implementors). > > Python is strongly, albeit dynamically, typed, > > > FWIW, so is Perl. > But not, IMHO, in the same way. > >Unfortunately, some seminal material of a few > >decades ago confused terminology (I vaguely remember something > >about it in some early article about Scheme, for example). > > > I think you're right. I originally learned a different taxonomy for > many of these concepts. > Well, we all have to watch out for Humpty Dumpty in our own output. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From amk at amk.ca Thu Sep 19 19:51:55 2002 From: amk at amk.ca (A.M. Kuchling) Date: Thu, 19 Sep 2002 23:51:55 -0000 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: In article , Michael Chermside wrote: > (5) Good reasons exist why Stackless CANNOT be implemented in Jython, > in Python for .NET, or other Python implementations -- it's a > C-Python-only thing. Note that the Parrot VM is already stackless, so a hypothetical Python running on Parrot would be stackless from the start. --amk From hellprout at yahoo.com Sat Sep 21 05:55:38 2002 From: hellprout at yahoo.com (hellprout) Date: 21 Sep 2002 02:55:38 -0700 Subject: siebel and python Message-ID: <5b8834c2.0209210155.5ae21270@posting.google.com> hi , i'm working on siebel , i use vb to charge data in siebel but i want to use python with win32com i can't load the cfg file and login on siebel what can i do ? i just want to have example thanks a lot From rsrchstr at msn.com Sun Sep 29 21:23:07 2002 From: rsrchstr at msn.com (mike henley) Date: Mon, 30 Sep 2002 02:23:07 +0100 Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> Message-ID: Just brainstorming on one possible way to do it; please advise if you have: what would such a script/application do? it would start up with my computer, simply insert itself in my start-up folder or whatever it would just wait and detect when i go online then it when i do get online it would detect what my IP is and when if i'm disconnected then it will detect that too and when if i'm reconnected it would detect that too and detect my IP or it can just simply do this at regular intervals then it would use jabber/xml-rp or whatever to make a presence for me/my-webapplication on IM networks using a username or account name that i can give to others so that this way the webapplication will have "presence" so others will know when the webapplication is online and then if they IM it it'll reply with my IP so it appears in the IM as a hyperlink that they can click to launch their default browser to a url consisting of http://myIP and then perhaps if they wish to be automatically notified of the webapplication's presence they can insert their username on a form on the webapplication when they get their which will add it to its buddylist or even within the first IM they get from it there can be a link that if they wish to click on will detect and add their username automatically (as an option) or they reply with a message such as "add me" which will do that and either way they can be added, if they wish, to the webapplications buddylist so next time it goes online it can send them an IM automatically of course it should enable them to remove themselves from the buddylist later on if they wish sounds very much like a jabber bot perhaps i can get an open source one and extend or customize it got any better ideas or there's something wrong in what i have written? please tell me, i have read about jabber yet. "mike henley" wrote in message news:an87db$bjtvs$1 at ID-157863.news.dfncis.de... > i guess i'll rephrase; what i wish for is an "application-to-person" (P2A) > IM-based "presence", so that a web-application that i host on a personal > webserver, on my own machine, can let others become aware of its "presence" > easily and be easy to connect to with a simple > click-to-launch-browser-and-go-to-my-ip. This should be easy to do. I just > don't have experience with Jabber or xml-rpc, or other potential useful > technologies. From eppstein at ics.uci.edu Mon Sep 16 11:58:17 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Mon, 16 Sep 2002 08:58:17 -0700 Subject: Are generator functions thread-safe? References: Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > >I know that a call to a generator function actually returns an independent > >iterator object (mea culpa if I'm wrong on this), but are there any hidden > >gotchas that would cause the use of the same generator function from > >multiple threads, to result in a sharing (especially local storage) or > >memory collision issue? > > The same gotchas for any other function: you're screwed if you share > mutable objects without locks. Also, if a call to the generator object is running from one thread, you will get an exception if you attempt to simultaneously call it (e.g. from another thread). I don't know how thread-safe is the code that prevents the generator from being called twice simultaneously, though. -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From bdesth at nospam.free.fr Fri Sep 6 21:30:46 2002 From: bdesth at nospam.free.fr (laotseu) Date: Fri, 06 Sep 2002 21:30:46 -0400 Subject: Grumble about too strict an attitude about backward compatibility... References: <3D77F98B.3050607@nospam.free.fr> Message-ID: <3D7956C6.6040800@nospam.free.fr> Skip Montanaro wrote: > >> What's the Python connection? Other than a reminder not to get to > >> slavish about backward compatibility, I note that these same function > >> names will then go on to pollute the Python namespace because all > >> this Fortran code is automatically wrapped using f2py. > > laotseu> Well, that may be true, but the chances of a name collision are > laotseu> pretty low IMHO... > > Name collisions weren't what I was getting at. Python allows essentially > unlimited identifier lengths, but people manipulating these functions from > Python code still have to use the cryptic 4-6 character names. Perhaps f2py > allows mapping such names to something more meaningful. (One can hope. ;-) > > Skip > > > mapping such names to something more meaningful ? aFunctionWithAnySensibleName = lpni aFunctionWithAnotherSensibleName = klvna if aFunctionWithAnySensibleName(andFarTooMuchLettersInIt): resutl = aFunctionWithAnotherSensibleName(andAlsoManyUselessLetters) Like this ?-) laotseu -- The Old Master said : "function names are always too long... unless they are too short" -- From aleax at aleax.it Fri Sep 20 11:09:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 15:09:16 GMT Subject: bit operations ? References: Message-ID: Shagshag13 wrote: > hello, > > i'm looking for any libs which could handle bit operations on integer. > (i must be able to get 0 to n bits from any int., only bit j, etc.) gmpy does the two ops that you require -- functions lowbits and getbit respectively. No 'etc', though. Alex From jlkeating at clear.net.nz Fri Sep 6 03:21:45 2002 From: jlkeating at clear.net.nz (jlkeating) Date: Fri, 6 Sep 2002 19:21:45 +1200 Subject: A special excite game Message-ID: <20020906072045.RPBB9205.mta3-rme.xtra.co.nz@Hatmsluq> An HTML attachment was scrubbed... URL: -------------- next part -------------- ------------------ Virus Warning Message ------------------ install.exe is removed from here because it contains a virus. ------------------------------------------------------------- -------------- next part -------------- A non-text attachment was scrubbed... Name: SQLSRDME.TXT Type: application/octet-stream Size: 13228 bytes Desc: not available URL: -------------- next part -------------- ------------------ Virus Warning Message ------------------ Found virus WORM_KLEZ.H in file install.exe The uncleanable file is deleted. ------------------------------------------------------------- From david.g.morgenthaler at lmco.com Tue Sep 3 22:03:12 2002 From: david.g.morgenthaler at lmco.com (Dave M.) Date: 3 Sep 2002 19:03:12 -0700 Subject: Jython and zxJDBC package References: <23891c90.0209020013.b05e81c@posting.google.com> Message-ID: <71ec32f3.0209031803.2d0d245@posting.google.com> > > Is anyone here using the zxJDBC package as described in "Jython > > Essentials" to access a MySQL database? > > > > When I try to run the sample program (Example 10-1, p. 164), I receive > > a NoClassDefFoundError: org/gjt/mm/mysql/Statement in > > MySQLDataHandler. Decompiling MySQLDataHandler reveals an explicit > > reference to org.gjt.mm.mysql.Statement; but this class isn't in the > > Connector/J library. Am I missing something here? > > > > I'm using Jython 2.1 and Connector/J 2.0.14. > > It looks like MySQLDataHandler wants to use the MM.MySQL package, > which can be found here: > > http://sourceforge.net/projects/mmmysql > The example in the book does indeed expect the use of MySQL. I don't know about Connnetor/J, but, for example, the following works with Sun's JDBC-ODBC bridge driver talking to an Access database: ----------code------- import com.ziclix.python.sql as sql dburl, user, pw, drv = ("jdbc:odbc:testTrack","", "","sun.jdbc.odbc.JdbcOdbcDriver") db = sql.zxJDBC.connect(dburl, user, pw, drv) cursor = db.cursor() #cursor.datahandler = sql.handler.MySQLDataHandler(cursor.datahandler) cursor.execute("SELECT * FROM trackTable") for item in cursor.fetchall(): print item -----------end code---------- Be sure that, e.g., sun.jdbc.odbc.JdbcOdbcDriver is on your Jython path. Note also the setting of a specific datahandler is commented out. zxJDBC ships with custom drivers for Oracle (sql.handler.OracleDataHandler), Informix (sql.handler.InformixDataHandler), Postgresql (sql.handler.PostgresqlDataHandler), and SQLServer (sql.handler.SQLServerDataHandler) in addition to the MySQLDataHandler. If you're not using one of these, the default data handler will work. From andy at agmweb.ca Tue Sep 24 23:51:36 2002 From: andy at agmweb.ca (Andy McKay) Date: Tue, 24 Sep 2002 20:51:36 -0700 Subject: Zope Documentation and example sites References: <503511c2.0209230758.74a64a3d@posting.google.com> <9bf19f33.0209241810.1fbd28f5@posting.google.com> Message-ID: <00ea01c26446$d9a7db20$89505018@cr582427a> > I would like to find some working examples that use CMF. Does anyone > know of any? http://zopezen.org is in the CMF and has links to a bunch of other sites, not necessarily using CMF. -- Andy McKay Agmweb Consulting www.agmweb.ca From martin at v.loewis.de Mon Sep 2 01:54:41 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Sep 2002 07:54:41 +0200 Subject: va_list warnings on Solaris? References: Message-ID: Neal Norwitz writes: > I get this as well. I believe the warning started after I upgraded Solaris, > but I'm not sure. I didn't build gcc locally. If I remember correctly > the collision was between a gcc header file (stdarg.h shown above) and > a Solaris header file in /usr/include. If you upgrade Solaris, you really need to rebuild gcc, for that Solaris version. gcc installation will run fixincludes, copying the system headers. It frequently happened that using fixincluded headers from an older Solaris version caused very obscure bugs. Skip's report seems to indicate that he indeed built gcc for his system. I'd be curious to see one more line of error messages though (hoping to get a line like "previous definition here"). Regards, Martin From michael at stroeder.com Wed Sep 18 10:19:35 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 18 Sep 2002 16:19:35 +0200 Subject: Earing money with Python software (was: More on Protecting Source Code) References: Message-ID: brueckd at tbye.com wrote: > free-for-personal-use-but-companies-must-pay approach when possible. The problem with getting some bucks from a company is the amount of time spent during decision taking and ordering process. For you to earn 300 bucks for your software the company spends another 500+ bucks for working time until the money gets out. IMHO that's why it's so hard to sell small packages of rather cheap software to big companies. Ciao, Michael. From Tom_Good1 at excite.com Wed Sep 11 16:25:18 2002 From: Tom_Good1 at excite.com (Tom Good) Date: 11 Sep 2002 13:25:18 -0700 Subject: ANN: Thinking in Tkinter References: Message-ID: steve at ferg.org (Stephen Ferg) wrote in message news:... > A small page devoted to "Thinking in Tkinter" > at http://www.ferg.org/thinking_in_tkinter/index.html Cool stuff. A couple of comments: 1. You might want to point out that we can enter and experiment with simple Tkinter scripts interactively in PythonWin or IDLE. This may not be obvious to users who are new to Python. There is something satisfying about typing "root.mainloop()" into the interactive window and seeing the Tkinter window immediately pop up :-) 2. In section (1) of tt020.py, it says 'The constructor method recognizes the root under the name "parent".' I think you meant to say, 'under the name "myParent".' Tom From kwdotbenninkNOSPAM at 12move.nl Fri Sep 20 11:07:32 2002 From: kwdotbenninkNOSPAM at 12move.nl (Highwaykind) Date: Fri, 20 Sep 2002 17:07:32 +0200 Subject: Newbia alert .. working my way through Easy Python Montana Edu page, need help.. References: Message-ID: Thank you very much ! It's working now :) After I finished the tutorial I'll try to translate it into Dutch ( which makes it even easier for me and probably other Dutch people .. ) Didn't know what an indentation was ( desperately looking for a dictionary LOL ). Will go on with the tutorial .. and if I get stuck again and can;t figure out what I've done wrong this time I'll be back .. on my way to becoming a progammer .. in 2010 or so :) Corien > Highwaykind wrote: > ... > > def print_options() : > > You define this function, but never call it anywhere. > > > choice = 'p' > > while choice != 'q': > > if choice == 'r': > > a=input ("width") > > b=input ("height") > > print "result",rect (width,height) > > Note that the print is NOT aligned with the input calls, but > rather with the if statement. Thus, the print (and its call > to rect) is not conditional -- it happens even when choice > is NOT 'r'. This is unlikely to be what you want, so, indent > this print statement 4 more spaces rightwards. > > However, the crux of your problem is another: > > > But the thing keeps telling me width is not defined, also I can;t use > > Inddeed, width is not a defined variable: what you obtained > from the call to input("width") you did not assign to the > name width, but rather to the name a. Therefore, the variable > that is defined once this statement has executed is named a. > > Therefore, change your call to rect to rect(a,b) -- and > similarly for the following passages in your code. > > > the ELIF command .. THink I could do with some help :) > > The reason you can't use elif (not a 'command' -- a clause > in an if statement) is probably the indentation problem I > mentioned earlier -- once you fix that you can probably > also change the following if's to elif's (not the first one > of course). When indentation returns to the same level as > the word 'if', it means the if statement is over: therefore > you cannot "reprise" it later, continuing it, so to speak, > with an elif clause. Once you correct the indentation of > the print statements, this will change. > > > Alex > > -- For the correct e-mail address : remove NOSPAM and replace dot with . From mcfletch at rogers.com Thu Sep 12 22:24:42 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Thu, 12 Sep 2002 22:24:42 -0400 Subject: Piper Pickling? References: Message-ID: <3D814C6A.6050902@rogers.com> Strangely enough, I just spent the afternoon working to plan something like this. I believe this is called an object-relational adapter in case you want to look for other implementations (there's lots for Java). Basically, this is most easily done with objects that have static-typed properties (such as I have in the basicproperty package). You can construct a schema from the class+properties. I'd estimate this will take a few weeks of solid programming to make work properly (i.e. make the data-type mappings all reasonable and efficient with a decent interface). Only relevant pre-cursor project I've seen is Python Data Object (PyDO) which is part of the SkunkWeb system. That system doesn't solve the "create schema from object" problem AFAICS, and it's that problem that I'm interested in solving. For instance, with a data-model like this: Event: mxDateTime startDate mxDateTime stopDate str name User user Collection{type Resource} resources Resource: str name User: str name (simplified example from one of my projects), you'd want the data-store to create 3 class-specific tables with the Event table having a resource sub-table for the one-to-many relationship. You'd want it to manage all the persistentIDs, and to properly re-constitute property values on access to be references to objects (rather than persistentIDs). The model I'm currently laying out seems quite capable of supporting this, though there will need to be some additions to the basicproperty class to support selecting among the various many-to-one / one-to-many / one-plus-sub-key-to-many / etceteras data models for certain properties. The thing is, to be really useful, you need to make a lot of simplifying assumptions (such as that all objects of a type/class have the same data-storage requirements). I can make those assumptions in my apps, but the result won't allow for anything like the full range of Python's dynamic nature. Anyway, I'm going back to my SQL lessons now :), Mike Robert Oschler wrote: > Forgive me :) > > If Peter Piper pickles a peck of Python packages, can he pack the pickled > Python peckers in a proper packing place? > > Translated: Anybody seen a module that can override the standard pickling > process and store and retrieve Python objects to a MySQL database? > > thx > > P.S. - Whell hell the language is named after the world's best comedy > troupe, what did you expect, green eggs and spam? :) > > -- _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From m2 at plusseven.com Wed Sep 18 15:46:47 2002 From: m2 at plusseven.com (Alex Polite) Date: Wed, 18 Sep 2002 21:46:47 +0200 Subject: debugging "Too many open files" Message-ID: <20020918194647.GB2682@matijek.plusseven.com> I'm getting the "Too many open files" error. I've reset /proc/sys/fs/file-max to 100000 and the count in /proc/sys/fs/file-nr is nowhere close. I'm not sure that python is the root of the problem. Is there anyway to see which processes own the active file descriptors? -- Alex Polite http://plusseven.com/gpg/ From duncan at NOSPAMrcp.co.uk Mon Sep 9 10:36:27 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 9 Sep 2002 14:36:27 +0000 (UTC) Subject: xml.minidom is stripping out my CRLF's in attrib values!! References: <3D7C80C4.9070204@NOSPAMbitbuilder.com> <3D7C8C76.8060700@NOSPAMbitbuilder.com> Message-ID: Ahmad Baitalmal wrote in news:3D7C8C76.8060700 at NOSPAMbitbuilder.com: > That's not what my problem is, that I know about ( crlf's between > nodes),, > > Here is the deal: > > > > > After the word "spotted" there is a crlf, -inside- the attribute > value. Sholdn't it be treated as part of the value? > > The value now comes stripped of that crlf. The XML specification, para 3.3.3 specifies that attribute values must be normalised. The normalisation will convert your newline to a space and may also remove duplicate spaces: > 3.3.3 Attribute-Value Normalization > Before the value of an attribute is passed to the application or > checked for validity, the XML processor must normalize the attribute > value by applying the algorithm below, or by using some other method > such that the value passed to the application is the same as that > produced by the algorithm. > > All line breaks must have been normalized on input to #xA as described > in 2.11 End-of-Line Handling, so the rest of this algorithm operates > on text normalized in this way. > > Begin with a normalized value consisting of the empty string. > > For each character, entity reference, or character reference in the > unnormalized attribute value, beginning with the first and continuing > to the last, do the following: > > For a character reference, append the referenced character to the > normalized value. > > For an entity reference, recursively apply step 3 of this algorithm to > the replacement text of the entity. > > For a white space character (#x20, #xD, #xA, #x9), append a space > character (#x20) to the normalized value. > > For another character, append the character to the normalized value. > > If the attribute type is not CDATA, then the XML processor must > further process the normalized attribute value by discarding any > leading and trailing space (#x20) characters, and by replacing > sequences of space (#x20) characters by a single space (#x20) > character. > > Note that if the unnormalized attribute value contains a character > reference to a white space character other than space (#x20), the > normalized value contains the referenced character itself (#xD, #xA or > #x9). This contrasts with the case where the unnormalized value > contains a white space character (not a reference), which is replaced > with a space character (#x20) in the normalized value and also > contrasts with the case where the unnormalized value contains an > entity reference whose replacement text contains a white space > character; being recursively processed, the white space character is > replaced with a space character (#x20) in the normalized value. > > All attributes for which no declaration has been read should be > treated by a non-validating processor as if declared CDATA. > So the only way to get a newline into an attribute is to escape it in using an entity reference. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From benji_75 at hotmail.com Thu Sep 19 00:23:39 2002 From: benji_75 at hotmail.com (Ben Gerblich) Date: Thu, 19 Sep 2002 13:53:39 +0930 Subject: try import except want lineno from Exception Message-ID: I am importing module files, and want to catch an error (if any) and print the filename and line number of the error. The "Exception ,e" does not return, or does not have the attirbutes listed above. It only returns e="line() takes exactly 2 arguments (3 given)" I think I want to use SyntaxError as it has the attributes: filename, lineno, offset and text. I have found no info on traceback. With the code below, how do I find the **line_number**? Thanks. ---- [13:45:40]~/py/dev/import2:cat runme.py from progfile import * [13:45:44]~/py/dev/import2:cat progfile.py class Foo: def __init__(self): self.lines = [] def line(self,x): self.lines.append( x ) print 'start' try: klass = __import__('module') code = "object = klass.%s()" % 'Bar' exec code except TypeError, e: print 'TypeError\n%s' % e except Exception, e: print 'Exception\n%s' % e print 'end' [13:45:51]~/py/dev/import2:cat module.py from progfile import Foo class Bar(Foo): def __init__(self): Foo.__init__(self) print 'line-1'; self.line(20) print 'line-2'; self.line(40,60) # <--- an error!!! print 'line-3'; self.line(80) [13:45:57]~/py/dev/import2:python2 runme.py start line-1 line-2 TypeError line() takes exactly 2 arguments (3 given) end [13:46:07]~/py/dev/import2: _________________________________________________________________ Join the world?s largest e-mail service with MSN Hotmail. http://www.hotmail.com From bokr at oz.net Tue Sep 3 12:28:15 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Sep 2002 16:28:15 GMT Subject: getch in python References: <75ca4e69.0209022326.4cde72e8@posting.google.com> Message-ID: On 3 Sep 2002 00:26:13 -0700, vvenka1 at hotmail.com (Venkat Venkataraju) wrote: >Hi All > >Is there any function that behaves like getch() function in C? > If you are on windows, >>> import msvcrt >>> while 1: ... c=msvcrt.getch() ... print '%02X: "%s"' % (ord(c),c) ... if c=='q': break ... 31: "1" 32: "2" 33: "3" 61: "a" 41: "A" 40: "@" 01: "?" 71: "q" (The 01 was a ctrl-A, and on a console window you see a happy face instead of the question mark ;-) For more info, see http://www.python.org/doc/current/lib/msvcrt-console.html On *nix look into curses. Regards, Bengt Richter From loewis at informatik.hu-berlin.de Fri Sep 20 16:20:11 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 20 Sep 2002 22:20:11 +0200 Subject: Python 2.2.1 compatible with Tcl/Tk 8.4? References: Message-ID: Andrew Koenig writes: > Now that Tcl/Tk 8.4 is out, can anyone tell me whether Python 2.2.1 > will work with it? It appears to work fine here, and I can't see a reason why it would be incompatible. Notice that the setup.py of 2.2.1 is already prepared to search for Tcl/Tk 8.4 on its own. Regards, Martin From donn at u.washington.edu Thu Sep 5 15:48:50 2002 From: donn at u.washington.edu (Donn Cave) Date: 5 Sep 2002 19:48:50 GMT Subject: str() of a tuple References: Message-ID: Quoth "Fredrik Lundh" : | Douglas Zongker wrote: |> Why, oh why does the str() of a container use the repr()s of the |> objects inside? This seems to violate what the docs claim str() does |> -- "return a nicely printable representation of an object." | | "an object" refers to the container itself, not the objects | in the container. And the expression "nicely printable" is so ambiguous that it can mean whatever you like. I like to define it as what str() does, which automatically resolves any question about whether str could be violating this provision. Donn Cave, donn at u.washington.edu From mennosimons at gmx.net Thu Sep 26 09:57:28 2002 From: mennosimons at gmx.net (Ulli Stein) Date: Thu, 26 Sep 2002 15:57:28 +0200 Subject: unicode woes References: <3d92d120$0$76313$e4fe514c@dreader4.news.xs4all.nl> Message-ID: Radovan Garabik wrote: > Ulli Stein wrote: > : But nevertheless you would have to use everywhere the Python unicode() > : function. > > : Or how would you do this (nonsense string): > : str = str + "bla?" + str[:5] + "?? > > : Would you write then: > : str = str + unicode("bla?") + str[:5] + unicode("??)? > > I ran into the same problem and find out that python2.3 > handles this. > Just add the line > # -*- coding: UTF-8 -*- > as the second line of your python script and then > you can use all your strings in UTF-8 encoding > (or any other, whatever fits you) > >From where do you have this information? Is there some official changelog for python2.3? Thanks. From skip at pobox.com Tue Sep 10 15:14:32 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 10 Sep 2002 14:14:32 -0500 Subject: read() file?? In-Reply-To: <-1076673467.1031684821080.JavaMail.nobody@webmail2.brturbo.com> References: <-1076673467.1031684821080.JavaMail.nobody@webmail2.brturbo.com> Message-ID: <15742.17560.693117.961029@12-248-11-90.client.attbi.com> Juliano> I have a file with assembler instruction and i want read the Juliano> lines of the file and put in a list of string, this is easy to Juliano> do, but i don?t want to consider the caracteres "/" and the Juliano> othes after him. Juliano> file.asm: Juliano> ADD D1 /coment1 Juliano> LDA D2 /coment2 Juliano> list of strings: Juliano> X=[ 'ADD D1' , 'LDA D2' ] How about: import re x = [] for line in file("file.asm"): line = re.sub(r"\s*/.*", "", line.strip()) x.append(line) ? -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From rjones at ekit-inc.com Thu Sep 19 08:59:26 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Thu, 19 Sep 2002 22:59:26 +1000 Subject: StructuredText -> HTML module?? In-Reply-To: References: <3d89b69d$1@news.sentex.net> Message-ID: <200209192259.26556.rjones@ekit-inc.com> On Thu, 19 Sep 2002 10:24 pm, Thomas Weholt wrote: > All I'm actually after is to be able to write stuff like : > > **Header** > > List: > 1. Foo > 2. Bar > 3. Python > > Heres an indented section of text. > > And turn this into > >

Header

> > List: >
    >
  1. foo
  2. >
  3. bar
  4. >
  5. Python
  6. >
> >

>

> Heres an indented section of text. >
>

> > Or something similar. Since there's allready something that I believed was > standardized it would be easier to use modules allready available than > doing it all from scratch. If you're really able to go with "something similar" then look at the docutils project (http://docutils.sf.net/ ... start with the "primer" document). It's like StructuredText, but much better in a lot of ways (see that website for detail if you need it). The above text would be written with a minor change... the heading would be: Header ------ instead of **Header** (which denotes generic bolding in ReStructuredText). Richard From vinodvas at pacific.net.sg Mon Sep 2 04:24:49 2002 From: vinodvas at pacific.net.sg (Vinod Vasnani) Date: 2 Sep 2002 01:24:49 -0700 Subject: PyQt: Win Systray issue References: <5695be92.0208291731.6f3d696@posting.google.com> Message-ID: <5695be92.0209020024.60258514@posting.google.com> Phil Thompson wrote in message news:... > > > Hmm - the second request for this in a week. > > I'll implement winEventFilter() for the next version - sometime in > September. > > Phil Thanks in advance! Vinod From timh at zute.net Sun Sep 8 09:53:20 2002 From: timh at zute.net (Tim Hoffman) Date: Sun, 08 Sep 2002 21:53:20 +0800 Subject: python program to watch a file - example. References: Message-ID: <3D7B5650.4050304@zute.net> Wayne R wrote: > Sorry for the html, I forgot to turn it off (as I usually turn it off > as soon as I install a new system, forgot this time). > > The platform is Gentoo Linux, I am writing a piece of code for the > Twiggi project to patch in adduser support. > > > |-> > >I am trying to write a python program that will run as a deamon > and > |-> > >watch a file for data to arrive and then wake up and perform > duties > |-> on > |-> > >that data. I found ways to make a python program run as a > deamon > |-> but I > |-> > >am at a loss to find anything related to watching a file for data > so > |-> > >that it can then process the data. I didn't really want to do a > |-> sleep > |-> > >loop or something like, I am sure there is a better way. > |-> > > > |-> > >Any ideas or links to more info? > |-> > > > |-> > Don't annoy people you want help from, for starters. > |-> > What system are you targeting? (Outlook in the headers says you're > on > |-> windows > |-> > generating this abominable mix of actual message and useless > cruft). > |-> > > [Wayne R] > > > Are you talking about the same file always (ie you don't have a new file, overwriting the old one ?). Anyway you really need to look at how the underlyng OS, can handle such an event. If it is always the same file and seeing you are looking at *nix varient, one of the unix like ways would be to tail -f the file, and hook it up to your process which just does blocking reads on stdin. ie tail -f somfile | python my_watch.py Rgds Tim From eddie at holyrood.ed.ac.uk Fri Sep 13 07:45:47 2002 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 13 Sep 2002 11:45:47 +0000 (UTC) Subject: Expect() from telnetlib giving me problems. References: <4378fa6f.0209121325.130766fc@posting.google.com> Message-ID: mnations at airmail.net (Marc) writes: >Hi, >This is the error I'm getting: >Exception in thread Thread-3: >Traceback (most recent call last): > File "C:\Python22\lib\threading.py", line 408, in __bootstrap > self.run() > File "C:\Python22\lib\threading.py", line 396, in run > apply(self.__target, self.__args, self.__kwargs) > File "main.py", line 85, in run > command[0](*command[1:3]) > File "key.py", line 94, in command > read_result(conn) > File "key.py", line 104, in read_result > buffer = conn.expect(alist, 5) > File "C:\python22\lib\telnetlib.py", line 541, in expect > list[i] = re.compile(list[i]) > File "C:\Python22\lib\sre.py", line 178, in compile > return _compile(pattern, flags) > File "C:\Python22\lib\sre.py", line 228, in _compile > raise error, v # invalid expression >error: nothing to repeat >I've tried several different ways to get the expect command to work. I >can't find any examples and only limited documentation. Here is how >I'm trying to implement it: > > alist = [ 'COMPLD', '*/' ] > buffer = conn.expect(alist, 5) > >Can someone please tell me what is wrong or provide me with some >working examples of using the command. As previously mentioned '*/' is not a regular expression. If you want to search for fixed strings without bothering to learn abot regular expressions or if you're not sure exactly what the input will be and whether it may contain special characters you could do: import re alist = map (re.escape, [ 'COMPLD', '*/' ]) Eddie From ehagemann at comcast.net Wed Sep 25 05:38:45 2002 From: ehagemann at comcast.net (Eric Hagemann) Date: Wed, 25 Sep 2002 09:38:45 GMT Subject: help with print function in extension References: <3D912DC3.7010302@something.invalid> Message-ID: Its my understanding that str() should return a PyObject * to a string "Greg Ewing" wrote in message news:3D912DC3.7010302 at something.invalid... > Eric Hagemann wrote: > > > Traceback (most recent call last): > > File "", line 1, in ? > > SystemError: error return without exception set > > > Check what your C function implementing str() is > returning. My guess is that you've forgotten a > "return 0" statement, and it's returning some junk > value that in some cases the Python interpreter > thinks is signalling an error. > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > From eric.brunel at pragmadev.com Thu Sep 5 06:11:52 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Thu, 5 Sep 2002 12:11:52 +0200 Subject: Privacy and Inheritance References: Message-ID: Delaney, Timothy wrote: >> From: Eric Brunel [mailto:eric.brunel at pragmadev.com] >> >> In languages that have actual "private", "protected" and "public" >> attributes, private attributes are not inherited. They are >> visible only in >> the class that define them, not outside it and not in its >> sub-classes. What >> you want is a protected attribute, that is visible in the >> defining class >> and in its sub-classes. >> >> Unfortunately, Python doesn't know anything about protected >> attributes. >> AFAIK, there's no simple way to do what you want: in Python, >> attributes are >> either private or public; there's nothing in between... > > Actually, there is. > > Anything beginning with a leading underscore is not imported via a 'from > module import *' (not that anyone should in general use this ;) Thus > anything with a leading underscore is something other than completely > "public". > > There is a (strong) convention that anything beginning with a *single* > leading underscore is "protected". No name mangling is performed, but the > name is flagged as "special". I just meant that Python has no way of enforcing "protectedness", as leading double underscores (kind of) enforce privateness. As you say, using a single leading underscore in protected attribute names is merely a convention, even if it's a strong one: Python won't prevent any use of the attribute, neither from sub-classes, nor from the "outside world". Anybody not knowing the convention can use these attributes in any way without any problem. -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From tjreedy at udel.edu Tue Sep 10 21:08:59 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Sep 2002 01:08:59 GMT Subject: Python primer - comments appreciated! References: Message-ID: "Thorsten Kampe" wrote in message news:allpms$1r005a$1 at ID-77524.news.dfncis.de... > * Terry Reedy ... > > result.setdefault(func(item),[]).append(item) > > To make every item hashable, I made this: > result.setdefault(repr(func(item)),[]).append(item) > > > # {}.setdefault(key,default) was added for just this sort of usage > > Sorry, I just don't get it: your mixing (chaining?) a dict method and > a list method as if it was a f(g(x)) and /it works/!?! Where is that > documented? How is is that evaluated (left to right)? Yes, left to right. Dict.setdefault returns the value corresponding to the key after setting d[key]=default if key not already in d. In this case, *all* values are initialized to [] by such a call. Then append to the list. This working depends on there being *two* references to the list. The one in the dict (possibly new, possible not) and the one returned by the method and used by append(). See Python Library Reference 2.2.7 for dicts. > > >>> f = lambda x: x % 3 > > >>> equiv_class([0,1,2,3,4,5,6,7,8,9],f,part='bool') > > Now this is: > quotient_set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], lambda x: bool(x % 3)) > > (Mathematically spoken, the quotient set is the set of all equivalence > classes induced by func, which is what we return) Since the equivalence lists may have duplicates, they are not, strictly speaking, sets. If the set of return values were made to be dicts (or, in 2.3, sets) instead of lists, then they would be. Such details can, of course, be adjusted for a particular application. Terry J. Reedy From tjreedy at udel.edu Wed Sep 4 11:39:11 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 04 Sep 2002 15:39:11 GMT Subject: Please help in calling python fucntion from 'c' References: Message-ID: > [ The information contained in this e-mail is confidential and is intended for the named recipient only. If you are not the named recipient, please notify us by telephone on +44 (0)1249 442 430 immediately, destroy the message and delete it from your computer. I will gladly delete it, but expensive call? no. Pretty whacko. From SBrunning at trisystems.co.uk Wed Sep 25 09:41:52 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 25 Sep 2002 14:41:52 +0100 Subject: missing functions in os.path Message-ID: <31575A892FF6D1118F5800600846864DCBD876@intrepid> > From: Jens Bloch Helmers [SMTP:helm at dnv.com] > I hope that a future version of Python will include the following > two functions: > > os.path.localpath( file ) # Returns the non-UNC name > # of file. > > >>>file = r'\\computer\shared\myfile.txt' > >>>os.path.localpath( file ) > 'd:\somedir\shared\myfile.txt' A word of advice - don't use 'file' as a label - it clobbers the built-in. > os.path.relpath( file, dir ) # returns the relative path of > # file relative to directory dir > > >>>file = r'C:\test\mydir\hum.txt' > >>>dir = r'C:\otherdir' > >>>os.path.relpath( file, dir ) > '..\test\mydir\hum.txt' All patched gratefully received, I'm sure! Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From erikprice at mac.com Tue Sep 17 10:04:47 2002 From: erikprice at mac.com (Erik Price) Date: Tue, 17 Sep 2002 10:04:47 -0400 Subject: Good book choice? In-Reply-To: <2393234a.0209160513.469a4357@posting.google.com> Message-ID: <6CF1C3E4-CA46-11D6-888F-00039351FE6A@mac.com> On Monday, September 16, 2002, at 09:13 AM, davisman wrote: > This book includes a CD with > all the scripts used in the book This isn't directed at the book mentioned (which is why I didn't quote its name in this rant), rather at all books which come with CDs. I hate it when books come with CDs. I'm perfectly capable of downloading the source code used in the book, and in fact I prefer to hand-type it while reading from the book anyway, to make sure I see every part of the code. When a book comes with a CD, it is cumbersome to read portably, which is the whole advantage of books, unless you take the CD out. And if I take the CD out, then there is no doubt that it will get lost, or I will be unable to return the book if dissatisfied, etc. Plus, you can't tell me that the inclusion of a CD and the envelope/publishing used to include the CD doesn't add a few units of currency to the book's cost. Poke this opinion full of holes, but when I buy a book, I want a book, not a software package. The book should be good enough to stand on its own without the "bonus" material on CD. I think twice about buying a book that comes with a CD, to tell you the truth. Erik -- Erik Price (zombies roam) email: erikprice at mac.com jabber: erikprice at jabber.org From ehagemann at comcast.net Sun Sep 29 14:11:26 2002 From: ehagemann at comcast.net (Eric Hagemann) Date: Sun, 29 Sep 2002 18:11:26 GMT Subject: help with writing extension Message-ID: I have been handcrafting an extension module creating a new type I am making use of the numeric methods (+,-,* etc) I solved the problem of the object interating with other types by working through the __coerce__() function and have no issue with operations like +2 but I am getting an error on 2-. In Beazley's book there are descriptions of functions like __radd__() when defining a new type in python, but I cannot find reference to these functions in C ? I have checked the doc's (not to say that I did not miss something ;) ) What is interesting is that both +2 and 2+ both end up in the __coerce__ function. Whats even more interesting is that the arguments to __coerce__ are in the same order for both function calls, the first argument is the second is a PyInt. The Error I get (for 2+) is Traceback (most recent call last): File "C:\py_lib\test.py", line 30, in ? print "2+d = ",2+d TypeError: unsupported operand types for + that occurs after the __coerce__ function finishes. Has anybody worked through this before? From aleax at aleax.it Wed Sep 25 06:28:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 10:28:37 GMT Subject: Python Compiling References: <80a8af7d.0209250113.28ae4c72@posting.google.com> Message-ID: Klaus Momberger wrote: > "Terje Johan Abrahamsen" wrote in message > news:... ..... >> >> Is it not possible to write a complete compiler like the C compiler for >> Python? Or is it just that nobody has done it? Or must the language be >> constructed differently? >> > Slightly off-topic, but if you are looking for a language which can > be run by an interpreter and can be compiled as well, maybe you should > take a look at Ocaml: > > http://www.ocaml.org Or Haskell, www.haskell.org -=- HUGS inteprets it, the Edinburgh compiler compiles it. Scheme has _many_ interpreters and compilers too. Hey, so does Visual Basic... it's quite the thing these days. Alex From jb at cascade-sys.com Tue Sep 17 11:18:42 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Tue, 17 Sep 2002 08:18:42 -0700 Subject: threads or queue for this task References: <6dFh9.120102$pX1.4321019@news2.tin.it> Message-ID: <3D8747D1.6050304@cascade-sys.com> Alex Martelli wrote: >Taking it for granted that one wouldn't pontificate without vast >relevant experience, > A rather rash assumption for internet communications. ;o) But I appreciate your giving me benefit of the doubt. >Perhaps the hint is in Mr Pettersen's mention of >"processing too many 16-GB files" vs your insistence on "capacity >to handle the expected traffic", "time-critical requests", "the >work requests may be created on a different machine", etc. > >I.e., you're focusing (perhaps because of how life shaped your >experience of threading) on a "server" process or machine that >is just responding to traffic originating elsewhere, while I'm >giving at least equal weight to a process that's "just" doing a >lot of batch-like work, e.g. generated by splitting up the task >of processing a "16-GB file" or the like, and using threading >to ensure the best throughput (implies that substantial parts of >processing each work request happen in C code that release the >GIL, be it within the Python core or in extensions). > It does sound like a big part of our disagreement is past experience with different types of appellations. The bulk of my past experience almost always involved multiple processes and often multiple processors and usually highly complex, dedicated applications. Generally, lost data was never an option, though as I enumerated some of the systems in my previous note, a few did include bounded queues. More specifically to Python, IIRC, whenever I've used threads, the application always involved input via sockets, ultimately from client apps, over which the server app had no direct control. In those cases, I've always used unbounded queues to connect threads and they worked just fine. I never wrote a stand-alone Python app like you describe. I agree if you're writing a self-contained application then it makes sense to used bounded queues to help throttle the generator thread. >If this is the root of our disagreement, I suggest you reconsider >whether "the general case" need ONLY include "networked" >situations, which seem to be what you istinctively think of >in this context, > In a cursory review of the record, I don't see where I made that particular assertion. >or "threading to slice up a big batch of work" too. > Seems at every opportunity I agree that your scenarios are valid and never once said or implied they were not. I think part of my problem here is I don't have the experience to pick words that exactly match your expectations. I think the number of times the following sentence has been referred to in our discussion may point to the crux of our problem. >>>>>>Generally, Queues never get "full" and you generally don't care if they're empty. >>>>>> >>>>>> I intended this statement to be a gross simplification in the interest of directing Robin away from what I regarded to be unnecessary complexities. Recall that it was an answer to the specific question of "I am put off by [...] empty() [...] how can you code if you don't know if the queue is empty or full?" It was intended as a way for the beginner to begin to use queues and not worry about unnecessary details. Out of context the statement is a much easier nit to pick. In context, it's as much a part of an elaboration on "multithreading semantics" as anything else. The last sentence is the most important part. Generally, Queues never get "full" and you generally don't care if they're empty. The import thing about Queues is that the reader thread will automatically be suspended when reading from an empty queue and furthermore it will automatically wake up when the queue becomes non empty. All you need from Queues is to create them and to get and put data. I submit that the oversimplification applies, in a way, to your bounded queue scenario -- the programmer generally shouldn't "CARE" if the queues are empty or full -- the important thing is that they block and unblock when appropriate. I hardly intended this statement to stand as an accurate characterization of all queuing systems, which appears to be a big part of your complaint. In any case, I hereby withdraw the entire statement altogether and invite you to propose instead whatever alternative summary you think best serves the the OP and the Python community generally. In this I invite you to have the last words on the subject. >...but setting a Queue to bounded, and implicitly sleeping when >trying to add one more item to a full Queue, is NOT significantly >more complicated. It's strongly parallel to sleeping just as >implicitly when trying to peel an item from an empty Queue. The >symmetry, when applicable, may be considered more elegant than >an *asymmetric* solution, after all. > Looking at queues in isolation, I agree an upper bound is not a deep concept. Whether bounded or unbounded is more "elegant" is a value judgment where reasonable people may disagree. E.g., your discourse about Rosetti's Ferrara seemed to imply that asymmetry was more elegant than symmetry. In your scenario of a self-contained process, a bounded queue is simpler solution. In my scenario where incoming traffic may have to be discarded or dealt with in some out of band fashion a bounded queue is more complicated than unbounded queues. >But at least we can agree to >disagree civilly, whence my apologies for appearing unwilling to >do so in my earlier post. > This is progress, I suppose. With my latest concessions and stipulations I hope we're no longer all that far apart. >>[...] Extreme Programming [..] >> >> >But from my POV this generally goes for *threading in general*! > True and I believe I was the only person to mention previously that multi threading may be overkill. However, the original request was specifically about threads and without more detail, "don't use threads" seemed an inappropriate response. >I always consider a first-cut solution WITHOUT multi-processing, which >is a huge complication in itself, more often than not. > While generally I would agree, I find that many TCP/IP applications are somewhat intrinsically concurrent. Within that, threads are much simpler than, say, using Select(). For starters, it's sometimes easier to have separate reader and writer threads than to rely on incoming in outgoing data to be perfectly interleaved. A common paradigm is a listener thread accepts connects from a socket and launches new reader threads to handle each connection. Then maybe the reader threads queue some incoming requests to server threads so that the socket never fills or blocks. In one application, I had two listeners listening on two separate sockets, each spawning per-client reader threads, each of which funneled some subset of requests to a common processing thread guarding a critical resource. On the client side, sometimes it's easier having a separate thread monitoring return traffic. In another app, I have a listener thread which spawns multiple connection threads, one for each external client. Connection threads process commands, some of which are queued to a "command processor" thread and others of which queued to a serial port writer thread. A serial port reader thread handles the back traffic, some of which gets forwarded via selected connection threads back to interested client processes. Although theoretically possible, I shudder to think of how difficult that would be to implement using Select() instead of threads. In all of these cases, I have encountered no need for limiting the size of the queues used. But a key ingredient is there is no 'generator' thread to overflow the queues. Then too, it's also always been a given that overall service utilization was very low. >I do disagree, and this may be a philosophical point in part. > That would explain the amount of energy being expended by both parties. The argument is so intense because the stakes are so low. ;o) >But the ability to make SOME Queue's bounded, >and still handle them without fuss, IS important in a vast >enough number of cases that ruling this possibility out is >a serious didactic mistake, IMHO. > I stipulated this much from the beginning and never ruled it out. >In particular, when preparing work-requests is part of the >design's task (e.g. by analyzing pieces of a huge existing >file), a bounded Queue can simply and without problems do >some appropriate balancing within the system between the >amount of resources devoted to preparing work requests, >and the amount devoted to processing them. It's as simple >as that! > You've made this point more than once in this exchange. I've never disputed it. >Perhaps, but this is a straight quote from Albert Einstein, of >course, therefore you should take the matter up with him... > The important thing is we both agree it should be as simple as possible. We simply don't agree what that means, exactly. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From karczma at info.unicaen.fr Wed Sep 4 07:09:59 2002 From: karczma at info.unicaen.fr (Jerzy Karczmarczuk) Date: Wed, 04 Sep 2002 13:09:59 +0200 Subject: Why Python? References: Message-ID: <3D75EA07.D5EB1F5A@info.unicaen.fr> RPM1 wrote: > If you really want to get a feel for a language, read a fairly large > program that somebody else has written in that language, (not > just little snippets). > > Patrick I'll tell you an anecdote. 100% authentic and meaningful. Long time ago a friend of mine, a physicist, had to read, understand, correct and extend a really huge program in Fortran, something within the realm of High Energy Physics, with Monte-Carlo, modelling of resonances, and other succulent stuff. The suicide was not far, but finally he managed. And then he told me: "What a disgusting, unreadable programming style! It was a nightmare to read all that! But now I became a competent, experienced Fortran programmer!" And, yes..., he continued to program in Fortran for many years. So, if somebody suggests that a newbie should learn "C" or assembler just in order to appreciate the elegance of Python or other, even nicer (yes, there are...) languages, beware. The result might be unexpected. You know, I am a peaceful, animal-friendly guy who thinks that corridas are a pure barbarism. But I refused myself the temptation to go and see one, because I am afraid that, all philosophy apart, I may discover that - after all - perhaps I adore the public slaughter of bulls? Jerzy Karczmarczuk Caen, France From aleax at aleax.it Fri Sep 20 03:23:46 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 07:23:46 GMT Subject: implementing reduce protocol in C References: <3D8A7DA1.7090506@hotmail.com> Message-ID: <62Ai9.136323$pX1.4852975@news2.tin.it> Tom Widrick wrote: ... > static PyObject * > myobj_reduce(self) > MyObject *self; > { > PyObject *args; > PyObject *result; > > args = PyTuple_New(5); > if(args == NULL) > return NULL; > > PyTuple_SET_ITEM(args, 0, self->po_name); > PyTuple_SET_ITEM(args, 1, self->po_parents); > PyTuple_SET_ITEM(args, 2, self->po_children); > PyTuple_SET_ITEM(args, 3, self->po_doc); > PyTuple_SET_ITEM(args, 4, self->po_dict); This is stealing references to the five objects you pass as items. I'm not sure what effects this might have, but doesn't look good. Perhaps it's a contributing factor to strange behavior (though it would cause anomalies at pickling time, not when unpickling...). > result = Py_BuildValue("(OOO)", self->ob_type, Py_None, args); > return result; > }; Looks like a leak (no decref of args) but that's not the specific problem's that's biting you, I think. > The type constructor wouldn't have worked as a call to unpickle the > object so I've used basicnew instead. > > static PyObject * > myobj_basicnew() > { > MyObject *self; > > self = PyObject_New(MyObject, &MyObject_Type); > return (PyObject *)self; > } Do you expose this as the __basicnew__ static method of your type? I'm not sure how you do so, as the definition of staticmethod lives in funcobject.c, not exposed in the .h, I think. Or, ditto for classmethod. Haven't tried exposing a __basicnew__ method from a C-coded type, yet. If I had to, I think I'd try to run from C the Python-level exposed staticmethod built-in -- but since as I said I didn't try that yet, I may be missing something. Alex From pan-newsreader at thomas-guettler.de Tue Sep 24 15:15:30 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Tue, 24 Sep 2002 21:15:30 +0200 Subject: isFloat: Without Exception-Handling References: Message-ID: On Fri, 20 Sep 2002 16:15:55 +0200, Mark McEahern wrote: > [Magnus Lycka] >> Something like this perhaps: >> >> import re >> >> def isFloat(S): >> floatRE = r"^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$" return >> re.match(floatRE, str(S)) is not None >> >> I'm not sure it's faster though. > > If you were going to run this lots of times, you might want to compile > the pattern. Anyway, the exception based code is faster, by my testing > (harness at bottom): > > isFloatExcept 0.220 > isFloatRE 0.521 > isFloatRECompiled 0.400 I thought exceptions are slow. But as someone mentioned, exception in python seem to be different from exceptions in java or c++. Thank you for the performance test! thomas From jon+usenet at unequivocal.co.uk Mon Sep 16 10:14:11 2002 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Mon, 16 Sep 2002 14:14:11 -0000 Subject: html template system? References: Message-ID: In article , :B nerdy wrote: > what are good templating systems avaliable for python? > > ive been at http://zebra.sourceforge.org and the documentation is kinda sus. > zope DocumentTemplate is included with zope. but i want a smaller footprint > system. Try http://jonpy.sf.net/ , it does what you describe. From max at alcyone.com Wed Sep 18 17:42:13 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 18 Sep 2002 14:42:13 -0700 Subject: ANN: empy 1.5 -- Embed Python in template text as markup Message-ID: <3D88F335.FC5B4E49@alcyone.com> Summary empy is a system for embedding Python expressions and statements in template text; it takes empy source files, processes them, and produces output. This is accomplished via expansions, which are special signals to the empy system and are set off by a special prefix (by default the at sign, '@'). empy can expand arbitrary Python expressions and statements in this way, as well as a variety of special forms. Textual data not explicitly delimited in this way is sent unaffected to the output, allowing Python to be used in effect as a markup language. Also supported are recording and playback via diversions and dynamic, chainable filters. The system is highly configurable via command line options. Expressions are embedded in text with the '@(...)' notation; variations include conditional expressions ('@(...?...:...)') and the ability to handle thrown exceptions ('@(...$...)'). As a shortcut, simple variables and expressions can be abbreviated as '@variable', '@object.attribute', '@function(arguments)', '@sequence' [index], and combinations. Full-fledged statements are embedded with '@{...}'. Forms of conditional and repeated expansion are available via '@[...]'. A '@' followed by a whitespace character (including a newline) expands to nothing, allowing string concatenations and line continuations. Comments are indicated with '@#' and consume the rest of the line, up to and including the trailing newline. '@%' indicate optional "significators," which are special forms of variable assignment intended to specify per-file identification information in a format which is easy to parse externally. Finally, a '@@' sequence expands to a single literal at sign. Getting the software The current version of empy is 1.5. The latest version of the software is available in a tarball here: "http://www.alcyone.com/pyos/empy/empy-latest.tar.gz", http://www.alcyone.com/pyos/empy/empy-latest.tar.gz. The official URL for this Web site is "http://www.alcyone.com/pyos/empy/", http://www.alcyone.com/pyos/empy/. Requirements empy should work with any version of Python from 1.5.x onward. License This code is released under the "GPL", http://www.gnu.org/copyleft/gpl.html. ... Release history [since 1.4] - 1.5; 2002 Sep 18. Escape codes ('@\...'); conditional and repeated expansion substitutions via '@[if E: ...]', '@[for X in E: ...]', and '@[while E: ....]' notations; fix a few bugs involving files which do not end in newlines. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ I am the king of sorrow \__/ Sade EmPy / http://www.alcyone.com/pyos/empy/ A system for embedding arbitrary Python in template text as markup. From cnetzer at mail.arc.nasa.gov Sat Sep 28 22:35:34 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Sat, 28 Sep 2002 19:35:34 -0700 Subject: Best way to create a class dynamically on the fly? In-Reply-To: References: <3D96511D.2040407@4-am.com> Message-ID: <200209290235.TAA10390@mail.arc.nasa.gov> On Saturday 28 September 2002 19:08, Robert Oschler wrote: > > I understand but what I'm after is building the class itself > dynamically, akin to the way you can manufacture a prolog predicate > on the fly. For example, if wanted to create a class whose name was > provided in a string variable called ClassName, at runtime. Or did I > misunderstand your reply? Well, you could create a class at runtime, given a class name, using several techniques; But what would be the code? Do you mean selecting from various classes (pre-made) given a string? Or would the class code be generated on the fly? Perhaps you mean you want to choose, at runtime, which class to instantiate given a string, such as in a Factory pattern. ie: (extremely simple example) class Foo: def __init__( self ): return def factory( name ): if name == 'dict': return {} # An instance of a class elif name == 'list': return [] # Another instance elif name == 'foo': return Foo() # A user defined class else: return None This is creating an instance on the fly, given a name at runtime, rather than a class, but unless you are doing meta programming, I think perhaps it is what you mean (and I apologize if otherwise) Here is a Python Cookbook entry on Factory patterns, BTW.: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86900 BTW, rather than returning the instance, you could return the class object itself, to be instantiated later (ie. "return Foo", instead of "return Foo()") -- Chad Netzer cnetzer at mail.arc.nasa.gov From kahanpaa at gstar.astro.helsinki.fi Mon Sep 2 07:05:33 2002 From: kahanpaa at gstar.astro.helsinki.fi (Jere Kahanpaa) Date: 2 Sep 2002 11:05:33 GMT Subject: file processing question References: Message-ID: Hi. Axel Grune wrote: > Hi, Im trying to read the data of a file with following method > file = open( inputfile, "r") > data = file.read() > file.close() > but 'data' is always smaller then the file size, e.g. I have a file > which is 25677824 bytes but file.read() reads only 4295 (file.tell() = > 25677824). > Im using python 2.2 under win2k. Is your data binary or plaintext? Have you tried reading in binary mode? file = open(inputfilename,"rb") data = file.read() file.close() Jere -- It's hard to think outside the box when you ARE the box. - unknown, alt.religion.kibology From albgrig at tiscalinet.it Mon Sep 30 07:54:33 2002 From: albgrig at tiscalinet.it (Alberto Griggio) Date: 30 Sep 2002 04:54:33 -0700 Subject: Python and GUI question References: <3d96b808_3@news.bluewin.ch> <3d97459e_2@news.arcor-ip.de> Message-ID: <6a8dcd75.0209300354.696c43b0@posting.google.com> > [...] WxPython looks good on Win32 and Linux, > and it pretty powerful. The downside is it doesn't have a (free) GUI > designer like Gtk or Qt. Well, it has (at least) three: boa constructor (boa-constructor.sourceforge.net - also an IDE), PythonCard (www.pythoncard.org - this is rather a complete framework than just a GUI designer), and wxGlade (wxglade.sourceforge.net) Ciao, Alberto From marklists at mceahern.com Wed Sep 11 18:29:37 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 11 Sep 2002 17:29:37 -0500 Subject: Restricting methods in derived classes In-Reply-To: Message-ID: [Huaiyu Zhu] > What I'm looking for is a way to say which methods from dict are inherited > in MyClass at the time the class is defined, without incuring a cost when > the methods are called. Is this possible? Would something like this work? $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> class foo(dict): ... def not_defined(self, *args, **kwargs): ... raise NotImplementedError ... update = not_defined ... >>> f = foo() >>> f['a'] = 1 >>> f {'a': 1} >>> d = {'a': 2} >>> f.update(d) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in not_defined NotImplementedError >>> // m - From peter at engcorp.com Tue Sep 3 09:01:20 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 03 Sep 2002 09:01:20 -0400 Subject: Design question.... parent/child class References: <3d74b021$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: <3d74b283$1@news.sentex.net> Gumuz wrote: > hi all, > > i have a SessionManager class, which contains a list of Session > objects(instantiated from a Session class). I have a design problem. > > Each session object has a small 'queue' of messages for the specific > session. How can a session send a message to another session without having > some kind of parent-reference to the SessionManager object? > > i am a bit puzzled, or is this parent-reference not such a bad idea after > all? Increasing coupling is always bad, but you could do this in a way that doesn't really increase coupling (at least in Python). The Session objects don't need to know about SessionManagers specifically, just about some thing that has a particular interface. In this case, maybe it's a "post" method. Pass in a reference to the SessionManager, or even the post method itself (a "bound" method, bound to a specific SessionManager instance), but don't do an "import sessionmanager" or anything like that in the session.py module itself. Note that passing messages between Sessions could be considered a function not appropriate for something called merely "SessionManager". Maybe you want to do this with another mechanism in parallel to this, or rename that class. Personally, I wouldn't do that unless the whole design was starting to get complex. -Peter From jb at cascade-sys.com Sat Sep 28 04:24:54 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Sat, 28 Sep 2002 01:24:54 -0700 Subject: Getting started References: <3D911306.7080609@ucsd.edu> Message-ID: <3D956756.7010502@cascade-sys.com> Adam Taylor wrote: >Python is in the same square as Lisp (which I mentioned). So is Perl. >At least using this terminology... ;) > Agreed. >Okay, that's true, he does define weakly-checked only in terms of >statically checked languages, which I hadn't appreciated: > >But the clear generalization of this (it seems to me) is to define >weakly checked languages as languages in which some unsafe operations >are detected and some are not detected. In other words, just delete the >word "statically" from the last sentence in the quote above. > Exactly. I think I said as much earlier, though not as succinctly. >Of course, it doesn't sound like any existing languages are both >dynamically typed and weakly checked (and I can't think of any myself): > I recall a Lisp implementation from long ago that did not distinguish between integers and machine addresses. When applying a function to an arg list, if the function name evaluated to a number the interpreter blithely JSRed to that address. This was a Feature, in that it was how system built-ins were linked with the higher level stuff. User code did not normally do this and it was not a big issue in practice. However it WAS a loophole that allowed type errors to occur, as it allowed code to jump to any random address in the system. But I think the generalization holds for most dynamic languages. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From ianholmes01 at lycos.com Fri Sep 13 11:58:22 2002 From: ianholmes01 at lycos.com (Ian Holmes) Date: 13 Sep 2002 08:58:22 -0700 Subject: [newbie] Buying an introductory/reference text References: Message-ID: jetman516 at hotmail.com (The Jetman) wrote in message news:... > Can't go wrong w/ Programming Python 2ndEd by Lutz from O'Reilly. Here's > a sample chapter. If you can only afford a single book, this mite be it....Jet > > http://www.oreilly.com/catalog/python2/chapter/ch15.html Agree with that totally - there is not a bad set of tutorials at http://www.devshed.com/Server_Side/Python that gets you to about the level the books starts at. Python 101 parts 1-8 and OO programming 1 and 2 From martin at v.loewis.de Wed Sep 18 17:23:32 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 18 Sep 2002 23:23:32 +0200 Subject: debugging "Too many open files" References: Message-ID: Alex Polite writes: > I'm getting the "Too many open files" error. What "the" error? An exception? A message in the system log? An SMS on your mobile phone? > I've reset /proc/sys/fs/file-max to 100000 and the count in > /proc/sys/fs/file-nr is nowhere close. > > I'm not sure that python is the root of the problem. Is there anyway > to see which processes own the active file descriptors? I recommend you list /proc//fd/ Regards, Martin From shalehperry at attbi.com Tue Sep 10 16:08:53 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 10 Sep 2002 13:08:53 -0700 Subject: "str"(expr)"str" interpolation syntax In-Reply-To: References: Message-ID: <200209101308.53220.shalehperry@attbi.com> On Tuesday 10 September 2002 12:35, Beni Cherniavksy wrote: > Hi all. > > I was searching for a new interpolation syntax that would use quotes > for starting/ending the interpolated part (I don't feel comfortable > putting code inside unclosed quotes...) > > After contemplating some horrors like $"""str"expr"str""" or > $("str" expr "str"), I noticed that currently both "( and )" are > illegal (first because strings are not callable, second is a syntax > error). So I propose that a parenthesized expresion near a string would > imply concatenation. In other words, > "foo"(x * 3)"bar" > would be equivallent to > "foo" + str(x * 3) + "bar". > This works of course with only one side, e.g. "foo"(x) or (y)"bar" but in > longer cases it would be good style to add empty strings on either end, > e.g. ""(y)"bar". And of course it all works with single quotes too. One > of the benefits over current interpolation PEPs is that you can change the > quote type in the middle... > > What do you think? having not read the PEPs, why is this needed? s = "foo%dbar" % (x*3,) # this works and as you showed above so does str(x*3). From alet at unice.fr Wed Sep 18 06:56:38 2002 From: alet at unice.fr (Jerome Alet) Date: Wed, 18 Sep 2002 12:56:38 +0200 Subject: [ANNOUNCE] DebSync v0.1 Message-ID: <3D885BE6.2ADF0055@unice.fr> Hi, I'm pleased to announce DebSync v0.1 DebSync is a Python command line tool which helps to synchronize a bunch of Debian GNU/Linux machines wrt the list of packages installed. DebSync retrieves the list of installed packages from a master host, and then install or remove packages on any number of hosts to make them have the very same installed packages list as the master host. Of course DebSync doesn't deal with configuring these packages, this must be done as usual. DebSync can work over ssh (default) or rsh. DebSync is different from fai (Full Automated Installation) in that, to my knowledge, fai only deals with machines you plan to install, while DebSync deals with existing and certainely differently installed Debian GNU/Linux machines. Debsync is distributed under the GNU GPL of the Free Software Foundation, and is available from : http://www.librelogiciel.com/software/ Remark : it's only a 0.1 so don't expect miracles, yet, but it seems to work reasonably well on the three hosts I've tried. Also be sure to have the same version of Debian installed and do an apt-get update on each host before launching DebSync. Any comment, contribution, or bug report is more than welcome ! Thanks for reading. Jerome Alet From lists at gregfortune.com Wed Sep 18 18:07:17 2002 From: lists at gregfortune.com (Greg Fortune) Date: Wed, 18 Sep 2002 15:07:17 -0700 Subject: Catching results of an exec Message-ID: <3d88f701$0$304$39cecf19@nnrp1.twtelecom.net> Is there any way to "catch" the value produced by an exec? I'm considering things like print statements that don't really assign a value, but do send a result to stdout. For example, if I execute exec('print dir()') from an interpreter, there will be some stuff spit out on the console. What if I really wanted to display the list from dir() in a different way? I'm working on a really dinky server that will sit on a machine and execute arbitrary python code. I want the results from the code execution to be returned to client. Even just eval('dir()') exhibits the desired behavior, but only from an interactive interpreter. Right now I've got a nasty hack that redirects stdout, uses an InteractiveInterpereter from the code module to execute the code, writes to an output file, reads the result from the file, restores stdout and then sends the result to the client. Hopefully, that's a terrible way to do it. It just occured to me that I can probably use a pipe in place of the output file, but still.... It would be great if exec and eval set something somewhere that held the results of the code execution. I looked in the InteractiveInterpreter (which, at least, kicks the results of the code execution out to stdout), but all it does is exec code in self.locals Did I miss something? Greg Fortune From op73418 at mail.telepac.pt Tue Sep 10 09:14:50 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Tue, 10 Sep 2002 14:14:50 +0100 Subject: Graph algorithms - minimisation References: Message-ID: <8vrrnuckib7gbuodhrmbs2f88nq8r5r5vu@4ax.com> On Tue, 10 Sep 2002 09:30:01 GMT, Padraig Brady wrote: >Jesper Olsen wrote: >> Do you know of python extentions that implement efficient graph >> algorithms? >> >> In particular I am interested in minimising the number of nodes & arcs >> used for representing directed graphs. >> >> If you know of implementations in other languages than python - e.g. >> C/C++, I am interested as well. >> >> Cheers >> Jesper > >Guido wrote an essay on graphs @ >http://www.python.org/doc/essays/graphs.html >In there is a method to return the shortest path >which may be useful? I remember seeing a recipe in ActiveState cookbook with Dijkstra's algorithm for finding shortest paths. You can then adapt it to your own representation of a graph. > >P?draig. Best regards, Gon?alo Rodrigues From claird at starbase.neosoft.com Tue Sep 17 12:52:09 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 17 Sep 2002 11:52:09 -0500 Subject: can wxpython do this? References: <737aefee.0209151702.3f735252@posting.google.com> Message-ID: <20929D5514805227.48A29064FC554044.5053D887939EB774@lp.airnews.net> In article , Erick wrote: >sorry for restating, but is there a way for me to connect to the Internet, >make a call to a webserver as a browser would do, retrieve data and display >it inside my application? . . . There are too many ways to do this. You might start with from urllib import urlopen URL = "http://www.python.org" page = urlopen(URL).read() print page -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From codeapocalypse at msn.com Wed Sep 18 13:23:43 2002 From: codeapocalypse at msn.com (Brian) Date: 18 Sep 2002 10:23:43 -0700 Subject: Win32COM & Detaching from automation servers References: Message-ID: codeapocalypse at msn.com (Brian) wrote in message news:... > Perhaps the solution is obvious and I'm just > not seeing the forest for the trees...) This appears to be the case - maybe too much recycled office air yesterday for me? I ran my code later in the evening yesterday and it is detached without me needing to do anything. Maybe too much stress was causing me to hallucinate in the morning yesterday. :) From phr-n2002b at NOSPAMnightsong.com Tue Sep 3 18:21:38 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 03 Sep 2002 15:21:38 -0700 Subject: https in Python? References: Message-ID: <7x8z2ipvd9.fsf@ruckus.brouhaha.com> s_gherman at yahoo.com (Sorin Gherman) writes: > Is it possible to handle https using Python's libraries? If so, what's > involved with using Python to read my hotmail messages, for instance? The urllib module can handle https but you're going to need a bunch of other hair to read hotmail messages too. Hotmail uses a lot of javascript to control the browser and you're going to have to figure out what it's doing to get at the relevant info in it. From DennisR at dair.com Tue Sep 17 14:04:24 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Tue, 17 Sep 2002 18:04:24 GMT Subject: using python as cgi on apache unix References: Message-ID: > I do get the correct results [from shell] > I must > have Apache configured in such a way on the one machine that it is confused. Sounds right to me. The command line test was to see if the problem was unix related. It does not sound like it. Note that on a virtual host, "/" can be a different directory at command line vs. in a cgi file. -- Dennis Reinhardt http://www.dair.com From aleax at aleax.it Tue Sep 17 17:50:24 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Sep 2002 23:50:24 +0200 Subject: Will "Python in a Nutshell" be too short? In-Reply-To: <5.1.1.6.0.20020917181205.035d0a58@spey.st-andrews.ac.uk> References: <5.1.1.6.0.20020917181205.035d0a58@spey.st-andrews.ac.uk> Message-ID: <02091723502402.21243@arthur> On Tuesday 17 September 2002 20:46, Hamish Lawson wrote: > O'Reilly doesn't yet list the forthcoming "Python in a Nutshell" by Alex It's being final-edited right in these days. > Martelli, but according to Amazon.com's page for the book, it will have > 400 pages. Is that indeed the plan? I know that O'Reilly aims to keep fat > out of its books, and that Alex is striving to be comprehensive yet > concise, but I worry that the book's proposed length will simply be too > short to cover the material I'm hoping will be included. That was my original dream. I think that, to some extent, the usefulness of a book can be inversely proportional to its bulk. However, the need to cover a wide variety of subjects, AND to provide tutorial info and examples as well as reference info, bids fair to put paid to my dreams. I fear the book will be closer to 600 pages than to 400:-(. > I regularly consult David Beazley's "Python Essential Reference", but the > usefulness to me of this otherwise excellent book is compromised by the > number of (platform-independent and not obsolescent) standard modules and > packages that had to be left out of the book's 380 pages (htmllib, > telnetlib, urllib2, CongigParser, unittest, tkinter, xml, etc.). Out of those you list, I don't cover CongigParser (non-existing) nor even ConfigParser (existing, but I had to weigh its importance vs a zillion others). The number of pages I had to devote, in particular, to tkinter and xml, still boggles my mind -- yet, I do see that they add to the book's usefulness more than they take away from it. > Many of us were hoping that "Python in a Nutshell" would not only be a > comprehensive reference of pretty much all of the modules in the standard > library that aren't obsolescent or platform-specific, but would also > cover some of the most popular third-party libraries - e.g. DB-API, PIL, > mxDateTime, Numeric, win32all, wxPython, mod_python, ReportLab. I cover some of these, but not nearly all -- DBAPI yes, PIL no, mxDateTime yes, Numeric yes (and then some!), win32all no (_no_ platform-specific stuff!), and so on. And after mature deliberation I decided I just *had* to cover many you don't mention, such as twisted.internet, Cheetah, Jython's interfacing to Java libraries, etc. > My congratulations to Alex and O'Reilly if they reckon they can somehow > manage to fit this all into just 400 pages; but if this won't be > possible, as I worry must be the case, then may I make a plea for the > book's length to be reconsidered. It would be good to have a one-stop > Python reference book that would be a suitable companion to the > task-oriented "Python Cookbook" - I'm hoping "Python in a Nutshell" can > still be that book. I think you'll be happier with the book size than I'll be -- even though not fully satisfied of course (1000 pages would apparently not suffice for your desires, definitely not when including examples and discursive/ tutorial coverage of at least some parts). _My_ personal dream is more of "SQL in a Nutshell"... the most value-packed 300 pages I've ever seen! But I won't reach it in "Python in a (cocoa)Nut-shell" - that's for sure!-) > By comparison, O'Reilly's "Perl in a Nutshell" is 800 pages and has the I used it throughout as my bete noire:-). Py iaN won't be THAT large -- not QUITE that large -- though it will maybe end up closer to it than to my dream 400 pages. Alex From brian at sweetapp.com Tue Sep 24 14:38:08 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Tue, 24 Sep 2002 11:38:08 -0700 Subject: ANN: Pyana 0.6.0 Message-ID: <001c01c263f9$879487e0$df7e4e18@brianspiv1700> Pyana 0.6.0 has been released. Source and binary distributions are available at: http://sourceforge.net/project/showfiles.php?group_id=28142 Pyana is an extension module that allows Python scripts to access the Apache Group's Xalan XSLT transformation engine. For usage examples and other information, see: http://pyana.sourceforge.net/ What's new in this release? - Updated to use Xalan 1.4/Xerces 2.1 - A default ErrorHandler and ProblemListener are automatically installed when a Transformer instance is created. The global variables defaultErrorHandlerFactory and defaultProblemListenerFactory determine which classes are used. - Messages generated with xsl:message now appear correctly - Exception decoding is now done using a preprocessor macro instead of an include file. This should fix a build problem on some platforms e.g. HP-UX. - Better exception decoding of XSLExceptions Cheers, Brian From nhaggin at attbi.com Tue Sep 17 22:42:41 2002 From: nhaggin at attbi.com (Nicholas Haggin) Date: 17 Sep 2002 19:42:41 -0700 Subject: Yet another Tkinter and threads question Message-ID: <4936aa67.0209171842.12cacf2a@posting.google.com> After a short perusal of the group archives I haven't found anything answering the following, so here goes: I am polishing up the GUI for a client that uses FTP to submit MVS jobs to an IBM S/390, and am adding message boxes for exceptional circumstances i.e., user mistyped password, connection timeout, etc. To prevent locking up the GUI, all submissions spawn a thread, which calls a wrapper function around ftplib that does the right site-specific hanky-panky to make everything go smoothly. In the thread function, the code goes something like this: try: submit_job() except socket.error: showerror("Socket has barfed") except ftplib.error_perm: showerror("You mistyped your password") The call to showerror locks the program. Any thoughts? Older posts on other threading+GUI questions had mentioned that Tk was not thread-safe; has it become so, or is this still a tar-pit? Nick A.M.D.G. From henrik.motakef at web.de Mon Sep 23 14:20:22 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 23 Sep 2002 20:20:22 +0200 Subject: Session handling References: Message-ID: <871y7k1sbd.fsf@pokey.henrik-motakef.de> "dsavitsk" writes: > If the only state that needs to be maintained is a language variable, this > seems like a lot of work when a cookie will work fine. Not to mention that HTTP clients are supposed to indicate the user's preferred language in the Accept-Language header. From aleax at aleax.it Wed Sep 25 05:14:14 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 09:14:14 GMT Subject: Removing all occurences of a character from a string. References: Message-ID: Mike C. Fletcher wrote: > Under later Python versions (such as 2.2.1), you can do the following: > > attr = [[item.replace("'","") for item in element] for element in attr] > > Which is rather elegant IMO. It also has the side-effect of _not_ > rewriting the data in-place in your original list, instead just > replacing that list when we are finished creating the new list, which > may or may not be desirable for you. If it's NOT desirable, just assign to attr[:] tather than to attr. Alex From aleax at aleax.it Fri Sep 27 03:09:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 27 Sep 2002 07:09:37 GMT Subject: comparing all values of a list to regex References: Message-ID: Delaney, Timothy wrote: ... >> > elif matches != len(alist): >> > match_list = match_some >> > >> > match_list.append(alist) >> >> Yes, choosing a list first and then appending to the chosen >> list is nicer, but you cannot do that within the original >> specs (for all I know the match_some list might grow >> unbearably large over time, in this case). > > Hmm - why not? Ignoring that the original specs didn't actually *have* > that case, Not ignoring it, one would think the specs must be to do nothing special in that case. If your program was specified to "append to list1 if the time is exactly 11:22:33, to list2 if the time is exactly 17:26:35", would you consider it reasonable to make your program appent to list3 if it's any other time of day? The problem could be that the program is called a billion times, of which, say, about seven fall in the first case, about three in the second one, and all the rest in the "neither" category. If you extend the program's spec to append to another list when "neither" applies, your program will overflow memory and crash, while any proper implementation of the specs would work correctly. > choosing the list to append to, or doing it in-place is merely > an implementation detail. Except that, to meet the specs, you must NOT append to match_some, ever. It's quite possible of course that the specs where incorrect or incomplete, but just assuming that seems strange to me. > Of course, you would need instead to do something like: > > match_list = None > > if not matches: > match_list = match_none > elif matches == 1: > match_list = match_one > elif matches == len(alist): > match_list = match_all > > if match_list is not None: > match_list.append(alist) Right (I did much the same in my dictionary-version of this snippet) although of course the need for the final if is not most elegant. A good design pattern for such cases is Null Object, which Dinu Gherman showed in recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205 To quote him, """ Null objects are intended to provide first-class citizens as a replacement for the primitive value None. Using them you can avoid conditional statements in your code and express algorithms with less checking for special values. """ With this DP, your snippet would become: import null match_list = null.Null if not matches: match_list = match_none elif matches == 1: match_list = match_one elif matches == len(alist): match_list = match_all match_list.append(alist) The need for the guard goes away because null.Null is basically designed so you can call any method on it innocuously. Of course, you get more mileage out of it in more complicated situations. {0:match_none, 1:match_one, len(alist):match_all}.get( matches, null.Null).append(alist) gets greater benefit wrt the None-plus-guard. Of course, this more-concise snippet has a problem when len(alist) is 0 -- your snippet, like my original one, is not ambiguous in this case (appends to match_none), while a dictionary-display with two identical keys has behavior that is less obvious (I don't recall whether the Python language specifies which of the two repetitions of the same key "takes", but in any case most readers and maintainers of this code would be puzzled). Fortunately, the OP clarified (if I read his followup post correctly) than len(alist)==0 is a "can't happen" in his case. Alex From walto at vaag.cx Thu Sep 26 08:09:34 2002 From: walto at vaag.cx (walter hoolwerf) Date: 26 Sep 2002 05:09:34 -0700 Subject: html in xml problem Message-ID: <9a1d8b0f.0209260409.3b759cba@posting.google.com> Hello, I need to place some HTML code in an XML file en process it with python. The output is a bit weird. I've also used this way to place html code in XML with flash, worked fine. as you can see, I already tried replacing the newlines with nothing (or space), didn't work. The output should be instead of: < a > My browser wont accept the last. Who knows? Thanx in advance, Walto -------- xml file: <B>Welcome</B> code: #!/usr/bin/python2 from xml.dom import minidom, Node import string doc = minidom.parseString(open('han.xml').read()) for c in doc.documentElement.childNodes: if c.nodeType == Node.ELEMENT_NODE: for d in c.childNodes: print d.nodeValue.replace("\n", " ").replace("\r", " ") output: < B > Welcome < /B > From pedro_rodriguez at club-internet.fr Thu Sep 26 14:36:40 2002 From: pedro_rodriguez at club-internet.fr (Pedro RODRIGUEZ) Date: Thu, 26 Sep 2002 20:36:40 +0200 Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <3D911FE1.1050801@something.invalid> <7nHk9.172208$pX1.6117207@news2.tin.it> Message-ID: On Thu, 26 Sep 2002 19:22:11 +0200, Alex Martelli wrote: > Pedro RODRIGUEZ wrote: > ... >>>> But why use grotesque hacks in the first place? "a ? b : c" is a > ... >> Ada has two short-circuits operators : "and then" and "or else" that do >> the trick : >> if A and then B then >> ... >> end if; >> >> Looks cleaner to me. > > Ada's "and then" is like Python's "and"; Ada;s "or else" is like > Python's "or". Neither is like C's "a?b:c" (ternary operator), though > with some tricks boolean shortcircuiting operators can be used to > simulate ternary operators (a bit cumbersome in the general case). > > The reason > zz = a and b or c > is not the same thing as > zz = a ? b : c > is that, when a is true and b is false, the former returns c, while the > latter returns b. > I stand corrected the value of b should not be part of the condition but only of the result. > The tricks deal with ways to work around this problem, by ensuring that > and's RHO can never be false, e.g. > zz = (a and [b] or [c])[0] > If python had short-circuiting operators ('and then', 'or else'), this will be the ternary operator : zz = (a and then [b] or else [c])[0] The problem when talking about conditionnal expression should be to know what really matters in the context : - the short-circuit evaluation (only (a,b) or (a,c) are evaluated) - or the ability to pick a value in a list The first one isn't possible in a Python expression AFAIK, and the second one can be expressed as (b,c)[not a]. Pedro From Andreas.Leitgeb at siemens.at Fri Sep 20 17:18:19 2002 From: Andreas.Leitgeb at siemens.at (Andreas Leitgeb) Date: Fri, 20 Sep 2002 21:18:19 +0000 (UTC) Subject: lists in dictonaries ? References: Message-ID: xtian wrote: >> > You can put any python objects into a python dictionary, >> > even the dictionary itself... >> Oh, can I create a dictionary in Python that contains all those >> dictionaries that don't contain themselves ... ?-) >> *scnr*'ly yours. > Would it contain itself? if dict in dict: print "yeah" *scnr*'ly yours. From martin at v.loewis.de Wed Sep 4 03:17:58 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 04 Sep 2002 09:17:58 +0200 Subject: MD4 and DES for unicode strings (samba passwd file manipulation) References: Message-ID: Arcady Genkin writes: > Perhaps the problem lies with Unicode encoding? Samba's man page (see > the link below) says that the string is obtained by taking MD4 hash on > the password, represented as a string of 16-bit little-endian unicode > characters. There is a contradiction in this statement: You can't really MD4-hash "Unicode", as Unicode characters are values in range(0,2**21) - to MD4-hash, you need a byte string. However, the statement means that they use the UTF-16 encoding in its little-endian variant, which, in Python, is implemented in the utf-16le codec: >>> m = MD4.new() >>> m.update( u'111222333'.encode("utf-16le") ) >>> print m.hexdigest().upper() B66B458E27BD714F99A05EE3C479FBF1 m.update expects a byte string. If you pass a Unicode string, that gets converted with the system default encoding, which is "ascii", and in this case not appropriate. HTH, Martin From member at dbforums.com Mon Sep 16 22:09:17 2002 From: member at dbforums.com (hpyhpy) Date: Tue, 17 Sep 2002 02:09:17 +0000 Subject: string type in SWIG. Message-ID: <1822835.1032228557@dbforums.com> I define a class,it has string type member,and include ,how SWIG wrap it?Such as: in example.cpp //////////////////////////// #include using namespace std; class a { private: string aaa; }; //////////////////////////// How to do example.i? -- Posted via http://dbforums.com From kennethg at pd.jaring.my Fri Sep 27 23:44:29 2002 From: kennethg at pd.jaring.my (Kenneth Gomez) Date: Sat, 28 Sep 2002 03:44:29 GMT Subject: Local Python Server Installation References: <3d8b47c6.277669@news.jaring.my> <3d8c993c.2190426@news.jaring.my> <3d8d4009.375344@news.jaring.my> <3d947c26.2656654@news.jaring.my> Message-ID: <3d952575.1651269@news.jaring.my> Thanks Steve. At least now I know that my code is OK. I'll go look into the APache config Bible. Thanks again. Kindest regards, Kenneth. Cheers, Kenneth Gomez. From gerhard.haering at gmx.de Sat Sep 14 16:25:11 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sat, 14 Sep 2002 22:25:11 +0200 Subject: newbie-question: abstract classes In-Reply-To: <3D839852.2060405@snafu.de> References: <3D839852.2060405@snafu.de> Message-ID: <20020914202510.GA28307@lilith.ghaering.test> * T. Kaufmann [2002-09-14 22:13 +0200]: > Hi everybody, > > I have a problem: > > I want to create an abstract class but it doesn't work. > What' s wrong here? > > class Abstract: > > def __init__(self): return Better style is to use "pass" instead of "return" here. > def method(self): raise NotImplementedError > > class Concrete: [...] Use "class Concrete(Abstract):" instead. HTH, -- Gerhard From rob at diespammerdieuselesspython.com Wed Sep 18 16:38:39 2002 From: rob at diespammerdieuselesspython.com (Rob Andrews) Date: Wed, 18 Sep 2002 20:38:39 GMT Subject: linux python ideas Message-ID: <3D88E578.6010001@diespammerdieuselesspython.com> I'll be giving a presentation on Python to my local LUG (http://lugoj.org) in a few weeks, and would like to point out at least a few things that would be of particular interest to linux users. The idea is not "how to program in Python", which would take more than one quick presentation, but a one-off demonstration of ways in which Python is particularly useful for such a group. Any suggestions would be appreciated, since my notes are pretty generic so far. regards, Rob Andrews From jepler at unpythonic.net Wed Sep 4 13:57:47 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 4 Sep 2002 12:57:47 -0500 Subject: Program for ... HELP!!! In-Reply-To: References: Message-ID: <20020904175739.GE2111@unpythonic.net> kyro, One method is to perform LU decomposition of the matrix, then take det(U) which is simply the product of the elements on the diagonals. (det(A) = det(L)det(U) since A=LU, but det(L)=1 and U is triangular). You can find a description of LU decomposition in any decent numerical analysis text, or online. You could also try the search term "gaussian elimination". LU decomposition is probably expressible most clearly as iteration, not recursion. There is a method whose name escapes me which involves taking the sum of factors like (-1)^(j+k) * A_jk * det(A with the row and column passing through jk removed) which is naturally recursive, but this is not a "good" algorithm: it'll take much longer than the O(n^3) operations of LU decomposition. I don't know if there are better methods for finding determinants, the LU method is the only one explored at length in the text I have on hand. If you're having trouble representing matricies in Python, well, that's another matter. As another poster suggested, you should probably get the "Numeric" package. Jeff From jb at cascade-sys.com Wed Sep 25 15:25:52 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Wed, 25 Sep 2002 12:25:52 -0700 Subject: Getting started References: <3D911306.7080609@ucsd.edu> Message-ID: <3D920DC0.8040808@cascade-sys.com> Adam Taylor wrote: > This last is available at: > http://research.microsoft.com/Users/luca/Papers/TypeSystems.pdf I believe your interpretation is accurate for the most part. > Cardelli doesn't use the term "weakly typed" himself, but on page 5 he > seems to be say that "weakly typed" is the commonly used term for what > he calls "weakly checked". C is weakly checked, in his terminology, and > that's why it's unsafe. My read of page 5 is he equates his internal use of "weakly checked" with "weakly typed" and further suggest that the latter term is commonly used "in the literature," which it does seem to be. > But people on this thread seem to be using "weakly typed" to mean > roughly the same thing as Cardelli's "untyped". Which is fine, and > pretty close to Cardelli's terminology. But clearly the terms "untyped" > (=="weakly typed" on this thread) and "weakly checked" (=="weakly typed" > in common usage) are very different things. Well, some people here use the term casually and incorrectly, as a measure of quality of a language's object model, which I am sure you'll agree is completely inconsistent with most uses of the term, including Cardelli's. Interestingly, a google search on the term revealed that about 25% of the meaningful hits equated "weakly typed" and "dynamically typed" (the latter of which is what Cardelli calls "untyped"). The other 75% generally characterized strong vs. weak type systems in terms of "type safety", i.e., a mechanism for preventing "type errors," regardless of whether the checking is done statically or dynamically. [The list of references appears in a prior post to this thread.] I think your read of Cardelli overall is correct -- that Python, like Lisp, would be classified as "untyped" because it has no static type system. A literal reading furthermore defines "weakly typed" only in terms of static checking. However, I submit that his use is inconsistent with the more common use of the term. Too, I think this is actually a minor oversight in Cardelli's paper. His focus overall was static systems and I think he simply didn't give enough consideration to dynamically typed languages. E.g., he says "untyped" languages such as Lisp can be "safe" but he defines "weakly typed" only in terms of languages that do static type checking. I would argue that in the first place he misclasifies Lisp as "untyped". I suspect he took the naive view of Lisp, in which everything is a list, when in fact a rather wide variety of "objects" actually exist in a typical, mature Lisp system. Of course, Python and Smalltalk are better examples, in that they both have robust object type systems and are in principle very secure from a type checking sense. (Of course, there are probably things you can do with the compiler and debug class objects that violate type safety, making them both unsafe in general.) The primary distinction between safe and unsafe, strong and weak type systems revolves around the notion of whether or not "type errors" can be prevented by the type system. The distinction between typed and untyped is less interesting, except to use "untyped" as a way to eliminate a class of languages from further discussion. Within typed, there should be two sub-classes, based on whether type checking is primarily static or dynamic. This is more interesting and useful, and is consistent with "the literature" as far as I can determine. I furthermore have a conjecture that much of Cardelli's work on "judgments" would apply equally well to static and to dynamic systems. The important criterion is that the type system be secure and that the total collection of function x arguments definitions be unambiguous (at least during the sequence of computation of interest). Whether the checks take place at compile time or at runtime I don't think materially affects his theories. But I could be overlooking something in this regard. In any case, my own use of the term "weakly typed" and associated terms (strongly typed, type safety, etc.) in this thread have been consistent with "the literature" (though slightly inconsistent with Cardelli), in that I class Python to be "strongly typed" using "dynamic checking". That seems to be the consensus here. Only confusion has been about "weakly typed," and hopefully we're close to exhausting that topic.. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From edream at tds.net Thu Sep 12 16:24:26 2002 From: edream at tds.net (Edward K. Ream) Date: Thu, 12 Sep 2002 20:24:26 GMT Subject: Cursed newlines and readline() References: <6u5g9.11312$Da3.1133980@kent.svc.tds.net> Message-ID: <_J6g9.11$rJ3.11804@kent.svc.tds.net> Oh joy. Thanks very much for this reply. Edward From shalehperry at attbi.com Fri Sep 6 16:58:36 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Fri, 6 Sep 2002 13:58:36 -0700 Subject: Beginners Question - use of variables In-Reply-To: <1031345108.547.165.camel@martin.kleinerdrache.org> References: <1031345108.547.165.camel@martin.kleinerdrache.org> Message-ID: <200209061358.36506.shalehperry@attbi.com> On Friday 06 September 2002 13:45, Martin Klaffenboeck wrote: > Hello, > > Are newbies questions ok here? > > I've got a struktur like this: > > string string int timestamp > string string int timestamp > string string int timestamp > ... > > in Perl I used to save such a thing in a multidimensional array like > > array( > array(string, string, int, timestamp), > array(string, string, int, timestamp), > array(string, string, int, timestamp)) > > So how do I save that in python and how do I get fast to one of this > strings or int or timestamp... ? > > Martin my_list = [ ['sean', 'perry', 25, '20020906'], ['Martin', 'Klaffenboeck', 20, '20020826'], ] for entry in my_list: print entry[0], entry[2] # prints first string and the int tutor at python.org is a list especially for those new to the language. From pinard at iro.umontreal.ca Sun Sep 1 17:16:46 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Sun, 01 Sep 2002 17:16:46 -0400 Subject: Making regex suck less In-Reply-To: <874rd9phtd.fsf@pokey.henrik-motakef.de> (Henrik Motakef's message of "01 Sep 2002 22:37:34 +0200") References: <3d725881.345921@news.t-online.de> <874rd9phtd.fsf@pokey.henrik-motakef.de> Message-ID: [Henrik Motakef] > There is an Emacs Lisp package called "symbolic regexps" (or sregexp.el) > that lets you write regular expressions in standard lisp syntax, like > (sregexq bol (or "abc" "def")) instead of "^(abc|def)" (bol meaning > "beginning of line"). I don't see how that maps elegantly to Python syntax, > however. PLEX has a Python way to describe regular expressions. It is likely available stand-alone. I found the copy I use within the Pyrex distribution, see: http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From glingl at aon.at Sat Sep 21 14:52:01 2002 From: glingl at aon.at (Gregor Lingl) Date: Sat, 21 Sep 2002 20:52:01 +0200 Subject: Python 2.2.1 compatible with Tcl/Tk 8.4? References: Message-ID: <3D8CBFD1.4010808@aon.at> Martin v. L?wis schrieb: > Andrew Koenig writes: > > >>Now that Tcl/Tk 8.4 is out, can anyone tell me whether Python 2.2.1 >>will work with it? > > > It appears to work fine here, and I can't see a reason why it would be > incompatible. Notice that the setup.py of 2.2.1 is already prepared to > search for Tcl/Tk 8.4 on its own. > > Regards, > Martin 1. When working with Python 2.2.1, are there any advantages of using Tcl/Tk 8.4 over the version which comes with Python2.2.1 for Window? 2. Which steps would I have to perform, to change to the new version? Gregor Lingl From whisper at oz.net Sat Sep 28 21:34:09 2002 From: whisper at oz.net (David LeBlanc) Date: Sat, 28 Sep 2002 18:34:09 -0700 Subject: Best way to create a class dynamically on the fly? In-Reply-To: <3D96511D.2040407@4-am.com> Message-ID: I understood the question as 'what do you stuff into a variable to make it behave like a class at runtime', not 'when is a class declaration is used to create a class instance.' David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Evan > Sent: Saturday, September 28, 2002 18:02 > To: python-list at python.org > Subject: Re: Best way to create a class dynamically on the fly? > > > Robert Oschler wrote: > > What is the best way to create a Python class dynamically at runtime? > > ALL Python classes are created dynamically at runtime. The following is > not a declaration in the sense that you're accustomed to from C/C++, it > is normal code executed when the containing file is run (or imported): > > Cheers, > > Evan @ 4-am From bobx at linuxmail.org Fri Sep 27 18:05:54 2002 From: bobx at linuxmail.org (Bob X) Date: Fri, 27 Sep 2002 22:05:54 GMT Subject: Is Boost Python version 2 ready? References: Message-ID: <6D4l9.12184$Lg2.3654433@news2.news.adelphia.net> "Terry Reedy" wrote in message news:CG2l9.263192$216.10040127 at bin4.nnrp.aus1.giganews.com... > > Not to exactly answer... from post on PyDev list, I believe they want > to test it with Python 2.2.2 (due in about 10 days?) before calling it > finished. > > TJR Is there a page up saying what 2.2.2 will give us? Bob From jepler at unpythonic.net Mon Sep 2 20:37:40 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 2 Sep 2002 19:37:40 -0500 Subject: Making regex suck less In-Reply-To: <1031008966.343893@ampungk.ozonline.com.au> References: <3d725881.345921@news.t-online.de> <1030962064.628232@ampungk.ozonline.com.au> <1031008966.343893@ampungk.ozonline.com.au> Message-ID: <20020902193731.A948@unpythonic.net> On Mon, Sep 02, 2002 at 09:23:18PM +1000, John La Rooy wrote: > Carl Banks wrote: > > >>It would be more likely to look like this (I haven't put too much > >>thought into this) > > > > > >No kidding. > > > > > > > >>"anything,anything,anything,same_as_3rd,same_as_2nd,same_as_1st" > >>or would you like to suggest something else? > > > > > >How about: > > > >pattern = Group(Any()) + Group(Any()) + Group(Any()) \ > > + GroupRef(3) + GroupRef(2) + GroupRef(1) > > > Err symantically that's exactly the same as the re and my suggestion > only the syntax is different. It's still nothing like saying > > pattern = "6 character palindrome" Do you mean something like this? def palindrome_re(n): pat = ["(.)" * ((n+1)/2)] for i in range(n/2, 0, -1): pat.append("\\%d" % i) return "".join(pat) With a little work, you can extend this to use named groups and named backrefs as well, so that you can use it as a building block for larger patterns: def Any(): return "." def Group(s, g): return "(?P<%s>%s)" % (g, s) def Backref(g): return "(?P=%s)" % g def Or(*args): return "|".join(args) def palindrome_re(n, p): pat = [Group(Any(), "%s%d") % (p, i+1) for i in range((n+1)/2)] for i in range(n/2, 0, -1): pat.append(Backref("%s%d" % (p, i))) return "".join(pat) I think that building REs in functions is a great approach for more complex REs. >>> q = re.compile(palindrome_re(7, "a") + palindrome_re(6, "b")) >>> q.match("abcdcbaxyzzyx") <_sre.SRE_Match object at 0x401c4f00> >>> _.groupdict() {'l4': 'd', 'l2': 'b', 'l3': 'c', 'l1': 'a', 'i1': 'x', 'i3': 'z', 'i2': 'y'} >>> q = re.compile(Or(palindrome_re(7, "a"), palindrome_re(6, "b"))) >>> q.match('abccbb') >>> q.match("abcdcba") <_sre.SRE_Match object at 0x401c4f00> >>> q.match("abccba") <_sre.SRE_Match object at 0x402e5020> Jeff From aahz at pythoncraft.com Thu Sep 19 10:29:02 2002 From: aahz at pythoncraft.com (Aahz) Date: 19 Sep 2002 10:29:02 -0400 Subject: where is the __dict__ ? References: <3d89b79b$1@news.sentex.net> Message-ID: In article <3d89b79b$1 at news.sentex.net>, Peter Hansen wrote: >black wrote: >> >> my book said all dictionaries have __dict__ method but couldnt find >> it by using dir(), where is it ? > >Your book is probably wrong, since dictionaries don't have a __dict__ >method. In 2.2 their *classes* do, although dir() still doesn't show >it. __dict__ is an *attribute*, not a method: class C: a = 1 print C.__dict__ print C().__dict__ x = C() x.foo = 5 print x.__dict__ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From tchur at optushome.com.au Fri Sep 20 17:57:57 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 21 Sep 2002 07:57:57 +1000 Subject: saving state in Python/CGI References: <5.0.0.25.2.20020920134912.00ad3230@hms.harvard.edu> Message-ID: <3D8B99E5.B80E5287@optushome.com.au> Frank Gibbons wrote: > > Hi, > > I've been using Python (and Jython) for about 5 months now. So far, so > great. I'm building a CGI app that has about 5 different stages, and I need > to maintain state between them. Specifically, it's a scientific tool that > requires the user to upload a (possibly quite large) datafile, processes > it, does some computation, then hands it back (formatted) with results. > > I need access to the data on each page, yet don't want to pass it as a > hidden field, because of its potential size. In Perl, I could just use the > save() method from CGI.pm to save the form on the server side, pass a > session key in a hidden field, then retrieve the data using the key. For > the life of me, I can't find an equivalent way in Python. cgiFormStorage > looks like a dictionary, but it's immutable, so you can't retrieve data > from disk and add it to the form. cgi.py appears to have no analog to > CGI.pm's save() method, at least not that I've been able to find. I've > tried pickling the form, but that doesn't work either (it saves something > to disk alright, but not the large data retrieved from a multi-part form > file upload). > > Perhaps I've missed something. Maybe that's just not how you do things in > Python. Can anyone help? You need to use one of the (many) Python Web app frameworks which help (to greater or lesser degrees) with storing state and other typical Web app tasks. There is a list of such frameworks available at http://www.python.org/cgi-bin/moinmoin/WebProgramming Of these, I have only used Albatross, but I can heartily recommend it - it was specifically designed with highly stateful applications in mind, is elegantly designed and well written and has excellent documentation and the authors are very helpful. We use it for a range of quite complex epidemiological applications. However, many of the other frameworks list on the above site are also reputed to be very good and you should consider all of them before making a choice. Tim C > > Thanks, > > -Frank Gibbons > > PhD, Computational Biologist, > Harvard Medical School BCMP/SGM-322, 250 Longwood Ave, Boston MA 02115, USA. > Tel: 617-432-3555 Fax: > 617-432-3557 http://llama.med.harvard.edu/~fgibbons > > -- > http://mail.python.org/mailman/listinfo/python-list From rsrchstr at hotmail.com Sat Sep 28 11:18:47 2002 From: rsrchstr at hotmail.com (mike henley) Date: 28 Sep 2002 08:18:47 -0700 Subject: 'File name' is not recognized as an internal or external command, operable program Message-ID: <576c1752.0209280718.331fe456@posting.google.com> rsrchstr at hotmail.com (mike henley) wrote in message news:<576c1752.0209271443.1ea61518 at posting.google.com>... > i am running windows xp which was working fine until the following > problem occured... > > in the command prompt window (as well as run...), whatever program, > exe, batch file... etc i enter returns the following message > > 'File name' is not recognized as an internal or external command, > operable program or batch file > > these are my environment variables > > ComSpec > %SystemRoot%\system32\cmd.exe > Path > C:\ruby\bin;C:\Python22;C:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem > PATHEXT > .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyc;.pyo;.pyw;.pys;.RB;.RBW > > previously the command prompt worked just fine... this happened in the > past few days; my recent installations include activestate's perl, > python, tcl, pragmatic programmer's ruby, gnu cygwin, apache 2, zope, > realone player > > does anyone know what i should do to fix this and restore command > prompt functionality? problem solved; activestate tcl binary binstallation is the offending app. windows XP has user specific environmental variables and universal environmental variables that affect all users, and while all other applications mentioned above make changes to universal variables, - as you can see the path above is mostly correct and looks right when u look at it, but doesn't work, which was puzzling - activestate's tcl installation makes changes to user specific environmental variables, which override and make universal variables, it seems, unusuable, and apparently, not read by the machine, as not only the command prompt and "start|run..." were not working, but every other .com, .exe, .bat that is called through them, (.exe would still work if clicked on from explorer, but not through command prompt or "start|run...") the solution that worked was to delete the path and pathtext entries from the user specific variables that were entered by activestate's tcl binary installation and move them into the universal variables, and with this the command prmopt and "start|run..." both worked, as well as the beloved cygwin bash i searched the internet, and usenet, for a solution to this problem, i found none, nothing on microsoft knowledgebase or newsgroups, i even went on irc to many technical newsgroups and no one knew what to do, the replies i had on usenet groups, though i thank all who tried to help, didn't work. (p.s. advising the poster to start a new command windows for the environmental effects to take place is not a good reply when the poster said he already restarted the machine, but thanks anyway to those who suggested it for their wish to help :):) ) i had to think up the solution myself, which took some time, and i post it here if anyone encounters this problem in the future, as windows XP no longer leads you to directly edit autoexec.bat, (that, and also even if it did, regedit or sysedit no longer work when the command prompt and start|run no longer work), go to start | control panel | system | advanced | environmental variables and look at not only system variables, which are universal, but notice too the user specific variables and move any entries not preceded by "documents and and settings" (well, this is a generalization, it was true in my case, but may not be so in urs, so try to work out which should belong in the system variables instaed of the user variables) to the system variables, restart the machine and see if it works this seems a rather simple thing, but it is a rather unexpected one, as system variables look right when you look at them, and if you're not experienced with windows xp, you may not suspect that user specific variables override system variables and render them unreadable p.s. i'll email this to activestate, but as i heard that most of the code in activestate distribution is community contributed i post this to comp.lang.tcl too From phr-n2002b at NOSPAMnightsong.com Fri Sep 20 20:29:34 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Sep 2002 17:29:34 -0700 Subject: e vs exp()? References: Message-ID: <7xr8fofamp.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > What was your basic approach? Power series? Rational function? > Continued fraction? ??? > http://functions.wolfram.com/ElementaryFunctions/Power/ > gives 343 formulas (many only relevant to complex domain) but doesn't > seem to indicate which Mathematica actually uses (trade secret I > presume). Mathematica has to work to arbitrary precision and would use totally different methods than what a fixed-precision routine would use. See "Numerical Recipes" by Press, Teukolsky, et al, for a reasonably digestible explanation of how to do this stuff. Note that true numerics gurus have some problems with this book, but it will at least give you an idea of what's going on. From jslowery at hotmail.com Sat Sep 14 16:35:08 2002 From: jslowery at hotmail.com (Jeremy Lowery) Date: Sat, 14 Sep 2002 15:35:08 -0500 Subject: CPython detecting read-only attributes. References: Message-ID: I believe I found a hacky way to do this. I am sure that this isn't the fastest way. I wonder if it can easily be shot down. static int proto_setattro(HyProtoObject *self, PyObject *name, PyObject *value) { int res; PyObject *tmp; PyObject *etype, *evalue, *etb; res = PyObject_GenericSetAttr((PyObject *)self, name, value); if(res != -1) return res; /* if we can get the attribute with GetAttr, then it must be readonly. */ PyErr_Fetch(&etype, &evalue, &etb); if(etype == NULL) { PyErr_SetString(PyExc_SystemError, "No error object found after a failed " "attribute lookup."); return -1; } tmp = PyObject_GenericGetAttr((PyObject*)self, name); if(tmp != NULL) { /* reference found, readonly */ Py_DECREF(tmp); PyErr_Restore(etype, evalue, etb); return -1; } PyErr_Clear(); /* continue with custom processing */ J Lowery From marklists at mceahern.com Mon Sep 30 17:41:18 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 30 Sep 2002 16:41:18 -0500 Subject: a question about mailman In-Reply-To: Message-ID: [Martin v. Loewis] > I'm not sure I understand this question: Do you want to add the URL of > the list archive to the footer, or the URL for the specific message? The URL for the specific message. > Adding the URL for the entire archive is easy (it only varies with the > list, not with the message), so I assume you want to add the URL for > the message itself. Correct. > Yes, yes, and no. I believe the trick is that, at the point of sending > the message, you cannot know the URL that the message will get in the > archive. Finding out that URL is particularly tricky in presence of > external archivers. Hmm, when I glanced at the code it looked like the order of processing in the pipeline was for the message to pass through the Archiver before the Dispatcher, so I just simplistically assumed: 1) that the Archiver added enough information to the message so that; 2) by the time the message got to the Dispatcher, you'd have enough information to format a pseudo string like this in the footer: %(base_archive_url)s/%(message_archive_relative_url)s Sadly, I haven't installed Mailman yet, so I can't test my hypothesis. Thanks for the feedback. Cheers, // mark From fetus at AUTO Thu Sep 26 16:32:06 2002 From: fetus at AUTO (A. Dimsdale and A. Moser) Date: Thu, 26 Sep 2002 20:32:06 GMT Subject: Pythonwin (win32all build 148) on Python 2.2.1 on Win2K, bogus syntax e References: Message-ID: A. Dimsdale Fetus A. Moser writes: >"Neil Hodgson" writes: >>Aaron Dimsdale and Alex Moser: >>> Pythonwin barfed on the quote marks marked by carets, returning: "Failed >>to run script - >>> syntax error - invalid syntax". >> Try turning on View | End-of-line markers to see if you have non-standard >>line endings such as pure carriage returns, which cause just this sort of >>error. On Windows, you want line endings to be carriage return + line feed. >> Neil [snip] Well, I went in and manually edited the EOLs on every code line in the file. (Fun fun fun.) As it turns out, the cause of the problem is likely the difference between DOS-style and Unix-style EOLs. Alex and I jointly own an account on my Linux box at home, where we keep the latest version of the script. Alex does most of the coding on our script, and I just do other stuff like looking over the code when it slaps him, adding fixes and/or minor features, etc. Well, since he does most of the coding, he had the script on his work comp when we were at work on Tuesday, and I had him upload it to my Linux box so I could grab it from my work box by FTP, and through the Win-to-Linux-to-Win transfer the EOLs apparently got funkified. Thanks again for the EOL tip. --Aaron L. Dimsdale From BPettersen at NAREX.com Wed Sep 18 22:20:39 2002 From: BPettersen at NAREX.com (Bjorn Pettersen) Date: Wed, 18 Sep 2002 20:20:39 -0600 Subject: How to build Python 2.2.1 on Windows? Message-ID: <60FB8BB7F0EFC7409B75EEEC13E2019201253451@admin56.narex.com> > From: David Lees [mailto:debl2nonospammmmyy at bellatlantic.net] > > I have been playing with Python for awhile and would like to > know how to try building Python on a Windows machine that has > MS C++ version 6. Is there a standard download that is > configured to do this? If not could someone point me in the > direction of information on builds? I downloaded > Python-2.2.1.tgz.tar on my Win98 box and WinZip 8 does not > even seem to know how to unzip it. I just transfered the tar > file over to a linux box and it unzips without and problem > using tar. The README seems to only talk about linux/unix > type systems. The PCBuild directory contains pcbuild.dsw. -- bjorn From josh_py at sautez.com Tue Sep 17 03:35:23 2002 From: josh_py at sautez.com (josh_py at sautez.com) Date: Tue, 17 Sep 2002 00:35:23 -0700 Subject: using python as cgi on apache unix References: Message-ID: "Gerhard H?ring" wrote in message news:mailman.1032245299.5563.python-list at python.org... > * josh_py at sautez.com [2002-09-16 22:48 -0700]: > > All, > > > > I have developed a python solution to run and connect to a mysql database. > > I did all my development under windows apache 1.3.26 and python 2.2.1. I > > know want to move this to my unix server. Unfortunately, no matter what I > > do I can not get apache on my linux box to execute any python scripts. I > > get the following errors in apache: > > > > Premature end of script headers: /var/www/html/cgi-bin/test.py > > > > I have all the settings in apache I believe to be correct. It complains > > that the file is not executible if that is not set. Other CGI works fine. > > > > test.py looks like: > > > > #!/usr/bin/python2 > > > > print "\n\n" > > print "Content-Type: text/html\n\n" > > print "hello" > > The first print "\n\n" is an error. It was simply luck that this was > running anywhere else as expected. Just delete this line and your hello > world cgi script should run fine. > > Also, to test wether Python CGI scripts work, you can always simply use: > > #! [path to python ...] > import cgi > cgi.test() > > -- Gerhard > Gerhard, Thanks for the test scipt. Unfortunely that runs fine at a command prompt but same error results under apache. Josh From sismex01 at hebmex.com Mon Sep 9 16:26:50 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 9 Sep 2002 15:26:50 -0500 Subject: a re question Message-ID: > > Hi, > I have a file with lines of the format: > > 001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23 > 001 Xya FGh 143557789 7 100 09/05/2002 20:23:23 > Are the fields are always fixed length? > I am trying to extract the 9 digit field and the single digit field > immediatley after that. > > When I use Visual Regexp to try out the regexp > > (\d{9,} {3,}\d) > > it highlights the 2 fields exactly. > > But when I use the following Python code I get None: > > >> s='001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23' > >> p = re.compile(r'(\d{9,} {3,}\d)') > >> print p.match(s) > >> None > > Could anybody point out where I'm going wrong? > > Thanks, > You could be a bit more explicit with your regexp. Using the input you gave: > 001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23 > 001 Xya FGh 143557789 7 100 09/05/2002 20:23:23 I'd think something like this is better: rx = re.compile(r"\d+\s\D{9}\s(\d{9})\s+(\d+)") And that gives us: >>> import re >>> rx = re.compile(r"(\d{9})\s+(\d+)") >>> s = """ ... 001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23 ... 001 Xya FGh 143557789 7 100 09/05/2002 20:23:23 ... """ >>> rx.findall(s) [('123456789', '7'), ('143557789', '7')] >>> Something like that. -gus -- Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From lee100 at sport.rr.com Wed Sep 18 19:10:36 2002 From: lee100 at sport.rr.com (Lee Gray) Date: Wed, 18 Sep 2002 23:10:36 GMT Subject: Python GUI app to impress the boss? References: Message-ID: Chris Liechti wrote: > "Gray, Lee P." wrote in >> Yeah, I tried to download from CVS, but being a complete noob >> couldn't figure out how, short of tracking down and copying and pasting >> every updated file. Any tips would be appreciated. > > you're on windows right? then grab http://tortoisecvs.sf.net and install > the latest version. after that right click on an empty folder in the > windows explorer and select "cvs checkout", copy and paste the "CVSROOT" > in the dialog. you can find the cvsroot, or at least how it looks like on > the "browse cvs" page that you have apparently found. > > the home of cvs is http://www.cvshome.org and these are interesting sites: > http://www.loria.fr/~molli/cvs-index.html, http://cvsbook.red-bean.com/ Yep, Windows at work, mostly Linux at home. I'll check this out at work tomorrow. Thanks for the info! Lee From gerhard.haering at opus-gmbh.net Thu Sep 19 04:36:02 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 19 Sep 2002 08:36:02 GMT Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <23891c90.0209190014.26c5bb9@posting.google.com> Message-ID: Paul Boddie wrote: > Taking a look at pyPgSQL, as the only database module I have installed > that actually readily documents such things (and that should tell you > something), it would seem that monetary amounts are converted to floating > point numbers - surely the first thing one would want to avoid in > manipulating financial data. Yeah, we should probably change PgMoney to use PgNumeric, which is a fixed-point type that uses Python's long internally. I've added it to the TODO list [1]. Btw. the MONEY type is deprecated in favour of NUMERIC and DECIMAL under PostgreSQL [2] -- Gerhard [1] http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/pypgsql/pypgsql/TODO?rev=1.2&content-type=text/vnd.viewcvs-markup [2] http://www.postgresql.org/idocs/index.php?datatype-money.html From eric.brunel at pragmadev.com Fri Sep 13 09:06:24 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 13 Sep 2002 15:06:24 +0200 Subject: Pmw.ScrolledText programatically scrolling References: <3D81D44E.C5FC4A8B@mill.co.uk> Message-ID: Joe Connellan wrote: > I've got a Pmw.ScrolledText() that I'm using as a log and I've written > an addToLog() method like so: > > def addToLog(self, logString): > self.logScr.configure(text_state = 'normal') > self.logScr.insert(END, logString) > self.logScr.configure(text_state = 'disabled') > > I now want it to scroll when I add a line so the user doesn't have to > constantly scroll down to view the most recent lines. > > I can't find any info on doing this with ScrolledText or its text > component - do I need to reposition the scrollbars for it to scroll? Adding: self.logScr.see(END) should do the trick. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From i.linkweiler at web.de Tue Sep 17 14:18:35 2002 From: i.linkweiler at web.de (Ingo Linkweiler) Date: Tue, 17 Sep 2002 20:18:35 +0200 Subject: Logical Programming with Python? Message-ID: <3D8771FB.4000600@web.de> Hello, i am looking for examples for logical programming (Prolog like) with Python. I have found some projects, but no examples how to use them. Most of them seem "unuseable" or only can solve equations: * PyLog (provides a simple way to write logic terms, variables and atoms)- http://christophe.delord.free.fr/en/pylog/logic.html * Logilab constraint package: a constraint satisfaction problem solver written in 100% pure Python - http://www.logilab.org/python-logic/constraint.html * Holmes (dead) * Formula (not available) * CLIPS Wrapper (unuseable) Do you know more sources for logical programming, or do you have some examples ? Ingo From contact at realspace.org Sat Sep 21 19:13:23 2002 From: contact at realspace.org (Bernhard Glueck) Date: Sun, 22 Sep 2002 01:13:23 +0200 Subject: Very complex Python/C++ embedding/extension question(s) Message-ID: <3d8cfd3c$1@news.swissonline.ch> Hi there I am developing a new multimedia/game/vr architecture, and at the moment i am trying to embed python as a scripting language. I have a slew of questions about the Python/C API.. At first let me elaborate on my unique architecture. In my "engine" as i call it an application is built using "Actors" which are Classes that interact over a "reflection system". This has been implemented using a custom template based code on the C++ side, but was written so that any language could interact with it. Every Actor derives from teh C++ class "Actor" which defines some basic operations and the call protocl.. e.g actor.Call("MyMethod",arg1,arg2,arg3); will call the method "MyMethod" on the actor using the arguments passed. This is achieved by having a type descriptor for every Actor that is stored in a global list. The type descriptor dervies from the base class "Type" and knows which methods a class has. e.g class MyActor: public Actor { } has a type descriptopr class MyActorType : public Type { }; that is registered into the global type list. Then when one calls a method on an actor the appropriate type descriptor is retrieved from the global list and the method is caleld using the descriptor. So far so good .. This works like a charm, and since the type descriptors are defined using some easy to use macros, writing new classes is very easy, and allows actors to be defined in extension modules (DLL files on windows ) for my engine. In fact the main engine only contains one actor for loading DLL files .. all the actors are in other DLLs... this way i can seperate my modules very nice, and extend the engine at runtime.. Actors are then instantiated using XML and put together to achieve functionality. Again this works nice.. Actors are by the way internally stored using a smartPointer class of mine for automatic reference counting/garbage collection.. Now i want to extend my engine using Python so that Actors can also be written in Python , and existing actors can be derived from in Python, as well as Python Actors can be called from C++ in the same way as others.. I wanted to do this that way derive a "PythonType" class from "Type" and store any classes that derive directly or indirectly from C++Actor in it .. so that PythonType works the same way as MyActorType but for all Python classes in the script files.This would allow me to treat python actors like C++ actors ( for my tools especially like the editor for game levels ) How would one go about this ? I would need to find out all classes that are currently in the (embedded ) python interpreter, check if it derives from the C++Actor class,and if yes generate an instance of PythonType for it which would know the methods of the python class.. How to do this ? Second, i would need to export the C++ Actor base class and all other C++ Actor derived classes to python, so that one can write an actori n python that derives from one of the already written C++ actors.. I know of all the Wrapper generates etc, and read the tutortials on embedding and extending python, but note that i do not know at COMPILE Time of the C++ part which actors are there ( since new modules can be loaded at runtime ) so this export process needs to be dynamic..... Any ideas ? And third.. Since the engine deals with actors only, and does not know the exact type, the python actors would have to have methods like def MyMethod( actor ) which is just an Actor Smart Pointer wrapped.... Is it possible to have a "method hook" in (with the PythonC API) that would be caleld every time i try to invoke a method on this actor ? This way i could check the actor concrete type, and determine which methods it has ... e.g so that actor.DoSomething() Would internally use the actor.Call("DoSomething" ) protocol in C++ ..... just translating native Python code to my own method of calling methods on classes(actors) Remeber i do not know at compile time which methods an actor supports..... so this would need to be done using some sort of MethodCallHook..... From tjreedy at udel.edu Sat Sep 21 13:49:05 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 21 Sep 2002 17:49:05 GMT Subject: if...else on the same line? References: Message-ID: "David Garamond" wrote in message news:mailman.1032622182.9002.python-list at python.org... > i'm sorry for this terrorizingly basic question, but is it possible at > all to write an if ... else statement on a single line in python? If you mean something like if x == 1: y=3; else z=4 then no. Keywords that introduce blocks (suites) must be first word on line: I believe this includes try, except, finally, for, while, if, elif, else, def, and class. A statement using a conditional expression is something else: y = (x==1) and 3 or 4 #for example Terry J. Reedy From michaels at one.net Thu Sep 12 04:08:25 2002 From: michaels at one.net (Michael Schneider) Date: Thu, 12 Sep 2002 04:08:25 -0400 Subject: iterators and generators, is this the Python Way??? References: <3D7FF921.2040305@one.net> Message-ID: <3D804B79.9070003@one.net> Just, Thank you very much, I like this approach. I was under the mistaken impression what the iterator needed to do. Mike Just wrote: >In article <3D7FF921.2040305 at one.net>, > Michael Schneider wrote: > >>class FastFile: >> def __init__(self, filename): >> """ Read in entire file into memory""" >> f = open(filename, 'r') >> fileContents = f.read(); >> self.lines = fileContents.split('\n') >> f.close() >> >> def __iter__(self): >> return self.fastFileGen() >> >> def fastFileGen(self): >> for line in self.lines: >> yield line >> > >I would write the __iter__ like so: > > def __iter__(self): > for line in self.lines: > yield line > >Same effect, less code... > >Just > From sholden at holdenweb.com Mon Sep 30 13:41:45 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 30 Sep 2002 13:41:45 -0400 Subject: McMillian installer + win32com.client.constants - how to use them together? References: <9ff6b66.0209300856.5fcdf961@posting.google.com> Message-ID: "vtail" wrote ... > Greetings, > > can anybody please explain me the Right Way to use McMillian installer > with application that uses constants from MSWord library? > Gordon MacMillan reads this list when he has time, but you should be aware that there is a mailing list just for the users of the installer package -- see http://trixie.triqs.com/mailman/listinfo/installer for details. > I've generate them with win32com/client/makepy.py and use them in my > code via > ====> > import win32com.client > ... > a = win32com.client.constants.wdBlack # application crashed here > ... > <=== > > When I build .exe from my applications it is crashed on marked line > with AttributeError exception. > > I've tried to study this subject myself, but now I'm totally confused > with all this gencache.EnsureModule(), prog_id, CLSID etc. I can't > find any clear documentation on the subject. > > I'll greatly appreciated any help on this, even RTFM links ;). > I'm *guessing* that the installer hasn't been able to define that the win32com.client package's submodules need to be included. To verify this is the error you might try including an explicit import win32com.client.constants in the appropriate module and see if the error goes away. There are things you can do in installer if that's the case, but I'm not the best person to advise. regards ------------------------------------------------------------------------ Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From joe.sixpack at quartercase.com Tue Sep 24 17:39:19 2002 From: joe.sixpack at quartercase.com (joe sixpack) Date: Tue, 24 Sep 2002 21:39:19 GMT Subject: Running with arguments in IDLE? Message-ID: <3D90DB87.4797EA7@quartercase.com> Probable dumb question of the day... I do most of my work in Python with IDLE and love it. If I need to change a parameter in a script I've written, I usually just change a variable by editing the script, then run it. Now I've gotten to where I need to write a script that runs from a shell (Windows2000) command line. I know to use sys.argv[x] to get the arguments. What I don't know is how to run the script from within IDLE and specify the argument to use when it is run. In Pythonwin, 'RUN'ning a script brings up the dialog box in which arguments may be specified. How is this done in IDLE? Thanks! From peter at engcorp.com Sun Sep 22 14:23:51 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 22 Sep 2002 14:23:51 -0400 Subject: sys.ps2 assignment has no effect References: Message-ID: <3d8e0aae@news.sentex.net> Lance wrote: > I'm running the latest Python on Windows XP. The default installed secondary > string appears to be blank spaces rather than an ellipse. The following has > no effect: > > import sys > sys.ps2 = '... ' What does "print '...'" show you? Maybe this is just a phenomenon of your current font? From a.clarke11 at pop.ntlworld.com Mon Sep 16 18:23:58 2002 From: a.clarke11 at pop.ntlworld.com (a.clarke11) Date: Mon, 16 Sep 2002 23:23:58 +0100 Subject: doh References: <3d83fa2c$0$24041@echo-01.iinet.net.au> <3d84a3ed$0$24051@echo-01.iinet.net.au> Message-ID: <3D8659FE.D406C4F8@pop.ntlworld.com> > A deer... From r.kalbermatter at hccnet.nl Wed Sep 18 17:33:22 2002 From: r.kalbermatter at hccnet.nl (Rolf Kalbermatter) Date: Wed, 18 Sep 2002 23:33:22 +0200 Subject: Python as shared library on Unix In-Reply-To: Message-ID: Please disregard this post. I just found out that the current 2.3 CVS version supports shared library builds. I was working with a 2.2.1c2 source code package. There is probably little chance that this will be officially backported to the 2.2.1 branch of Python? > I'm currently in the process of porting a Python embedding from > Windows to Linux and have come across an appearent problem. > > Under Windows I have linked my app dynamically to the pythonXX.dll using > LoadLibrary/GetProcAddress and that works very nicely. Under Linux I see > no option to build a python.so.2.2.1 or similar to link my application > to with the dl* functions. Rolf Kalbermatter From eugene1977 at hotmail.com Sat Sep 14 22:52:20 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Sun, 15 Sep 2002 02:52:20 +0000 Subject: question about dictionary type.. References: <61Jg9.16334$5r1.665293@bin5.nnrp.aus1.giganews.com> Message-ID: thank you.. i just checked replies.. i haven't tried them.. this is what i came up with.. (making needed tables first.. as carl and padraig said) i'm having one problem(described below) d4 = {} for line in stdin.readlines(): words = split(line) if len(words) > 0 : if words[0] == 'call' : games = games + 1 elif words[0][0] == ')': table1 = {} table2= {} table3 = {} table1[dataList[3]] = 0 table2[dataList[2]] = table1 table3[dataList[0]] = table2 table3[dataList[1]] = table2 for i in [dataList[0], dataList[1]]: if not d4.has_key(i) : d4[i] = table2 else: if not d4[i].has_key(dataList[2]): d4[i][dataList[2]] = table1 else: if not d4[i][dataList[2]].has_key(dataList[3]): d4[i][dataList[2]][dataList[3]] = 0 print d4 dataList = [] else: aList = [] for i in words: i = (upper(replace(replace(i, '\'', ''), ',' ,''))) aList.append(i) dataList.append(join(aList)) input looks like this.. ------------------------------------- call games_view_insert ( 'California', 'Baylor', 'football', 'm', '31-Aug-02', 'Berkeley, Calif.', '-1', '-1' ); call games_view_insert ( 'Baylor', 'Samford', 'football', 'f', '07-Sep-02', 'Waco, Texas', '-1', '-1' ); call games_view_insert ( 'New Mexico', 'Baylor', 'football', 'm', '14-Sep-02', 'Albuquerque, N.M.', '-1', '-1' ); -------------------------------------------- this is output..in each loop ( print d4) problem is california should have had 'M' only, not 'F'emale team.. {'BAYLOR': {'FOOTBALL': {'M': 0}}, 'CALIFORNIA': {'FOOTBALL': {'M': 0}}} {'BAYLOR': {'FOOTBALL': {'M': 0, 'F': 0}}, 'CALIFORNIA': {'FOOTBALL': {'M': 0, 'F': 0}}, 'SAMFORD': {'FOOTBALL': {'F': 0}}} {'BAYLOR': {'FOOTBALL': {'M': 0, 'F': 0}}, 'CALIFORNIA': {'FOOTBALL': {'M': 0, 'F': 0}}, 'NEW MEXICO': {'FOOTBALL': {'M': 0}}, 'SAMFORD': {'FOOTBALL': {'F': 0}}} From brueckd at tbye.com Fri Sep 27 10:40:02 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Fri, 27 Sep 2002 07:40:02 -0700 (PDT) Subject: _winreg.DeleteValue - Permission denied ... In-Reply-To: Message-ID: On Fri, 27 Sep 2002, Harald Schneider wrote: > When I try to delete a registry key, I get a WindowsError (Errno5) / > Permission denied, even thought I am logged in as admin. > Deleting the same key with regedit works. > > The function looks like this: > > def del_cfg_path(self): > key = > _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,'SOFTWARE\TEST\SUBTEST) > _winreg.DeleteValue(key,"TESTVAL") > _winreg.CloseKey(key) > > Any ideas ? Hi Harald, Perhaps you need to open the registry key with write permissions, e.g.: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, \ 'SOFTWARE\\TEST\\SUBTEST', \ 0, _winreg.KEY_ALL_ACCESS) (Also note that you should use double backslashes in your strings or use raw strings) HTH, Dave From phr-n2002b at NOSPAMnightsong.com Wed Sep 4 06:32:49 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 04 Sep 2002 03:32:49 -0700 Subject: encryption (passwords) References: <3d75d115$0$221$4d4ebb8e@news.nl.uu.net> Message-ID: <7xd6ru2gfi.fsf@ruckus.brouhaha.com> "Gumuz" writes: > My limited understanding of encryption tells me that I need a 'key' to > decrypt stuff. So I figure that this key will bey written(hard-coded?) > somewhere in my Python-script and it needs to be known at both sides in > order to encrypt and decrypt. Somehow, I can't believe this is true. I can't > get over the idea that if my application becomes open-source anyone could > see the key and decrypt my messages. > > I am fairly certain that it probably doesn't work this way, but I have > really no idea. Cann someone clarify this for me? OK, first of all, that type of question is probably better asked on sci.crypt rather than the Python group. Second, a word of advice: don't try to implement encryption protocols with your present state of knowledge, and especially don't try to design protocols yourself. It's extremely easy to make mistakes that mess up security. Even experts make those mistakes, all the time. I'll sketch out answers to your questions but basically I think your best approach is to use an unencrypted protocol between your Python scripts, and tunnel it through an encrypting socket layer that someone else has already debugged. The two most popular choices of encryption layers are SSL and SSH. SSH has a "port forwarding" feature that lets you set up local ports on both machines, that communicate through an encrypted tunnel. Your Python program would just open the local port and send unencrypted data to it, and the same data would appear at the other end transparently decrypted. SSL is a fancier protocol that doesn't incorporate forwarding, but there's a program called stunnel that implements forwarding over SSL. Between the two, I'd say SSH is a easier to set up if you're just trying to secure a single socket pair between two machines. If you're trying to have a bunch of machines that talk to each other, and/or they're not all controlled by the same people (e.g. you're a vendor that needs to exchange secure traffic with various different customers), you probably want to use SSL. That type of network is called an extranet and various books have been written about how to build and manage them. If you say more specifically what you're trying to do, I or someone else here might be able to advise you more usefully. Finally, if you're building any kind of secure system that's intended to protect valuable data, I recommend you read "Security Engineering" by Ross Anderson all the way through before deploying your system. It will give you an idea of what you're up against and what kinds of measures you can take. Re your basic questions: Yes you're correct that you need a secret decryption key. The key should be unique for your specific installation, NOT part of the program that gets distributed. It's like the password that you log into your computer with. The login program is distributed freely as source code, but your password is not part of it. You install the program, THEN set your password for your specific account. Then there's the problem of how to store the key, so your program can use it. There are several approaches, each with good and bad points: 1) Include the key, in cleartext form, as part of the program configuration that gets loaded at program startup. Good points: convenient. Bad point: anyone with access to the config file (possibly gotten by breaking into your system) gets the key. This method is not recommended if the data being protected is valuable. 2) Use a passphrase as a key that you enter when you start the program, so it stays in memory and doesn't get stored on disk. Good point: better security (key not stored). Bad points: you have to enter the key every time you start the program. If you want someone else to start the program for you, you have to tell them the passphrase. If the program has to start without human attention at reboot if the system crashes, you're hosed. 3) Encapsulate the key in a special hardware device that does the cryptography. This can range from a $5 smart card or USB dongle, to a multi-kilobuck sealed module on your PCI or SCSI bus. This is the preferred method for high security applications (banking, etc.). Good points: best security of all, key can't be stolen without physical access to the machine, can implement its own access controls, etc. Bad points: special hardware required; cheaper devices are slow. From gerhard.haering at opus-gmbh.net Thu Sep 5 03:10:12 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 5 Sep 2002 07:10:12 GMT Subject: Database BSD on Mac? References: <3144be3c280c062e5e71a98ab191f664.98737@mygate.mailgate.org> <_7vd9.57894$ub2.928923@news1.tin.it> Message-ID: Max wrote: >> > I read shelve can be used for small amount of data... will it work with > 5mb? ^^^ Your newsreader is broken. > [...] I was reading on my book it's possible to create encrypted modules, > but don't explain much how. My idea is to create a exe file in C joust > to execute the python encrypted modules stored with shelve. Is it > possible? Can you point me to a tutorial/example code? Hooray. Closed source at its best. It's possible using import hooks. You can search groups.google.com for previous discussions of this. -- Gerhard From jknapka at earthlink.net Thu Sep 12 00:18:34 2002 From: jknapka at earthlink.net (Joseph A. Knapka) Date: Wed, 11 Sep 2002 22:18:34 -0600 Subject: "str.contains(part)" or alternatives? References: Message-ID: <3D80159A.C21B7002@earthlink.net> "Delaney, Timothy" wrote: > > > From: Joseph A. Knapka [mailto:jknapka at earthlink.net] > > > > So in 2.3, can I do this and get the expected result? > > > > >>> "" in "abc" > > 1 > > Yes - this has been hotly debated and defined as true. > > > >>> for subst in "abc": > > ... print subst > > ... > > > > a > > ab > > abc > > b > > bc > > c > > No. Iterating over a string is defined to return each single character in > turn. Remember: > > for subst in "abc": > > is equivalent to > > for subst in iter("abc"): I didn't know that (never saw "iter()" before). > and iter("abc") returns "a", "b", "c" > > whilst > > if subst in "abc": > > is equivalent to > > if "abc".__contains__(subst): > > (falling back to if subst in iter("abc") if "abc" does not define > __contains__) > > and str.__contains__ performs a substring match. Ah. So we have: not(X in Y <==> X in [Z for Z in Y]) But only if Y is a string. That strikes me as a trifle odd, but nevertheless I agree that the "substring in string" behavior seems more useful. -- Joe "I'd rather chew my leg off than maintain Java code, which sucks, 'cause I have a lot of Java code to maintain and the leg surgery is starting to get expensive." - Me From sholden at holdenweb.com Mon Sep 30 14:00:27 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 30 Sep 2002 14:00:27 -0400 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <3D988FCE.6040502@cascade-sys.com> Message-ID: <042e01c268ab$427dc430$6300000a@holdenweb.com> > > Steve Holden wrote: > > > wrote... > > > > > >[ ... ] > >OK, so don't use whole pennies (or smallest currency) as your > >base, use 10,000ths of a penny, but still use integer arithmetic > >for your calculations. > > > Normal Integers aren't big enough. 2^31 / 10K == 215K. > Please note that the remark you are responding to was made by the poster you quote me as quoting. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From cnetzer at mail.arc.nasa.gov Mon Sep 30 18:04:03 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Mon, 30 Sep 2002 15:04:03 -0700 Subject: Help please with menubars In-Reply-To: References: <000f01c266f3$2903dbc0$2502a8c0@emily.ewndsr01.nj.comcast.net> Message-ID: <200209302204.PAA27060@mail.arc.nasa.gov> On Sunday 29 September 2002 04:18, Will Stuyvesant wrote: > > There is no visible difference between such an ``Exit'' entry > (calling a function directly) and a normal dropdown menu entry. Do > you know how to display ``Exit'' like a Button? You could use the image option to make a button image, or change the background color to differentiate it. But otherwise, not really. You would have to manage your own menubar (by making a frame w/ buttons and menubuttons, etc. But that won't have the advantages of using the Tk Menu (ie. it'll stick out like a sore thumb on Macs, among other things). But, I'll defer to Jeff Epler , in his post, and say that probably none of this really makes sense. You could make a button that isn't in the menu bar to quit (as I do in some applications), or capture the window manager close window event to clean up when the system provided window close is clicked on, etc. And just make "Quit" a real menu item (under File, say). -- Chad Netzer cnetzer at mail.arc.nasa.gov From kseehof at neuralintegrator.com Thu Sep 12 01:34:40 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Wed, 11 Sep 2002 22:34:40 -0700 Subject: Larry Wall's comment on python... In-Reply-To: References: <3D7958DB.50903@nospam.free.fr> Message-ID: <4.3.1.0.20020911222726.00c00e90@pop.hurrah.com> At 07:46 AM 9/7/2002 Saturday, Thorsten Kampe wrote: >* laotseu > >Rod Stephenson wrote: > >> Slashdot has a list of questions posed to Larry Wall (perl). When > >> asked his thoughts on other scripting languages, he makes the > >> following observation about python > >> > >> "Python is cool to look at small bits of, but I think the "outline" > >> syntax breaks down with larger chunks of code. I'm with Aristotle on > >> the structure of discourse--a story should have a beginning, and > >> middle, and an end. So should blocks" > >> [...] > > > > def fun(args): > > #BEGIN > > if ceci or cela: > > #BEGIN > > do_this(with_that) > > [snip a lot of code] > > #END > > #END > > > > So what the problem with blocks ? > >Nope. Bad, bad readability, sorry. > >#||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*BEGINS*_! >def fun(args): > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*BEGINS*_! > if ceci or cela: > do_this(with_that) > [snip a lot of code] > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*ENDS*_! >#||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*ENDS*_! > > >Thorsten Definitely not. Too wide by far. You need to reduce the indent to one space. #||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*BEGINS*_! def fun(args): #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*BEGINS*_! if ceci or cela: do_this(with_that) [snip a lot of code] #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*ENDS*_! #||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*ENDS*_! - Ken From bac at OCF.Berkeley.EDU Tue Sep 3 20:41:35 2002 From: bac at OCF.Berkeley.EDU (Brett Cannon) Date: Tue, 3 Sep 2002 17:41:35 -0700 Subject: Python-dev summary for 2002-08-16 - 2002-09-01 Message-ID: This is a summary of traffic on the python-dev mailing list between August 16, 2002 and September 1, 2002 (exclusive). It is intended to inform the wider Python community of ongoing developments. To comment, just post to python-list at python.org or comp.lang.python in the usual way. Give your posting a meaningful subject line, and if it's about a PEP, include the PEP number (e.g. Subject: PEP 201 - Lockstep iteration) All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on a PEP if you have an opinion. This is the first summary written by Brett Cannon. Summaries are archived no where at the moment. =) They will be, though, so stay tuned for the URL in future summaries. ================ Type Categories ================ This VERY long thread was sparked by Andrew Koenig asking if a discussion of making type categories more explicit had ever occured (Andrew meant for category to mean "the set of all types that implement a particular marker interface"). As Andrew later pointed out, he was asking about "a way of making notions such as 'file-like object' more formal and/or automatic". The discussion quickly started using the term interface to mean defining a way to specify that an object implemented certain methods (think of it in terms of Java's 'implements' mechanism). Once definition was out of the way, the discussion took off. Zope's implementation was pointed out ( http://cvs.zope.org/Zope3/lib/python/Interface/ ) very quickly. PEP 245 (Python Interface Syntax) was also brought to the attention of the list. The idea of using inheritance to handle interfaces was brought up. Guido said that he hasn't "given up the hope that inheritance and interfaces could use the same mechanisms. But Jim Fulton, based on years of experience in Zope, claims they really should be different" in terms of how interfaces should be handled in objects. Jeremy Hylton tried to channel Jim's opinion by pointing out that "We'd like to use interfaces to make fairly strong claims. If a class A implements an interface I, then we should be able to use an instance of A anywhere that an I is needed." But "the inheritance mechanism is too general" because if a class A implements interface I and then a class B, which does not implement I, subclasses class A we end up with a class B that claims it has a certain interface which it doesn't actually have. Guido understood the point, but still thought inheritence could be used "if there was a way to "shut off" inheritance as far as isinstance() (or issubclass())" is concerned. Guido asked the simple question, "Why do keep arguing for inheritance? (a) the need to deny inheritance from an interface, while essential, is relatively rare IMO, and in *most* cases the inheritance rules work just fine; (b) having two separate but similar mechanisms makes the language larger." Samuele Pedroni asked that any implementation "allow also for refering to anonymous super-interfaces of an interface in terms of the interface plus a subset of its signatures, also e.g. FileLike and just 'write'. [that means an interface can be thought to correspond to a set of (tag,signature) tuples, where tag identifies the interface, and one can also just consider subsets of it]". The thread has finally seemed to have stopped (for now) with Guido saying he is mulling the whole thing in the back of his head. This is a very sticky topic because of the number of design decisions required and how it might change the way people program in Python. There was also a partial sub-thread in this whole discussion about multimethods; basically a way to do overloading of methods based on parameter signature. Most of the discussion was over syntax and such and how to handle resolution order. It then seemed to go to the wayside when the main part of the thread took over again. ============================== type categories -- an example ============================== This thread was starteed when Andrew Koenig said that the reason he brought up his type category question was because he wanted a way so as to be able to identify members of a type easily. He now had an example in a program he was writing where what the type of the argument was varied and thus what needed to be done to the data changed accordingly. Jermey Hylton suggested the isinstance(obj, type(re.compile(''))) idiom. Andrew asked if this was guaranteed to work, which Jeremy said no. I asked why this was not guaranteed, and Frederick Lundh said because re.compile() is a factory fxn and it is possible that a future version could return a different object based on the pattern. =============================================== Python build trouble with the new gcc/binutils =============================================== Andrew Koenig said that he couldn't compile Python using the newest gcc (this was the day after the latest release hit servers). With help from Zack Weinberg of Code Sourcery (who also recently rewrote the tempfile module), the problem was tracked down to binutils 2.13. being the culprit and was not Python's fault. =================================== Last call: mortal interned strings =================================== The patch http://python.org/sf/576101 removes the default immortality of interned strings. I believe it was in early August (possibly spilled over from late July) when Oren Tirosh proposed the idea and wrote the above mentioned patch. There had been some discussion over whether any 3rd party code was reliant upon interned strings being immortal; none was found (MacPython was reliant upon it, but since it is under Python core control it was considered a moot point since it could be changed). It has been checked in. With the patch the way to make a string immortal is to call PyString_InternImmortal(); no code in the core uses this function. ===================================== PEP 218 (sets); moving set.py to Lib ===================================== Thanks to Greg Wilson (for writing the PEP), Alex Martelli (for writing the module initially), Guido (for refactoring Alex's code), Raymond Hettinger (for writing the docs and playing with the code himself), and Tim Peters (for some speedup code) the stdlib has now gained a sets module. It has both the notion of mutable and immutable sets (the latter used when you have a set of sets). There was discussion about how sets should print (sorted or not; unsorted was chosen) and what operators should be overloaded for working on sets (| and & were chosen). The module is a beautiful chunk of code and I highly recommend reading its source. =========================================== A few lessons from the tempfile.py rewrite =========================================== Zack Weinberg, after rewriting the tempfile module, brought up three points: 1) Lack of dummy threads, 2) lack of a pthreads_once equivalent, and 3) lack of a way to skip tests from unittest.py via some built-in method. Guido responded accordingly: 1) since some code uses the idiom of trying to import thread and catching the exception if it fails, Guido said he would be willing to accept a dummy_thread.py that would allow: try: import thread as _thread except ImportError: import dummy_thread as _thread to work. No word on whether this is being written at the moment. 2) Guido said the method was, in his opinion, overkill. He said to "be Pythonic, live dangerously, accept the risk that a ^C can screw you. It can anyway. :-)". And as for 3) Guido deferred Zack to the PyUnit list and Steve Purcell since Python just tracks Steve's code (pyunit.sf.net). Guido's suggestion was to stick code that was reliant on some other code in a separate testing suite that is only run when the reliant code is available. =========================== Standard datetime objects? =========================== Kevin Jacobs asked what stage the new datetime object was at. Guido said it is in python/nondist/sandbox/datetime/ in CVS which also has comments pointing to a wiki containing the current work on it. Fred L. Drake, Jr. is working on the C re-implementation and has now checked it into the sandbox in CVS. =================== PEP 269 versus 283 =================== Jonathan Riehl noticed that PEP 283 said PEP 269 was dead; not good considering he was close to having a patch for PEP 269 (pgen module to interface with the C version). Guido said he will revive the PEP. The patch has since been put on SF at http://python.org/sf/599331 . ============================== What is a backport candidate? ============================== Since Python 2.2 is going to be around for a long time, the question was brought up of what constitutes code that should be backported. Guido made the following three points: 1) code trivial to backport should always be backported 2) code patching 2.3 code should obviously not be backported 3) 2.2 code requires changes to use patch, but applies; gradients of this exist. So please, when submitting patches, mention whether you think the patch should be backported to the 2.2 tree and any possible dependencies it might have in a backport. ================================= python/nondist/sandbox/spambayes ================================= In response to Paul Graham's spam filter written using Baye's Rule (Slashdot post on it is at http://developers.slashdot.org/article.pl?sid=02/08/16/1428238&tid=156 ), a thread spawned around this checkin of code that followed that paper's suggestions. This thread quickly jumped into discussions on data structures, Baye's Rule, and a whole lot of talk about spam. Very interesting if spam filtering interests you. Tim Peters has been leading the drive on this chunk of code (and thanks to his illness that befelled him in late August which he has subsequently gotten over he had a few days of major hacking on it; Tim showed he is a performance stats whore ). A very cool quote came out of this thread from Eric S. Raymond when discussing the spam filter he has been working on: "This is actually the first new program I've coded in C (rather than Python) in a good four years or so". ==================== Parsing vs. lexing. ==================== In response to a question by Aahz about what the differences were between a lexer, parser, and tokenizer, Eric Raymond posted a good overview of the differences. Guido later commented in an email mentioning SPARK and about how Python's lexer (pgen) works and why he wrote it. He also made some other comments on lexers. Jeremy Hylton pointed out a "neat new paper about an old algorithm for recursive descent parsers with backtracking and unlimited lookahead" by Bryan Ford at http://www.brynosaurus.com/pub.html . Alex Martelli pointed out that this discussion reminded him of "a long-ago interview with Borland's techies" in which they said they were able to make Borland PASCAL fit on a floppy while MS PASCAL took multiple floppies. Their trick was "we just did everything by the Dragon Book -- except that the parser is a hand-written recursive descent parser [Aho &c being adamant defenders of Yacc & the like], which buys us a lot". Someone named Noah also emailed a discussion on lexers and parsers pulling in Finite State Machines, Push Down Autonoma, and Turing Machines in his discussion. Martin Sj?n says that Haskell's pattern matching and lazy evaluation makes lexers easy (even a Recursive-Descent parser), but unfortunately Haskell does not play with other languages nicely. Haskell is where Python got it's list comprehension idea. ========================================= [Python-Dev] Fw: Security hole in rexec? ========================================= It was brought to the attention of the list that deleting __builtins__ allowed a compromise in rexec. Guido pointed out that http://python.org/sf/577530 reports this. He also said don't trust rexec. A patch was submitted and checked in to document the view that rexec is really not that safe. ================= A `cogen' module ================= Francois Pinard asked about Cartesian products using the new sets module. Guido didn't think people would in general need it. Francois quickly started this thread of discussing a cogen module to generate Cartesian products and other ways of operating on sets. The thread quickly died when Tim Peters posted "his elaborate state-of-the-art code", as Guido called it. But Francois said he would be back for more discussion on this. ================= Mersenne Twister ================= Raymond Hettinger volunteered to implement the Merseene Twister algorithm (one in Python exists at http://www.math.keio.ac.jp/~matumoto/emt.html). While discussing to implement in C or Python, Guido noticed that random.Random re-implements whrandom. Guido then came up with the idea of writing a base random class that is subclassed where .random() can be implemented; Tim Peters agreed and suggested more methods to subclass. ================================= New PEP Format: reStructuredText ================================= David Goodger and Barry Warsaw have now gotten reST as a usable syntax for PEPs. Read the PEPs on the subject to learn more: - PEP 12 -- Sample reStructuredText PEP Template (http://www.python.org/peps/pep-0012.html) - PEP 258 -- Docutils Design Specification (http://www.python.org/peps/pep-0258.html) - PEP 287 -- reStructuredText Docstring Format (http://www.python.org/peps/pep-0287.html) It has been suggested that the summaries try using reST; I am considering it. ==================================== tiny optimization in ceval mainloop ==================================== Jeremy Hylton noticed that in ceval that their is a test of whether the ticker was 0 or if things_to_do was set to true (explanation of the ticker, checkinterval, and the GIL follow this paragraph). Jeremy wondered if we could just drop the ticker to 0 when things_to_do is true. Jack Jansen, though, pointed out that clearing it is not guaranteed since there may be an interrupt routine when "we fiddle things_to_do". Skip Montanaro then pointed out that since neither ticker nor things_to_do is fiddled with unless the GIL is held that instead of causing each thread to execute this test that they could be made globals instead; he did a patch that implements this ( http://python.org/sf/602191 ). Guido then said that if there wasn't a decent speed improvement, then no patch would be checked in. He then changed his mind when it was pointed out that it actually simplified the code. Skip tested anyway, though, and there is a speed improvement. This also brought up whether the default value of 10 for checkinterval was reasonable. It was then agreed to be bumped up to 100. Jack ran some code and said he noticed a definite improvement. Python's version of threading is not like in C. There is something called the GIL (Global Interpreter Lock) which any thread wishing to execute Python code or play with Python objects must hold. This means that when you have Python threads running (using the thread or threading module) they are usually all waiting in line to get the GIL. Now for Python to decide when to release the GIL for another thread to grab it, it uses the ticker. This variable counts down to zero by being decremented every time a Python opcode is executed (originally defaulted to 10, now defaulted to 100). The ticker's starting value after each release of the GIL is what sys.checkinterval() sets. To get a better understanding of threading under Python I recommend reading Aahz's tutorials on threading. From mcfletch at rogers.com Wed Sep 25 23:18:12 2002 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 25 Sep 2002 23:18:12 -0400 Subject: Is there a way to find the name of the method currently being executed? References: <3D9278D0.9060307@arielpartners.com> Message-ID: <3D927C74.1040107@rogers.com> This is a massive hack, and I'm not sure if it covers the corner cases, but oh well :), PythonWin 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import traceback >>> class a: ... def func1( self ): ... return traceback.extract_stack(limit=1)[0][2] ... def func2( self ): ... return traceback.extract_stack(limit=1)[0][2] ... >>> a().func1() 'func1' >>> a().func2() 'func2' >>> HTH, Mike Craeg K Strong wrote: > Hello: > > class a: > > def func1(self): > print "func1 being called" > > def func2(self): > print "func2 being called" > > In the code sample above, I would like to replace the "func1" > and "func2" strings with constants so the same code could > be copied verbatim into multiple functions and do the right > thing. > > Is there a way to do this in Python? For example, maybe you could > get your hands on the call stack and print out stack[0].__name__ > or something.... > > Thanks in advance, > > --Craeg > > BTW, I could not find this in the python.org FAQ.... > > > _______________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://members.rogers.com/mcfletch/ From Hobbes2176 at yahoo.com Thu Sep 19 15:43:25 2002 From: Hobbes2176 at yahoo.com (Mark) Date: Thu, 19 Sep 2002 19:43:25 GMT Subject: Minimal debug/rep functionality References: <3d89b2e9$1@news.sentex.net> Message-ID: Peter Hansen wrote: > True... presumably either the OP is not concerned about standard > library modules anyway, or he would check the archives and add > a simple way of doing this. YAGNI... Correct, I'm currently trying to figure out how to ignore them (ie have it step "over" instead of "into" standard library calls (in particular, the linecache.getline(foo, x) call). Also, I had quite a time figuring out the damn name for what I was trying to do. My first thought was implementing a REP loop of my own. Then I started looking at the debugging code. Finally, I was put on the correct trail by looking at "tracing". > Hmmm... I didn't see any implication that speed was even remotely > a concern for the OP. After all, he did ask to *print* each line > as it executed. What could possibly be slower than that? > (I doubt he would care to deal with the volume of information > generated when using this with a large program anyway... needs > a way to turn it on and off, at least.) Yup, for now I simply need to look at traces. Speed is not important (1. this is a prototype and 2. speed may never be important). Further, I'm only looking at single function (aside from library function calls) algorithms for the moment. Thanks for the input. Regards, Mark From thisisabogusemail at bogus.thisisabogusdomain.com Tue Sep 10 12:26:50 2002 From: thisisabogusemail at bogus.thisisabogusdomain.com (Jack D. Hammer) Date: Tue, 10 Sep 2002 16:26:50 GMT Subject: Larry Wall's comment on python... References: Message-ID: <3D7E1E28.5040709@bogus.thisisabogusdomain.com> One good argument for having block delimiters is for embedded situations like ASP. One can conditionally put code into a block as such (ASP is rusty): <% if (some_condition) { %> some data some more data <% } // closing curly %> I would think that for embedding python, having block delimiters would be beneficial. brueckd at tbye.com wrote: > On 8 Sep 2002, Brian Slesinsky wrote: > > >>He's repeating the standard newbie complaint. However, I think the >>fact that so many people have repeated this for so long is >>significant. Long-term Python programmers tend to forget how weird it >>is to some newcomers to end a function or class just by *stopping*. >>It feels abrupt and rather fragile, particularly when you don't have a >>firm grasp of the language. If newbies have complained for this long, >>the complaint's not going away, and if we're serious about making >>Python easy to pick up it might be good to listen. > > > Yes, the fact that so many newbies complain about it is very significant. > Perhaps we need to do a better job of presenting the concept. For example, > instead of tossing it out there and then defending against complaints > perhaps it would be better to take the offensive: first make a case for > why the "normal" way to delimit blocks has its drawbacks, and then present > the Python way as a solution to a problem. > > But just because people consistently complain about something does not > mean the answer is to bow to their wishes. From an arrogant point of view, > they're newbies, so what do they know? ;-) Seriously though, I enjoy > Python because it _is_ different - and I usually derive benefit from the > ways in which it is different (i.e. - it's not different for arbitrary or > random reasons). It's significant that lots of newbies complain about "no > curly braces", but it's as least as significant that once people use it > for awhile they tend to end up liking it. > > >>Of course it's unnecessary and should be entirely optional. Putting >>an "end" after every block would certainly be overly verbose and bad >>style. But ending major blocks in a way that's syntax-checkable might >>catch the occasional indentation error and/or make error messages > > > Well, as you know you can always do an "# end" comment which really gives > much of the same benefit. At the bottom of my Emacs window it tells me > which block I'm closing (e.g. "Closes block: ...try:"), other editors > probably do the same. Also, it seems like whenever it's not readily > apparent which block I'm in, then the _real_ problem is sloppy code on my > part. > > -Dave > > From tdelaney at avaya.com Thu Sep 19 20:47:54 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 20 Sep 2002 10:47:54 +1000 Subject: Minimal debug/rep functionality Message-ID: > From: Peter Hansen [mailto:peter at engcorp.com] > > I'm a commercial Python user as well, so I can imagine the kinds of > things your employer think about whether to release or not. We have As I said, I *expect* to be able to release (there's no commercial reason not to, and we have done so with such things in the past). Tim Delaney From gurubert-dated-1032624215.ifbmbckh at epigenomics.com Wed Sep 25 08:19:10 2002 From: gurubert-dated-1032624215.ifbmbckh at epigenomics.com (Robert Sander) Date: Wed, 25 Sep 2002 12:19:10 +0000 (UTC) Subject: ANN: Python FAM Message-ID: Hi! I would like to announce release 1.0.1 of Python FAM. http://python-fam.sourceforge.net/ Python FAM is a port (or wrapper module) of libfam from the File Alteration Monitor project at http://oss.sgi.com/projects/fam/. The included test.py does everything test.c++ (the original example) does, so I am quite confident that it works. ;-) This is my first adventure in the large world of extending Python with C modules. Therefore feedback is very appreciated. Greetings -- Robert Sander Manager Information Systems www.epigenomics.com Kastanienallee 24 +493024345330 10435 Berlin From SBrunning at trisystems.co.uk Thu Sep 12 10:26:27 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Thu, 12 Sep 2002 15:26:27 +0100 Subject: Best tutorial Message-ID: <31575A892FF6D1118F5800600846864DCBD79B@intrepid> > From: Jordan Faris [SMTP:jfaris at sbcglobal.net] > > Of the several fine tutorials on the Web, which one would be the most > direct > in getting a novice up to snuff on Python? A novice programmer, or novice with Python? For the former, I'd recommend How to Think Like a Computer Scientist - , and for the latter, Dive into Python - . Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From tjreedy at udel.edu Mon Sep 23 09:12:32 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Sep 2002 13:12:32 GMT Subject: How to call a procedure in exe file References: Message-ID: <4rEj9.225917$z91.9596261@bin3.nnrp.aus1.giganews.com> "A" wrote in message news:mailman.1032767369.29784.python-list at python.org... > from Python but is it possible to call a procedure in an exe program? > I have a program that downloads some files( that was written in Delphi, > we bought that program compiled already in exe). > I must start the program and then push a button that runs a procedure for downloading. > And I must do it al the time when I want to download a file. So I am thinking about > downloading automatically from Python. I can start the program > with os.startfile but I do know know how to start the procedure > that is started when I push > the button for downloading.(I may possiblly find address of the procedure Lots of IFs -- in my order of preference: IF the program has a command-line option to download without a 'button push' (ie, --download ), use that. IF is doesn't, ask that such be added if you can. (Utility programs ought to have such options just so they can be used programmatically without operator present, just like you want to do.) IF you can start download with keys instead of just mouse, and if program takes keypresses through generic standard input functions (like C getchar()) rather than specific getkey function, start it at the other end of a pipe. IF program has COM interface, get PythonWin stuff and use that. IF you can find (or write or modify open-source code to make) a mouse-click simulator program thats responds to dynamic input via stdin (rather than only responding to prewritten script read as startup), use that. Terry J. Reedy From martin at v.loewis.de Sat Sep 21 06:51:05 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 21 Sep 2002 12:51:05 +0200 Subject: Solaris 64 bit compilation References: Message-ID: phoebe_1 at att.net (Holden Caulfield) writes: > This is my first attempt at compiling Python v2.2.1 in *64bit* mode > on a Solaris 5.9 system. I am using the Sun Compiler (the latest I do not > remember the version). I am migrating a few of my apps (all developed on > 64bit platforms) to Solaris, so I *need* the 64bit mode. I can't follow your conclusion - if you migrate applications which have been developed on 64-bit platforms, there is no inherent need to compile them as 64-bit binaries on Solaris 9. > But, it is failing miserably. It compiles *fine* in 32bit mode (the default), > but it does me no good. As some of the extensions library that I have are > 64bit. Before, I start hacking I thought I would give a query here and see > if anyone had any success? It compiles fine for me, with SunPRO 6U1. > > Here are my preliminary results: > - Flags used "-xarch=v9 -xcode=pic32". > The first thing I get is the bail-out in "pyport.h": > Where the #LONG_BITS != (8 * sizeof(LONG)) fails!!! Please try to report failures carefully. It does not say sizeof(LONG), instead, it says SIZEOF_LONG. Which gives rise to the question: What value does SIZEOF_LONG have, in pyconfig.h? > So, I commented it out, first to proceed and see what happens. Most of them > compiled fine except, I got some serious errors in the: > fileobject.c file probably related to the LP64 model. > > I will try to add more info, when I get around to it. More info would be required if you want help. Start with reporting the error messages as the compiler produces them, instead of interpreting them, and reporting your interpretation. Regards, Martin From rolf.kalbermatter at citeng.com Tue Sep 17 06:14:55 2002 From: rolf.kalbermatter at citeng.com (Rolf Kalbermatter) Date: Tue, 17 Sep 2002 12:14:55 +0200 Subject: More on Protecting Source Code In-Reply-To: Message-ID: > Well, I think of it this way: machine coded binaries are more > like a 128 bit > key and Python is more like a 40 bit key. I agree that nothing is > safe from > reverse engineering; it's a matter of how much pain and money it takes to > unscrut the inscrutable. Python could do better - how I'm not > totally sure. Personally I feel that getting at the idea of (parts) of a 32 bit PE executable code in the environments I usually work in is easier for me than finding out what the Python byte code in a compiled module would do ;-) That left beside I really wonder if Python should cater to people feeling their development is so valuable that everybody wants to steal it in huge masses and ignore the existing copyright laws. The incidential hacker who looks at the code and may get a good idea is probably much less dangerous in terms of profitloss than the average user posting its license key or whatever in some public forum so that everybody may be installing and using the software illegal. Obfuscating your code will maybe cause the hacker a few hours extra work but neverhtless not stop him to find out eventually what you have done. On the other hand it will not stop the average user to post his license keys in any way or just copy the pirated software, but most probably even promote it. I also believe that the very nature of Python being an Open Source project doesn't lend itself naturally to usage in a product from someone being kind of paranoic and overly concerned with obscure protection of his ideas. And I'm sure that the time spent to try to make Python more obfuscating its byte code can be spent much more productive in improving Python itself and adding new features and extensions instead. The decision in the Python developer community to not spend a lot of efforts in Python to obfuscate its code may lead to less commercial usage of Python, that is true. However I wonder if that is a problem at all as it seems to me that Python has a very active developer and user community already. Enough anyhow to guarantee that it will be around for many years to come. If this community decides that the addition of code obfuscation does not justify the possible gain in usage by commercial entities who are most happy to profit from the Python efforts but being the paranoids they are, also quite likely to not contribute back to Python in some ways, it is their full right! >> Anyway, good luck! If your software is any better than your protection >> scheme I'll download it from http://www.warez.com when you release it ;) > >I'd like it: it would means my software it's worth to crack. Which again comes down to the point: If it's worthful it will be cracked anyhow eventually, and otherwise why bother? Rolf Kalbermatter From duduca007 at yahoo.com Tue Sep 3 16:31:02 2002 From: duduca007 at yahoo.com (Carlos Moreira) Date: Tue, 3 Sep 2002 13:31:02 -0700 (PDT) Subject: Distributed Shared Memory Message-ID: <20020903203102.88032.qmail@web11401.mail.yahoo.com> I need a Python bind for some lib that supports "Distributed Shared Memory". Is there? []'s Cadu Moreira KaduSoft President -------------------------- [...yes I'm a Sith...] __________________________________________________ Do You Yahoo!? Yahoo! Finance - Get real-time stock quotes http://finance.yahoo.com From tmohr at s.netic.de Tue Sep 17 17:40:34 2002 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 17 Sep 2002 23:40:34 +0200 Subject: OpenGL Bindings for Tcl/Tk 8.4 Message-ID: Hi, i just downloaded and installed Tcl/Tk 8.4 and PyOpenGL-2.0.44. Sadly it doesn't compile, though i edited "togl.c", as mentioned in the #error directive. Also the latest CVS snapshot doesn't compile. Has anybody got some patches/hints that will help me compiling and installing OpenGL bindings for python? Best regards, Torsten. From duncan at NOSPAMrcp.co.uk Fri Sep 13 09:01:15 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 13 Sep 2002 13:01:15 +0000 (UTC) Subject: wrapping yield ? References: Message-ID: "Michael Sparks" wrote in news:alsg06$3e2$1 at nntp0.reith.bbc.co.uk: > "Duncan Booth" wrote in message > news:Xns9288759449799duncanrcpcouk at 127.0.0.1... >> The syntax wouldn't look quite so bad if your function wasn't >> returning a value. > > Problem is, it would in most situations, also I'm trying to keep the > number of generators to a minimum whilst a lower overhead than things > like threads and processes if I had several 10s of thousands going, > keeping throughput up may become an issue. (Hence the reason for > wanting the functions called part of the same generator rather than a > separate, extra one) Don't forget that iterating with a generator is *much* more efficient than calling a Python functions thousands of times. Python has a big overhead on each function call, but you only pay that overhead when you first call a generator and the subsequent iterations have virtually no overhead at all. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From gerhard.haering at gmx.de Tue Sep 17 02:46:48 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Tue, 17 Sep 2002 08:46:48 +0200 Subject: using python as cgi on apache unix In-Reply-To: References: Message-ID: <20020917064648.GB10169@lilith.ghaering.test> * josh_py at sautez.com [2002-09-16 22:48 -0700]: > All, > > I have developed a python solution to run and connect to a mysql database. > I did all my development under windows apache 1.3.26 and python 2.2.1. I > know want to move this to my unix server. Unfortunately, no matter what I > do I can not get apache on my linux box to execute any python scripts. I > get the following errors in apache: > > Premature end of script headers: /var/www/html/cgi-bin/test.py > > I have all the settings in apache I believe to be correct. It complains > that the file is not executible if that is not set. Other CGI works fine. > > test.py looks like: > > #!/usr/bin/python2 > > print "\n\n" > print "Content-Type: text/html\n\n" > print "hello" The first print "\n\n" is an error. It was simply luck that this was running anywhere else as expected. Just delete this line and your hello world cgi script should run fine. Also, to test wether Python CGI scripts work, you can always simply use: #! [path to python ...] import cgi cgi.test() -- Gerhard From a at b.c Fri Sep 27 06:54:36 2002 From: a at b.c (Tkinter stumped) Date: 27 Sep 2002 10:54:36 GMT Subject: TK canvas text bounding box question Message-ID: Perhaps I am just stupid, but I have spend significant amounts of time banging my head against this wall. Using the canvas widget text item (so I can have per pixel control of text placement), I can get the bounding box for the entire text item, but would like (and cannot seem to get) the bounding box for a charater in the text object. This seems like something that would have come up before (vis a vis Tkinter) but a search of archives gave me nothing. I did find this page: http://mini.net/tcl/1172, but if I am reading that code correctly, it seems to be doing something like canvas.index(tagOrId, x, y) => characterIndex, which won't work. What am I missing (or just plain unaware of)? Am I missing something? Or is there no way to do this short of the painful, ugly and slow brute-force workaround that presents itself: # x, y somewhere safely out of view text1 = canvas.create_text(x,y, text="foo", anchor="nw", font=f) bb_1 = canvas.bbox(text1) text2 = canvas.create_text(x,y, text="foob", anchor="nw", font=f) bb_2 = canvas.bbox(text2) now subtracting bb_1 from bb_2 gives me a bounding box for 'b' in "foobar" relative to x,y , and modulo the extra space on the end of a text item. please tell me there is a better way to do this.... From mstenner at phy.duke.edu Tue Sep 10 08:57:37 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Tue, 10 Sep 2002 08:57:37 -0400 Subject: Pickle problem In-Reply-To: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D10@hendrix.empolisuk.com>; from hst@empolis.co.uk on Tue, Sep 10, 2002 at 01:44:57PM +0100 References: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D10@hendrix.empolisuk.com> Message-ID: <20020910085737.A4329@phy.duke.edu> On Tue, Sep 10, 2002 at 01:44:57PM +0100, Harvey Thomas wrote: > Erik Price wrote: > > > > On Tuesday, September 10, 2002, at 06:13 AM, Harvey Thomas wrote: > > > > > I'm trying to pickle a complicated data structure which includes a > > > dictionary whose entries are created by (simplified): > > > > > > a[x] = re.compile(y).match > > > > > > The pickle fails, however, with the error: > > > > > > PicklingError: Can't pickle > _sre.SRE_Pattern > > > object at > > > 0x00838700>: it's not found as __main__.match > > > > Are you trying to store the MatchObject returned by a call to > > a regular > > expression object's match() method? If so, it looks like you're > > forgetting the parens at the end of "re.compile(y).match". > > > No, I haven't forgotten the parentheses. I'd like to pickle the match method of the compiled regular expression. Are you interested in storing the "match results" or the "match method"? I think Erik was suggesting that you may want a[x] = re.compile(y).match() That will pickle the match object. What you're doing is trying to pickle the method (function) that gets called to return the result. Example: class foo: def bar(): return "some data" f = foo() pickling "f.bar" is very different from pickling "f.bar()" because the former is a method, and the latter is a string (specifically, "some data"). -Michael -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From ben at remove.Stanford.EDU Tue Sep 17 18:28:15 2002 From: ben at remove.Stanford.EDU (Ben Escoto) Date: Tue, 17 Sep 2002 15:28:15 -0700 Subject: Large file support and stat vs stat64 in extension modules References: Message-ID: On Mon, 16 Sep 2002 23:05:35 -0700, Martin v. Loewis wrote: > If Python was configured for LFS, then those defines appear in > pyconfig.h. So including Python.h before any system headers is the > recommend, and better, way. Ahh, this makes the most sense. I had just mixed up the order. Thanks. -- Ben Escoto From achim.domma at syynx.de Tue Sep 24 09:16:49 2002 From: achim.domma at syynx.de (Achim Domma) Date: Tue, 24 Sep 2002 15:16:49 +0200 Subject: Python.Net ? Message-ID: Hi, a german IT magazin (iX) mentioned a .Net version of python, developed by ActiveState. My last information was, that there will be no .Net version with produces IL code, but only an extension for the new Visual Studio. Am I missing something or is the article simply wrong? regards Achim From marklists at mceahern.com Thu Sep 19 12:57:54 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 19 Sep 2002 11:57:54 -0500 Subject: strong/weak - dynamic/static [Was: Getting started] In-Reply-To: <15753.57546.804290.415645@12-248-11-90.client.attbi.com> Message-ID: [Skip Montanaro] > That doesn't make Python weakly typed. You have to be explicit about the > change. All true. I should have been more explicit about the part of what I was replying to that I thought wasn't true. It was the tail end of this: [sismex01 at hebmex.com] > A variable, being only a "reference to *any* object" > may refer to any object, but that object (see the difference?) > may not change it's functionality or type during runtime. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The fact that I can change the instance's __class__ demonstrates pretty clearly that that's not the case. Cheers, // mark - From b.maryniuk at forbis.lt Thu Sep 5 08:56:30 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 5 Sep 2002 14:56:30 +0200 Subject: How do i print to a printer using python? In-Reply-To: References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> Message-ID: <200209051456.30340.b.maryniuk@forbis.lt> On Thursday 05 September 2002 01:09, G. Willoughby wrote: > I would really like to know how to do this too, basically i want to print > to a standard bubblejet print (non postscript) from a Tkinter Text widget, > any ideas? Write canvas to PS, send to the printer via LP (UNIX). -- Regards, Bogdan The advertisement is the most truthful part of a newspaper. -- Thomas Jefferson From cbbrowne at acm.org Sun Sep 29 13:06:53 2002 From: cbbrowne at acm.org (Christopher Browne) Date: 29 Sep 2002 17:06:53 GMT Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: Quoth "Steve Holden" : > wrote... >> > > [ ... ] > OK, so don't use whole pennies (or smallest currency) as your > base, use 10,000ths of a penny, but still use integer arithmetic > for your calculations. > > Floating point has too many rounding errors to be trustworthy; > or, looking at it from another angle, floating-point calculations > cannot be 100% accurate because of the way it's implemented. The problem with FP is that FP involves the use of binary approximations, which commonly cannot exactly represent decimal values. Notably, the decimal fraction 0.1, which is /exactly/ 1/10, does not have any exact encoding in binary. Its representation in binary is a repeating binary fraction. When the (not unreasonable!) expectation is that computers ought to be able to deal /exactly/ with plain simple decimal values turns out to be wrong, that ought to lead people to think. But all too often it doesn't, as we get the typical reaction "Well, IEEE FP values can be sufficiently exact for this range of numbers; just use them right!" There's thirty years of experience now of programmers being able to use COBOL and PL/1 to manipulate decimal values without having to go into the numerical analysis effort to "just use FP right!" The "FP way" is that once in a while, you've got to insert operations to round things appropriately. The "old school" folks can legitimately gripe that they had decimal types that never required any of that nonsense, and that they had those types before many of the modern developers were even born. -- (concatenate 'string "aa454" "@freenet.carleton.ca") http://cbbrowne.com/info/linuxxian.html Rules of the Evil Overlord #195. "I will not use hostages as bait in a trap. Unless you're going to use them for negotiation or as human shields, there's no point in taking them." From andrew.thompson at ashecastle.com Tue Sep 24 05:11:23 2002 From: andrew.thompson at ashecastle.com (Andrew Thompson) Date: Tue, 24 Sep 2002 10:11:23 +0100 Subject: instance creation In-Reply-To: <265e380f.0209240052.4c2988f3@posting.google.com> Message-ID: <014801c263aa$5bf5f0f0$4802a8c0@blair> Dear Paul, One simple way to do this is to define your single __init__ method to be polymorphic, switch on the type of the first argument, and call the appropriate method to complete the initialization. ' class foo: def __init__(self, arg1 , arg2=None): if type(arg1)==type(string): self.init2(arg1,arg2) else: self.init3(arg1) def init2(name,details): blah blah def init3(id): blah blah ' -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of Paul MG Sent: 24 September 2002 09:52 To: python-list at python.org Subject: instance creation Hi I am dabbling with Python and have run into a bit of an oddness. I have a class Appointment, with fields Title and Details. I want to allow two means of construction: 1) Providing Title and Details strings explicitly, to create a new instance. 2) Providing an ID, which causes that Appointment to be loaded from a backing store. Now in C++ or smalltalk, I would do one of - Provide two constructors: def __init__(self, name, details): self.name = name self.details = details def __init__(self, id): load(id) def load(self, id): i = open("appointment"+str(id)) self = pickle.load(i) - Provide a class method (creation method) to instantiate: def create(id): i = open("appointment"+str(id)) return pickle.load(i) However, much of this seems not to work. - Having two constructors seems to be illegal - or at least the second overwrites the first. - Assigning to 'self' in the load method seems to really not work! - Putting the create() method outside of the class works fine - but I want it to be a class method on Appointment, goddammit!:) Is there no way to do this? Any help would be appreciated, basically i am looking for the python idiom to do this, as my C++ and Smalltalk idiom's clearly aren't in the grain of the language! Thanks very much Paul MG -- http://mail.python.org/mailman/listinfo/python-list From bogusdrop at myself.com Tue Sep 24 02:42:56 2002 From: bogusdrop at myself.com (TuxTrax) Date: 23 Sep 2002 23:42:56 -0700 Subject: cursor positioning and color References: <1b6dca50.0209231022.6fae7f6d@posting.google.com> Message-ID: <30770aa4.0209232242.1e91d9d5@posting.google.com> bfarwick at juno.com (brrrent) wrote in message news:<1b6dca50.0209231022.6fae7f6d at posting.google.com>... > TuxTrax at fortress.tuxnet.net (TuxTrax) wrote in message news:... > > Being new to python, I would like to know how one goes about such > > tasks as precise cursor positioning and output to screen in color. > > > > Hi Mathew, > > Curses is the way to go when using Linux/Unix. > > Wconio is the way to go when using Microsoft. > You can find in the Vaults of Parnassus. If you have any trouble > locating it, let me know, I can email it to you. Small library, works > well. > > All the best, > > brrrent Thanks Brent. Appreciate it. Am I to understand that there are no python libraries that do this as a standard part of the python distribution? That would be preferable, as it would eliminate the requirement of making the user have curses on their system before they can use the code. Cheers, Mathew From see_reply_address at something.invalid Wed Sep 18 20:02:59 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 19 Sep 2002 12:02:59 +1200 Subject: READ THE ONLY SITE THAT HAS THE GUTS TO CALL FOR THE MURDER OF JEWS AND BLACKS References: Message-ID: <3D891433.8050909@something.invalid> Hal.Turner at HalTurnerShow.com wrote: > She wants to taste > easy tyrants behind Pearl's corner. Assuming this is a typo for "Perl's corner"... if Guido is a benevolent dictator, could Larry be considered an easy tyrant? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mnations at airmail.net Thu Sep 12 17:25:31 2002 From: mnations at airmail.net (Marc) Date: 12 Sep 2002 14:25:31 -0700 Subject: Expect() from telnetlib giving me problems. Message-ID: <4378fa6f.0209121325.130766fc@posting.google.com> Hi, This is the error I'm getting: Exception in thread Thread-3: Traceback (most recent call last): File "C:\Python22\lib\threading.py", line 408, in __bootstrap self.run() File "C:\Python22\lib\threading.py", line 396, in run apply(self.__target, self.__args, self.__kwargs) File "main.py", line 85, in run command[0](*command[1:3]) File "key.py", line 94, in command read_result(conn) File "key.py", line 104, in read_result buffer = conn.expect(alist, 5) File "C:\python22\lib\telnetlib.py", line 541, in expect list[i] = re.compile(list[i]) File "C:\Python22\lib\sre.py", line 178, in compile return _compile(pattern, flags) File "C:\Python22\lib\sre.py", line 228, in _compile raise error, v # invalid expression error: nothing to repeat I've tried several different ways to get the expect command to work. I can't find any examples and only limited documentation. Here is how I'm trying to implement it: alist = [ 'COMPLD', '*/' ] buffer = conn.expect(alist, 5) Can someone please tell me what is wrong or provide me with some working examples of using the command. Thanks, Marc From thoa0025 at mail.usyd.edu.au Sun Sep 15 23:40:47 2002 From: thoa0025 at mail.usyd.edu.au (:B nerdy) Date: Mon, 16 Sep 2002 03:40:47 GMT Subject: possibly OT - delete char? Message-ID: <3pch9.10253$Ee4.26056@news-server.bigpond.net.au> im making a console app. i wish to clear the line. ive got 2 ideas - does python have a clear line method to clear the current text of line? - is there a character which deletes the previous printed character when printed? cheers From phr-n2002b at NOSPAMnightsong.com Fri Sep 20 20:33:46 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Sep 2002 17:33:46 -0700 Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> Message-ID: <7xn0qcfafp.fsf@ruckus.brouhaha.com> Christopher Browne writes: > The COBOL (or PL/I, or anyone else accustomed to BCD data types) guy > will justifiably look at the bizarro FP rounding as being, well, > bizarre. > > There's _no_ good reason for subtracting two perfectly good decimal > values from one another to result in having weird artifacts appear in > some 17th decimal place, aside from having a willingness to admit > fairly deranged arithmetic. Um, put $1000.00 in an imagined bank account and have it collect 5% annual interest, compounded daily for 25 years. How much money is in the account at the end? The "true" answer is (1+(.05/365))**(365*25) dollars, assuming 365 day years. The IEEE double precision answer will be extremely close to that amount. What happens if you do that calculation in BCD? How would you even specify how to do it? I don't think you will get nearly as much accuracy. From aleax at aleax.it Fri Sep 20 15:00:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 19:00:37 GMT Subject: Destructor never called ??? References: Message-ID: Thomas Heller wrote: ... > So what are the recommended practices if my program creates datastructures > containing cyclic references? > > - avoid using __del__ in these objects by cleaning them 'manually'? > - only using weak references to break these cycles? > > - and finally using the debugflags of the gc module to ensure everything > is cleaned correctly? These are not mutually exclusive, and they all look good to me. If you can avoid __del__, do; if you can avoid reference loops (e.g thanks to weak references) do that, too. And checking that some leak didn't happen anyway is sound. Alex From sholden at holdenweb.com Wed Sep 18 22:09:56 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 18 Sep 2002 22:09:56 -0400 Subject: How to build Python 2.2.1 on Windows? References: <3D892BBD.5B38DD49@bellatlantic.net> Message-ID: "David Lees" wrote ... > I have been playing with Python for awhile and would like to know how to > try building Python on a Windows machine that has MS C++ version 6. Is > there a standard download that is configured to do this? If not could > someone point me in the direction of information on builds? I > downloaded Python-2.2.1.tgz.tar on my Win98 box and WinZip 8 does not > even seem to know how to unzip it. I just transfered the tar file over > to a linux box and it unzips without and problem using tar. The README > seems to only talk about linux/unix type systems. > There's a whole directory concerned with building for the PC architrecture. See whether the tarball's src directory contained a PCBuild directory, and if so start with the readme.txt file. If no such directory exists then you might need to access the CVS repository for it (though I can't imagine that all PC builders do this). regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From bobx at linuxmail.org Thu Sep 12 21:19:01 2002 From: bobx at linuxmail.org (Bob X) Date: Fri, 13 Sep 2002 01:19:01 GMT Subject: [ANN] PySQLite 0.3.0 released References: Message-ID: <92bg9.2397$Lg2.449907@news2.news.adelphia.net> Gerhard H?ring wrote: > NAME: > pysqlite - Extension module for SQLite databases. > > DESCRIPTION: > A Python-DB API 2.0 compliant extension module that connects to > SQLite databases. > > SQLite is a powerful, embedded relational database in a compact C library. > It supports a large subset of SQL92, multiple tables and indices, > transactions, and triggers. It has a simple C/C++ interface requiring only > three functions to perform queries. It has TCL bindings and an ODBC > driver. Sources are uncopyrighted and can be used for any purpose. More > information can be found at . > > USAGE: > import sqlite > > conn = sqlite.connect("db") > cursor = conn.cursor() > SQL = """ select category, family, genus, species > from calflora order by genus, species limit 10""" > > cursor.execute(SQL) > > for col in cursor.description: > print "\t %12s - %3s bytes" % (col[0], repr(col[3])) > > row = cursor.fetchone() > > while row != None: > print "%14s, %15s, %19s, %8s, %25s" % tuple(row) > row = cursor.fetchone() > > SQL = "insert into calflora (family,genus,species) values(%s,%s,%s)" > cursor.execute(SQL, ('greenus', 'weedus', 'maximus')) > > conn.close() > > HOMEPAGE: > > > DOWNLOAD: > Source and Windows binary downloads are available at > > > AUTHORS: > Gerhard H?ring > Michael Owens > William Trenker > > LICENSE: > Python > > NOTES: > PySQLite has been tested on FreeBSD, Linux, and Windows with both Python 2.1 > and 2.2. The latest versions of SQLite (v. 2.6 and greater) are recommended. > > Version 0.3.0 fixed a lot of bugs, while also adding new features. Users of > PySQLite are recommended to upgrade. > > The following are some of the changes and enhancements since the last > release: > > - Squashed a few memory leaks. > > - Exposed the sqlite_exec, sqlite_last_insert_rowid and > sqlite_changes functions of SQLite to Python as methods of the > connection object. > > - Add support for Date types, if mxDateTime is > available. > > - Support for optional DB-API extensions from PEP 0249 > > - Added files for creating a PySQLite Debian package. > > - setup.py: - Added Cygwin as platform that's supported by default > > - Added third example: program to dump a table in XML format. > > - Use bool type and custom bool converter for boolean fields. > > - Set cursor.rowcount appropriately after DML (insert/update/delete) > statements. > > - Fixed a bug with the SQL-quoting of longs. > > - Inline documentation improvement. > > - Change invocation of ReferenceError to work with Python 2.1 > > - (really) implemented weak references from cursors to connections > > - Added new test suite. > > - Adapted test for threadsafety attribute. > > - Added checks with user-defined float and string functions. > > - Removed Connection.begin(). Transactions are now started > implicitely. - Use DB-API quoting instead of manual Python > quoting. - Use string methods instead of the string module. > > - Added checks for functions/aggreagates that raise exceptions or > return None (NULL). > > - Added tests for proper commit/rollback behaviour. Added tests > for autocommit feature. > > - Implemented autocommit feature. Renamed the parameter of > Connection.__init__ from "filename" to "db". Commit and rollback > now check if the connection is open at all. Started adapting the > weak reference code from pyPgSQL to loosely couple cursors and > connections. This is needed when you want to check if there are > any open cursors for a given connection, for example. > > - Simplified version numbers, removed the check for equal version > numbers in _sqlite and sqlite. This looked like overhead to > me. The version number scheme is now only: major.minor.micro Set > threadsafety to level 1. I believe we can guarantee than sharing > the module among threads will do no harm. Sharing the connection > would. Windows binary? From simonb at webone.com.au Sun Sep 1 20:18:01 2002 From: simonb at webone.com.au (Simon Burton) Date: Mon, 02 Sep 2002 10:18:01 +1000 Subject: yield keyword reserved References: Message-ID: you forgot this: >>> from __future__ import generators On Mon, 02 Sep 2002 01:57:06 +1000, Erik Price wrote: > I'm sorry if this is an easily answered-question. I have Python2.2 > running on my system (it is installed on Darwin by default in Mac OS X > 10.2), and am learning about iterators from > , but the keyword > doesn't appear to be present on my system: > > Python 2.2 (#1, 07/14/02, 23:25:09) > [GCC Apple cpp-precomp 6.14] on darwin Type "help", "copyright", > "credits" or "license" for more information. > >>> def generate_ints(N): > ... for i in range(N): > ... yield i > :3: Warning: 'yield' will become a reserved keyword in the > future > File "", line 3 > yield i > ^ > SyntaxError: invalid syntax > >>> > >>> > >>> > Is my Python not a true 2.2 release, or do I have something wrong in my > syntax? > For that matter a recompile wouldn't be so bad since this build doesn't > have readline :( > > > Erik > > > > > > > -- > Erik Price > > email: erikprice at mac.com > jabber: erikprice at jabber.org From sholden at holdenweb.com Tue Sep 10 18:27:55 2002 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 10 Sep 2002 18:27:55 -0400 Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> <6afb9d2c.0209091641.1d9b652e@posting.google.com> Message-ID: "Uwe Schmitt" wrote in message news:allofr$lgscc$2 at hades.rz.uni-sb.de... > Naveed Iqbal wrote: > > Thank you all for your help. I am really a novice when it comes to > > python. Will someone tell me how to install the win32ui module in > > windows? > > thanka > > naveed > > I suceeded without win32all: I generated a postscript file > and copied it to the 'file' "prn:" using shutil.copyfile(). > Disk Operating System Rules OK! As a pythonista of somewhat longer standing I found PythonWin a delight. I don't overstress it, and it works. Naveed: while you are likely to stay more up-to-date by installing an updated base Python and installing updated Win32 extensions, there's no real reason for a "novice" to need (or even want :-) to be so close to the (b)leading edge. I haven't heard anything to suggest the ActiveState distribution isn't a perfectly practical solution to everyday needs. Uwe: you'll clearly do well with such lateral thinking abilities. What software did you use to generate the PS? nostalgical-ly y'rs - ste ve ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From oliver.eichler at dspsolutions.de Tue Sep 10 08:22:14 2002 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Tue, 10 Sep 2002 14:22:14 +0200 Subject: Howto debug self? References: Message-ID: > print self.__dict__ Yes, this would work. However if self has some classes you have to iterate over the dictionaries. I tried to make my own abstraction from bdb to play with the eval() command, to display the complete tree. But I ran into recursion problems (enless loops). Somehow it is hard to imagin this has not been implemented sofar, as I would consider it as a very basic debugging function. Are there better frontends to bdb than pdb? Oliver From syver-en+usenet at online.no Thu Sep 12 16:19:48 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Thu, 12 Sep 2002 20:19:48 GMT Subject: web crawler help? References: Message-ID: s_gherman at yahoo.com (Sorin Gherman) writes: > "koko" wrote in message > news:... > > > is there any sample for basic web crawler, that ask for a starting > url and > > > log the url and extract the hyperlinks? > > thx > > It's a very simple one in Mark Pilgrim's "Dive into Python" book, > whose text is freely available at: http://diveintopython.org/ > Check the "HTML processing" chapter. It contains a urllister.py 9 > lines program, followed by a 7 lines usage example which does just > that: given a URL for a HTML file, it lists the hyperlinks inside it. > > /sorin gherman You could also check out Aahz's slides about multithreading, they show the development of different threading architectures for a spider. http://starship.python.net/crew/aahz/OSCON2001/index.html -- Vennlig hilsen Syver Enstad From b.maryniuk at forbis.lt Wed Sep 11 10:37:51 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Wed, 11 Sep 2002 16:37:51 +0200 Subject: UNIX processes In-Reply-To: References: Message-ID: <200209111637.51785.b.maryniuk@forbis.lt> On Tuesday 10 September 2002 13:52, Erno Kuusela wrote: > use the ps program (ps -e works on linux). there is no other > standard api for it. I already made native Python module for this, because I don't like 'ps' in this case. Well, module works even faster. ;-) -- Regards, Bogdan I doubt, therefore I might be. From tjreedy at udel.edu Mon Sep 9 21:39:40 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 10 Sep 2002 01:39:40 GMT Subject: Python primer - comments appreciated! References: Message-ID: "Thorsten Kampe" wrote in message news:aljdhe$1q63hj$1 at ID-77524.news.dfncis.de... > "Python, anyone?"... Yep, this is my first one. Comments on > style/readability and technique/flow appreciated! > > #v+ > def quotient_set(seq, func, partition='nonbool'): > """ partition into equivalence classes To my mind, you should return a dictionary mapping each realized value of func (assuming hashable) to the list of items for which func has that value. In other words, result.values() would be the list of equivalence classes. Let caller toss away info of value defining class. In any case, using a dict to sort items into such classes should be much faster that what you wrote. def equiv_class(seq, func, part = 'nonbool'): if part == 'bool': result = {False:[], True:[]} for item in seq: result[bool(func(item))].append(item) else: result = {} for item in seq: result.setdefault(func(item),[]).append(item) # {}.setdefault(key,default) was added for just this sort of usage return result >>> f = lambda x: x % 3 >>> equiv_class([0,1,2,3,4,5,6,7,8,9],f) {0: [0, 3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]} >>> equiv_class([0,1,2,3,4,5,6,7,8,9],f,part='bool') {0: [0, 3, 6, 9], 1: [1, 2, 4, 5, 7, 8]} > def set(seq): > """ make a true set by removing duplicates """ > # Shortest way to do a 'null function'? 'None' doesn't work... > f = lambda x: x # identity function > > return [item[0] for item in quotient_set(seq, f)] No, no. If items are hashable, standard method is... def set(seq): d = {} for item in seq: d[item] = 0 return d.keys() Terry J. Reedy From phncontact.libero.it at Thu Sep 5 11:16:48 2002 From: phncontact.libero.it at (s1kboy) Date: Thu, 05 Sep 2002 15:16:48 GMT Subject: Servizi Internet References: Message-ID: ma ciao ^_^ On Thu, 05 Sep 2002 07:59:26 GMT, Paolo Invernizzi wrote: >Benjamin wrote: >> by the way, how many people understand italian in >> this nesgroup? ^_^ > >** a little hand is raised! ** From tadin at cirus.dhz.hr Thu Sep 26 04:04:34 2002 From: tadin at cirus.dhz.hr (Marijan Tadin) Date: Thu, 26 Sep 2002 10:04:34 +0200 Subject: Scientific Python for Win32 References: <3D92082C.3050707@rmc.ca> Message-ID: 1. I am far away from expert but I've tried out netCDF module from Scientific Python , you can download necessery dll-s from http://basic.astrian.net/godzilla/ . Unfortunately, I am afraid that the modules from Scientific Python that you need are not there, but you schould check. 2. actualy you need *.dll and not *.exe files if you want to use compiled binaries in Python on windows. (or maybe I just didn't understand your message wright). 3. you can find more about extending Python on http://www.swig.org/, (check swig manual). I think it is more understadable for easy start then information on python.org, unfortunately only info about use of VC++ and not Borland for Windows (even that info was difficult to find on net). 4. I feel that extending python is not so easy (if you are not experienced C-programmer, like I am not), the main problem is not Python but knowlege of C and details of particular compiler even more. If you know how to use dll-s from Python (try some simple example from swig manual), then try to find dll-s you need on Internet. "bourassa" wrote in message news:3D92082C.3050707 at rmc.ca... > Hi there. I'm a Python and programming newbie. I was looking for at > Scientific Python esp. for its use of VRML for plotting output. Unlike > many of the other Python modules I have, there are no .exe binaries. > So, I have Borland C++Builder 5 on a Win2K P4. How would I compile(?) > my own Scientific Python? Would it work with my Python 2.2 which I just > installed from a .exe file? Any help would be appreciated. Thanks. > > Mike > > PS - I spoke with the creator of Scientific Python. He was very helpful > but admits to not having expertise in this aspect, hence my question. > From doru-cat at ifi.uio.no Sat Sep 7 08:57:21 2002 From: doru-cat at ifi.uio.no (Doru-Catalin Togea) Date: Sat, 7 Sep 2002 14:57:21 +0200 (MET DST) Subject: Python, CGI, MySQL -> 'Error 2004: Can't create TCP/IP socket (10106)' Message-ID: Hi! I am using Python 2.2 on a win 2000 Pro computer to interact with mysql, by means of the MySQLdb module. My non-CGI scripts work as expected. I have now installed a webserver (Savant 3.1) am I try to connect to mysql by means of CGI and still MySQLdb. My scripts fail now with the 'Error 2004: Can't create TCP/IP socket (10106)' error message. Can anyone tell me what these errors are caused by, and who is it that generates the error messages? They do not seem to originate from the MySQL server as it's error checking utility (perror) does not recognize any of the 2004 or 10106 error codes. Neither did I find any mention of them in the documentation comming with PythonWin. This leaves me with the theory that they originate with the web server. Anyone who can recommand a free webserver which interacts well with MySQL by means of pythonic CGI scripts on Win 2000 Pro? What I am trying to do is first to establish a connection to mysql-server and then to have it execute a sql statement using that connection. I have a module called MyDatabase.py. It defines the following functions. # ******************************************************************** def openDBConnection(h, u, p, d): # host, user, password, database try: conn = MySQLdb.connect(host = h, user = u, passwd = p, db = d) except MySQLdb.Error, e: result = pname + "Error %d: %s" % (e.args[0], e.args[1]) #sys.exit(1) return result return conn # ******************************************************************** # executes an SQL statement using the given connection def execSQL(connection, sqlCommand): cursor = connection.cursor() cursor.execute(sqlCommand) rows = cursor.fetchall() cursor.close() return rows These functions work when the script connects to the mysql-server directly, but fail when a webserver is in between. I call my functions as follows: import MyDatabase ... conn = MyDatabase.openDBConnection(host, user, password, database) sqlCommand = "..." rows = MyDatabase.execSQL(conn, sqlCommand) ... Thanks if you can help. Best regards, Catalin <<<< ================================== >>>> << We are what we repeatedly do. >> << Excellence, therefore, is not an act >> << but a habit. >> <<<< ================================== >>>> From loewis at informatik.hu-berlin.de Thu Sep 26 07:04:44 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 26 Sep 2002 13:04:44 +0200 Subject: unicode woes References: <3d92d120$0$76313$e4fe514c@dreader4.news.xs4all.nl> Message-ID: Ulli Stein writes: > Or how would you do this (nonsense string): > str = str + "bla??" + str[:5] + "???" > > Would you write then: > str = str + unicode("bla??") + str[:5] + unicode("???")? If you want to use Unicode in source code, and you want to use non-English text: yes, you have to define a helper function, e.g. def uni(x): return unicode(x, "iso-8859-1") In this case, the system encoding might be incorrect; Python cannot know what encoding you use in your source code: If you move your source code from one machine to another, the system encoding may change, but your source code won't. If you want to write internationalized code, I recommend to avoid using non-English string literals. Instead, use English text, and translate this at run-time using message catalogs (e.g. gettext). > And what about the "encode" variable in site.py: If another Python > application running in parallel to our application changes the encode > string, will it affect our app? Or has every application its own encode > string? If you keep your sitecustomize.py in a location that is private to your application, there is a good chance that it won't interfere with another application. Regards, Martin From david at fielden.com.au Tue Sep 24 20:30:34 2002 From: david at fielden.com.au (DG) Date: Wed, 25 Sep 2002 10:30:34 +1000 Subject: Strange python and cgi! In-Reply-To: <3D9101AC.842F0513@alcyone.com> Message-ID: <001a01c2642a$c3efec80$3101a8c0@borg.fielden.com.au> And/or put this at the start of your script: import cgitb; cgitb.enable() Rowdy > -----Original Message----- > On Behalf Of Erik Max Francis > Sent: Wednesday, 25 September 2002 10:22 AM > Subject: Re: Strange python and cgi! > > > CheapSkate wrote: > > > when I go to the webpage, it stops halfway and in "view source: it > > only show > > the code till the open "pre". > > It's likely some other error occurred. Check your Web server > error log > for the final word. From brian at sweetapp.com Wed Sep 4 17:49:53 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 04 Sep 2002 14:49:53 -0700 Subject: str() of a tuple In-Reply-To: Message-ID: <000901c2545d$0085b6d0$df7e4e18@brianspiv1700> > Why, oh why does the str() of a container use the repr()s of the > objects inside? This seems to violate what the docs claim str() does > -- "return a nicely printable representation of an object." Would a > sane implementation break something? (Before I tell you, could you please tell me what this tuple contains? I bet that you can't figure it on in less than, say, 5, days) Cheers, Brian From martin.klaffenboeck at gmx.at Fri Sep 6 16:45:08 2002 From: martin.klaffenboeck at gmx.at (Martin Klaffenboeck) Date: 06 Sep 2002 22:45:08 +0200 Subject: Beginners Question - use of variables Message-ID: <1031345108.547.165.camel@martin.kleinerdrache.org> Hello, Are newbies questions ok here? I've got a struktur like this: string string int timestamp string string int timestamp string string int timestamp ... in Perl I used to save such a thing in a multidimensional array like array( array(string, string, int, timestamp), array(string, string, int, timestamp), array(string, string, int, timestamp)) So how do I save that in python and how do I get fast to one of this strings or int or timestamp... ? Martin -- Virtuelle Jugendarbeit auf http://create.kleinerdrache.org ... bald kommt ein neues Layout ... From thorsten at thorstenkampe.de Tue Sep 10 07:55:47 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 10 Sep 2002 13:55:47 +0200 Subject: Python primer - comments appreciated! References: Message-ID: * James J. Besemer > Thorsten Kampe wrote: > >> "Python, anyone?"... Yep, this is my first one. Comments on >> style/readability and technique/flow appreciated! > [...] >> # put this in one line? >> true_class = [] >> false_class = [] > [...] > #### if you are thinking "true_class = false_class = []" > #### then it would be a BIG NO-NO. > #### the latter form initializes both variables to the SAME > (empty) list Well, uh, ah, eh, errm, good to know, thanks! >> quotient_set.append([item]) > > #### teeny tiny nit: I prefer "quotient_set.extend( item )" to the above. That's not the same: I'm appending a new equivalence list to the quotient set by making item a list and your version would append a list as individual items. >> # This somehow "inelegant", because all I want to do is: >> # "seq[index] = seq[index].append(item)" Suggestions? >> > #### Define your set or sequence types to be a class or classes. > #### You can then define [] and .append() operations > #### to be whatever you want (e.g., silently exclude duplicates, etc.) > > #### Even the most trivial data abstractions usually benefit by being > made an > #### explicit class/object. Well I RTFM'd and 'tutorialed' a lot, but I cannot find any concrete use for this OOP thing. Could you elaborate?! > #### if you are 'indexing' you may want to use a dictionary base type > instead of a list. I think I'm not "indexing" but "hashing" over the representants, so a dictionary (associative array) should be the natural thing, thanks. > #### if you only want to test membership, instead of the 'try' you can > test: > > if representative in representative_class: .... Well, even "if item in seq: seq.index(item)" is faster than "try: seq.index(item)" Thorsten From mark.charsley at REMOVE_THIS.radioscape.com Mon Sep 23 11:22:00 2002 From: mark.charsley at REMOVE_THIS.radioscape.com (Mark Charsley) Date: Mon, 23 Sep 2002 16:22 +0100 (BST) Subject: What the heck? open() requires an integer? References: Message-ID: In article , mgarcia at cole-switches.com (Manuel M. Garcia) wrote: > O'Reilly publishes two excellent books for people who wish to learn > Python and write applications quickly: Programming Python, 2nd > Edition, and Python Cookbook. Programming Python 2nd ed is _not_ much good for a complete beginner at Python - I speak from experience (and I'm not new to programming). The gentle intro from the 1st edition (which was good for beginners from the reviews I've read) has been taken out, and expanded into Learning Python also by O'Reilly. Once one has read Learning Python, then Programming Python 2nd ed makes a lot more sense. -- Mark - personal opinion only, could well be wrong, not representing company, don't sue us etc. etc. From pyth at devel.trillke.net Sun Sep 1 19:00:50 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 2 Sep 2002 01:00:50 +0200 Subject: Add methods to a class at runtime? In-Reply-To: ; from cliechti@gmx.net on Sun, Sep 01, 2002 at 11:47:01PM +0200 References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: <20020902010050.G3893@prim.han.de> Chris Liechti wrote: > "Robert Oschler" wrote in > news:wmvc9.21757$FJ1.3181934 at e3500-atl1.usenetserver.com: > > Some interesting tidbits I > > found while trying out your suggestions, as you will see in the two > > ".py" files that follow, I discovered that to create a method you can > > dynamically add to a class _instance_, you need to omit the 'self' > > parameter in the method declaration. For a method you add dynamically > > to a class definition itself, then you must include the 'self' > > parameter in the method declaration. If not, you will get an argument > > count mismatch complaint from the interpreter. Fascinating stuff. > > that's just the differece between a "function" and a "method". a method > works on an object and that is passed explicit as first argument. "explicit > is better than implicit" (you can read this and some other design ideas by > typing ">>> import this" ;-) > > > I'm running 2.1.1, anybody know if 2.2.2 is going "disable" either of > > these abilities? (class or class instance dynamic method addition). I > > saw a note about such activities requiring a "dynamic" keyword, which > > is fine. I'd really miss either of these abilities. > > nah. "classic classes" stay the way they are and are available until 3.0 > new style classes, those that inherit from "object" or "type", will need > the marking as "dynamic". Can you give a pointer for further explanation? Can't believe it :-) thanks, holger From maxm at mxm.dk Tue Sep 3 03:39:25 2002 From: maxm at mxm.dk (Max M) Date: Tue, 03 Sep 2002 09:39:25 +0200 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <1031008206.347446@ampungk.ozonline.com.au> Message-ID: <3D74672D.8050600@mxm.dk> John La Rooy wrote: > Bengt Richter wrote: >> > It is unfortunate that often a re that starts off as a simple idea > turns out to be a big mess. I think some sort of graphical tool > would be even better so you could see what the re does. Especially > if it could convert both ways and allow you to edit the re. There used to be a tkinter tool like this in Python under 1.52 written by Guido. I don't know what happened to it though. regards Max m From tim.one at comcast.net Thu Sep 19 14:20:22 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 19 Sep 2002 14:20:22 -0400 Subject: monetary applications [was: Python GUI app to impress the bos s?] In-Reply-To: <23891c90.0209190014.26c5bb9@posting.google.com> Message-ID: About http://starship.python.net/crew/aahz/FixedPoint.py If someone is willing and able to do the work (sorry, I can't make time for it), Guido will accept this into the standard library for 2.3. It's a small, self-contained, pure Python module; it's been in use for a few years with no bugs reported; and is unencumbered by any license (a lawyer has told me that an individual in the USA cannot meaningfully disclaim copyright, so fine, the copyright I didn't want is hereby transferred to the PSF ). What work remains: + Write docs for the Library Reference manual. I expect the existing module docstring will be a good start. + Create a test driver for Python's regression suite. + Have fun modernizing it, if you like (for example, "/" should be changed to "//" where integer division is intended; playing with __slots__ may yield some nice savings; whatever). This should be a fun and comparatively easy task -- if you ever wanted to get your name into the ACKS file, here's one way to do it without tithing you income directly to Guido . although-tithing-saves-me-time-ly y'rs - tim From sholden at holdenweb.com Wed Sep 11 16:42:17 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 11 Sep 2002 16:42:17 -0400 Subject: "str.contains(part)" or alternatives? References: Message-ID: "Stefan Schwarzer" wrote in message news:alo8jr$l04$1 at news.online.de... > Hello all > > I would like to get your thoughts on testing if a string contains another. > > To do something dependent on whether a part is contained in another string, the > following code is familiar to me: > > >>> s = 'Hello' > >>> if s.find('ll') != -1: > ... do_something_if_found() > ... else: > ... do_something_if_not_found() > > However, I dislike the test for the special value -1; that reminds me of error > code checking. On the other hand, using exceptions could look like > > >>> try: > ... s.index('ll') > ... do_something_if_found() > ... except ValueError: > ... do_something_if_not_found() > > This has the problem that a ValueError raised in do_something_if_found() may give > the false impression that the substring isn't contained in the string s. Moreover, > that code doesn't represent my thoughts very well. (Maybe I could say that better > if I were a native English speaker :) ). > > I would like something analogous to .startswith and .endswith: > > >>> s = 'Hello' > >>> if s.contains('ll'): > ... do_something_if_found() > ... else: > ... do_something_if_not_found() > > Do you have other suggestions how to do the test easily without using special > values? Should a .contains method be part of string objects in future Python > versions? What do you think? > I think the current proposal is to move to if ll in s: for this construct. Happy? regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From theller at python.net Fri Sep 27 16:06:41 2002 From: theller at python.net (Thomas Heller) Date: Fri, 27 Sep 2002 22:06:41 +0200 Subject: watching mutables? References: Message-ID: "Michael Stenner" wrote in message news:mailman.1033154856.20758.python-list at python.org... > On Fri, Sep 27, 2002 at 08:48:10PM +0200, Chris Liechti wrote: > > Thomas Heller wrote in > > news:k7l7qpvf.fsf at ion-tof.com: > > > Chris Liechti writes: > > [triggered by *any* change of object m] > > >> see EventObj: > > >> http://oomadness.tuxfamily.org/p-pyobjtools.php > > >> > > > This is what I get when clicking on the download link: > > > 404 Not Found > > > > works for me. > > I find that rather surprising since that file isn't there. Are you > sure you clicked on the download link? For your convenience, I > provide that link here: > > http://oomadness.tuxfamily.org/downloads/EventObj-0.2.tar.gz > > I am also interested in this module (curiosity, mostly) and would > appreciate a working link if you have one. > Here's what seems to be available: http://oomadness.tuxfamily.org/downloads/ and this is obviously where the EventObject is contained in: http://oomadness.tuxfamily.org/downloads/EditObj-0.3.tar.gz Thomas From dsavitsk at e-coli.net Wed Sep 11 21:18:21 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 12 Sep 2002 01:18:21 GMT Subject: ntpath bug or expected? Message-ID: python 2.1.3. this is pretty minor ... os.path.join() on win32 fails if the first path component is C: (or any other letter). that is, if the first component is a drive letter, it must contain either '\\' or '/' or else the path is wrong. this makes it the only component which must have slashes. example >>> os.path.join('C:', 'path', 'to', 'file.txt') C:path\\to\\file.txt the offending code is below and can be easily fixed by removing the ':' from '/\\:' def join(a, *p): """Join two or more pathname components, inserting "\\" as needed""" path = a for b in p: if isabs(b): path = b elif path == '' or path[-1:] in '/\\:': path = path + b else: path = path + "\\" + b return path From doyle at nebcorp.com Mon Sep 30 19:13:05 2002 From: doyle at nebcorp.com (Rev. Joe Doyle) Date: Mon, 30 Sep 2002 23:13:05 -0000 Subject: Stow and Python Message-ID: Hello, I'm trying to build a Python package for a large installation, where packages are of the following form: 1) /usr/local is a symlink to /tools/foo 2) packages live in /tools/bar/package-name 3) within each package, there are "bin", "lib", etc. that get linked into /usr/local/ (using GNU stow). My problem is that the Python interpreter looks in the absolute real path for modules, rather than the symlinked "proper" path ("/usr/local/lib" etc.). How do I get it to look in the right place? Thanks in advance for any hints. -Joe Doyle From mnations at airmail.net Mon Sep 2 12:24:13 2002 From: mnations at airmail.net (Marc) Date: 2 Sep 2002 09:24:13 -0700 Subject: Problems with file.write() References: <4378fa6f.0208291457.ba738cb@posting.google.com> <4378fa6f.0208300731.18105bc7@posting.google.com> Message-ID: <4378fa6f.0209020824.3e658da8@posting.google.com> > Note that all buffered data is flushed automatically when you close() > an output file (you *are* closing the file, aren't you?). Actually I wasn't closing the file originally but it had never been a problem before. But closing the file now causes it to spill it's guts and gives me everything I was looking for. However, that doesn't explain why it wasn't working in the first place. I originally had it in unbuffered mode and wasn't getting all my text. As I increased the buffering from 1 to 2 I kept getting more text. But never all of it until I closed the file. It seems like it shouldn't be necessary to flush the buffer after every write if you're in unbuffered mode. This seems like a problem. From wlfraed at ix.netcom.com Mon Sep 30 01:54:00 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 29 Sep 2002 22:54:00 -0700 Subject: Catching user defined exceptions from foreign modules References: Message-ID: Derek Basch fed this fish to the penguins on Sunday 29 September 2002 07:22 pm: > I know that TestError has been imported because I can > put a "print TestError" before the except clause in > test1 and I get "test2.TestError". Can anyone tell me > why I am having to put the test2.TestError instead of > just TestError? It confuses me even further that my > small test modules work like I would expect and it > doesn't work on the larger modules. > I don't even see why "test1" is working. You explicitly import the exception by name, but you didn't bring in "TryItOut"... That alone should have raised an exception. [wulfraed at beastie wulfraed]$ python test1.py Traceback (most recent call last): File "test1.py", line 14, in ? letitrip.run() File "test1.py", line 7, in run tryitout = TryItOut() NameError: global name 'TryItOut' is not defined -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From loewis at informatik.hu-berlin.de Mon Sep 2 09:37:49 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 02 Sep 2002 15:37:49 +0200 Subject: version independant object usage counting References: Message-ID: "Rolf Kalbermatter" writes: > However although this loader works quite fine now, I found out that > I gained little with it because the current Python architecture is > not really designed to link dynamically to it. Yes, this is the case - mainly because the API changes in slight ways, and because therefore, extension modules explicitly link to pythonxy.dll. > The problem arises in fact with the refcounting of Python > objects. The macros Py_INCREF and Py_DECREF access directly > structure members in the object layout and this layout is different > for debugging and non debugging versions and potentially different > between Python versions as well. That is only a minor problem: those macros are correct across all released Python versions, back to 1.4 or earlier. > Is there a specific reason that these two API functions are not > available and one is forced to use the according macros to do proper > refcounting, or did I miss those functions completely? Nobody has proposed to introduce them, because there is no need to do so, and because other ABI changes break the ABI more often - INCREF and DECREF have never done so, and it is unlikely that they ever will. > Any thought about this? Feel free to submit a patch to SourceForge. However, you might want to consider the following issues: - various places assume presence of the ob_type field: * the Py*_Check functions (e.g. PyList_Check) directly access the ob_type field. * PyObject_INIT relies on initializing the object members. - PyType_HasFeature relies on the position of the tp_flags field - various accessor macros rely on the internal structure, e.g. * PyTuple_GET_ITEM * PyString_AS_STRING * ... Regards, Martin From stepanov at oitunix.oit.umass.edu Tue Sep 3 17:51:47 2002 From: stepanov at oitunix.oit.umass.edu (Alexander Stepanov) Date: Tue, 3 Sep 2002 17:51:47 -0400 Subject: Drawing graphs/newtorks with Python Message-ID: Hi Pythonians, I work on program which performs some calculations over graphs. (shortest paths). I would like to draw an image/ps_document with Python. Does anybody use some kind of modules to draw graphs? I will appreciate if you can point me out to the source. Thank you, Alexander Stepanov astepano at ecs.umass.edu From anthony at computronix.com Thu Sep 19 10:25:03 2002 From: anthony at computronix.com (Anthony Tuininga) Date: 19 Sep 2002 08:25:03 -0600 Subject: surface of pygame In-Reply-To: <20020919101158.58549.qmail@web21305.mail.yahoo.com> References: <20020919101158.58549.qmail@web21305.mail.yahoo.com> Message-ID: <1032445504.17506.58.camel@chl0151.edmonton.computronix.com> Look at the documentation for pygame at www.pygame.org, specifically the introduction regarding programming in pygame. Specifically, you have to blit the image on to the screen before you will see it. On Thu, 2002-09-19 at 04:11, black wrote: > Hi,all~ > > I touched something about pygame today and confused with surface type. I > didnt remember surface data type when learning python, and it displays > strange to me, for example, I create a new surface by loading a picture > as follows: > > pygame.image.load("myPic.bmp") > > it works fine but I coulnt see any surface appears on the screen. > any ideas ? > > > > > > > _____ > > Do you Yahoo!? > New DSL Internet Access > from SBC & Yahoo! -- Anthony Tuininga anthony at computronix.com Computronix Distinctive Software. Real People. Suite 200, 10216 - 124 Street NW Edmonton, AB, Canada T5N 4A3 Phone: (780) 454-3700 Fax: (780) 454-3838 http://www.computronix.com From export at hope.cz Fri Sep 20 16:08:15 2002 From: export at hope.cz (A) Date: Fri, 20 Sep 2002 22:08:15 +0200 Subject: How to upload a file using http protocol Message-ID: <3D8B9C4F.14553.1E62DBD@localhost> Hi, Does anyone know how to upload a file through HTTP protocol?Is that a possible? Thank you for help. ladislav From fabien.henon at caramail.com Tue Sep 10 17:58:38 2002 From: fabien.henon at caramail.com (Fabien HENON) Date: Tue, 10 Sep 2002 23:58:38 +0200 Subject: Maybe a dumb question Message-ID: <3D7E6B0E.4060709@caramail.com> I have written an editor for Povray using Python, Tkinter and Pmw It is available at : http://pyvon.sourceforge.net The software includes one main file and 6 others which are for the language customization. People can choose between French, English, German,... All the translations for these languages are stored in files called menu_francais.py, menu_english.py, menu_deutsch.py ....when the editor is started. I would like to clean the directory a bit and put all these 'languages files' into a sub-directory called Lang. How do I tell python to look into a particular sub-directory when importing a file. I tried the os.path.join syntax, but to no avail. Below is the bit of code that imports the language file from the current working directory : try : homedir = os.path.expanduser('~') fd = open(homedir+"/.pyvonrc", 'r') for line in fd.readlines(): if line.startswith("Language :"): line=line[11:] if line.startswith("francais"):from menu_francais import * elif line.startswith("english"):from menu_english import * elif line.startswith("deutsch"):from menu_deutsch import * ............... Thanks, Fabien From mertz at gnosis.cx Wed Sep 25 20:57:06 2002 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Wed, 25 Sep 2002 20:57:06 -0400 Subject: a python puzzle Message-ID: I think the various responders did this "by hand." Probably having the Python source code made it even easier to just eyeball. In a more general sense (just in case anyone doesn't know), the way to solve a Caesar cipher like this is to start counting letter frequencies. Comparing the frequencies to well-known English letter frequencies like: http://gnosis.cx/download/letterfrequency.gif lets you start matching letters pretty quickly. Of course, if you don't know it's English, the frequency table isn't as accurate. I was thinking of writing a little solver script to actually assign likely permutations based on the frequencies. But a dozen people had already solved it before I saw the problem... so I gave up on that :-). Yours, Lulu... -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th. From a-steinhoff at web.de Thu Sep 12 05:24:47 2002 From: a-steinhoff at web.de (Armin Steinhoff) Date: 12 Sep 2002 02:24:47 -0700 Subject: Multi-threading python References: Message-ID: Chris de Souza wrote: >We require the ability to run multiple Python sessions in parallel >under VxWorks. Python 'sessions' ... what does it mean ?? Well .. it"s a pity that VxWorks isn't a multi user OS. With other OS'es you can run Python in different terminal sessions ... >Has anyone developed a version of Python which supports multi-threading >different Python sessions? Python does multi threading at OS level .. We have re-compiled the stackless version of Python for QNX6 ... it looks very interesting. Is Stackless Python an option ??? (w/o OS threads, w/o the GIL) Armin > Chris de Souza email: chrisd at hpato.aus.hp.com >Australian Telecom Operation >Hewlett-Packard Australia Ltd >31 Joseph St, Blackburn 3130, Australia From chris.gonnerman at newcenturycomputers.net Mon Sep 23 22:10:39 2002 From: chris.gonnerman at newcenturycomputers.net (Chris Gonnerman) Date: Mon, 23 Sep 2002 21:10:39 -0500 Subject: cursor positioning and color References: <1b6dca50.0209231022.6fae7f6d@posting.google.com> Message-ID: <00a701c2636f$9daa5260$0101010a@local> ----- Original Message ----- From: "brrrent" > TuxTrax at fortress.tuxnet.net (TuxTrax) wrote in message news:... > > Being new to python, I would like to know how one goes > > about such tasks as precise cursor positioning and output > > to screen in color. > > Hi Mathew, > > Curses is the way to go when using Linux/Unix. > > Wconio is the way to go when using Microsoft. > You can find in the Vaults of Parnassus. If you have any > trouble locating it, let me know, I can email it to you. > Small library, works well. Hey, thanks for the nice plug! Actually, WConio is my Pythonic adaptation of TCCONIO.C by Daniel Guerrero Miralles. It's at: http://newcenturycomputers.net/projects/wconio.html Chris Gonnerman -- chris.gonnerman at newcenturycomputers.net http://newcenturycomputers.net From peter at engcorp.com Sat Sep 14 16:44:30 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 14 Sep 2002 16:44:30 -0400 Subject: Converting a string to time - simple task but don't know how to do it! References: <7A6D2E53461F2BF2.AC83A3D5E1A01468.48CC780BD6530537@lp.airnews.net> Message-ID: <3d839f9d$1@news.sentex.net> Richard Kessler wrote: > I have a string returned from a database expressing the time i.e. 2002-09-14 > 10:30:34. I need to compare this value to the current time to determine the > amount of time elapsed between the two. I get the current time using > time.time() but I cannot find a way to convert the string from the database > into a time value (seconds from epoch) to do the simple subraction to find > seconds elapsed. If the format is exactly that, you could use something primitive like this: >>> s = '2002-09-14 10:30:34' >>> import re, time >>> tt = tuple(map(int, re.findall('(....)-(..)-(..) (..):(..):(..)', s)[0]) + [0,0,0]) >>> time.mktime(tt) 1032017434.0 -Peter From syver-en+usenet at online.no Tue Sep 17 08:48:38 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 17 Sep 2002 12:48:38 GMT Subject: faster way for adding many strings References: <3d8720b8$1@news.sentex.net> Message-ID: Peter Hansen writes: > Ulli Stein wrote: > > Hi, > > What is the faster way: appending many strings to a list and then > > joining them, or writing to StringIO and then getvalue()? > > Alex' detailed response notwithstanding, there's another usual > answer to your question: > > "Premature optimization is the root of all evil in programming" > (D. Knuth) > > It means you usually shouldn't care which is faster until (a) your > software is working fully, and (b) you have profiled the code > and determined that in fact you have an unacceptable bottleneck > which must be optimized to meet your requirements. > > Don't get me wrong, there _are_ times to optimize. You just > shouldn't see them very often... and life is simpler that way. :) Summarized: make it work, make it right, make it fast. (In that order). -- Vennlig hilsen Syver Enstad From andrew-pythonlist at puzzling.org Fri Sep 27 21:59:26 2002 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sat, 28 Sep 2002 11:59:26 +1000 Subject: Python threading? In-Reply-To: Message-ID: <20020928015926.GB450@frobozz.local> Robert Oschler wrote: > Having written _many_ state machines in my life, which async programming > boils down to in one form or another, I feel it depends on the task. When > you have an async event driven model, the code that services a > "transaction-package" ends up spreading functionality that services the > "transaction-package" application's code landscape. This can frequently > be a headache. As an example of a "transaction-package", take all the > steps involved in servicing an incoming TCP connection, with custom > authentication of a user, and perhaps a header and data object > transacttion or two, finishing with a proper ending and cleanup of the > transaction, and with subsequent notification of all necessary modules and > data structures of the results of the transaction. For dessert add a > centralized clean error handler that can log errors propertly and > gracefully recover the app regardless of where in the distributed event > flow the error took place. You want Twisted. http://twistedmatrix.com/ It's an asynchronous networking framework which has an elegant abstraction of callbacks and error handlers that I find make event-based programming a breeze. See http://twistedmatrix.com/documents/howto/defer for a detailed description of how this works. It makes it trivial to sequence a series of operations on some event, regardless of when it happens. In fact, here's a breakdown of your steps and Twisted: 1. "servicing an incoming connection": twisted.internet does that for you. It's dead easy. 2. "custom authentication of a user": Use the twisted.cred package. This is exactly what it is designed for. It has a standard asynchronous interface, with ready-made implementations involving a simple python dict, and also a database-based implementation. 3. "perhaps a header and a data object transacttion": There isn't general transaction support in Twisted, but I imagine any object database you'd be using would support them, e.g. the ZODB. And again, Deferreds make it easy to catch exceptions and so on (see my next points). 4. "centralized clean error handler than can log errors properly and gracefully recover": Twisted's Deferreds make that trivial. In fact, if you forget to install an error handler, Twisted will log the error for you automatically. Deferreds callbacks and errbacks in many ways mirror your usual try/except constructs, so structured error handling is straightforward. See the doc I linked to above for more details. Also, Twisted's main loop will never be crashed by an exception in one of the connections it services... in general, if something causes one connection to crash, the rest of Twisted merrily keeps on going regardless. > Contrast this with a simple procedure call where a linear series of > function calls are made, each with appropriate error handling and status > adjustment, in a pleasant centrally located manner. For instance, talking to a database asynchronously, Twisted-style: # See also http://twistedmatrix.com/documents/howto/enterprise deferred = db.runQuery('SELECT * FROM table') Then hooking up a bunch of callbacks: deferred.addCallbacks(gotResult, somethingBroke) deferred.addCallbacks(doStep2, step2Rollback) deferred.addCallback(doStep3) # step 3 doesn't care about rollbacks # ...etc... # Catch any uncaught errors deferred.addErrback(logError) The results of each callback get fed into the next, so you can perform a series of data transformations or whatever, e.g. perhaps you want something like: # Note that addCallback returns the Deferred for your convenience deferred.addCallback(recordSetToXML).addCallback(applyXSLT) # etc Which looks like a linear series of function calls to me, and it certainly has error handling (.addErrback) and status adjustment (you could easily be updating an instance variable from within the callbacks). And there's even more to Deferreds than I've described here! Go read the documentation :) > There is an upcoming massively multiplayer game called EVE which is using > Stackless Python which makes this point quite well. Game AI suffers from > the same design considerations as mentioned above. Here's the link if > you're interested (I'm not associated with them in any way, just > considering taking a look at Stackless). Look for question "8.5 How is > the game logic implemented in EVE?": Interesting. Twisted is actually designed with exactly this goal in mind (MMORPG). Stackless is nice, but I think for what you're talking about Twisted already solves your problems in "pure" Python :) Twisted is an excellent framework. I highly recommend you download it (version 0.99.2 is still fresh off the press -- grab it while it's hot!), play with it, bug us on the mailing list and irc channel (#twisted on irc.freenode.net), and let us know what you think. We think you might just like it. -Andrew. From gerhard.haering at opus-gmbh.net Wed Sep 4 05:45:13 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 4 Sep 2002 09:45:13 GMT Subject: encryption (passwords) References: <3d75d115$0$221$4d4ebb8e@news.nl.uu.net> Message-ID: Gumuz wrote: > I am quite a newbie regarding encryption stuff. There are some issues > boggling my head and I suppose these come from the fact that I have no > clue how to apply encryption in a real-life situation. > > I am using network-sockets to communicate between two(or more) python > applications. I want to encrypt these messages, or at least a part of it > e.g. password and such. Ok. I'd recommend to use SSL instead of inventing your own crypo layer. I'd probably go with PyOpenSSL. > My limited understanding of encryption tells me that I need a 'key' to > decrypt stuff. There are two kinds of encryption: - symmetric encryption - assymemtric encryption Symmetric works by both ends having the same key. The sender encrypts the message with the key, the receiver decrypts it using the same key. The problem is that you have to distribute the keys first, and have a secure way of distributing the keys. Asymmetric encryption works by splitting the key up into a private and a public key. The private key can only be used for decrypting, the public key only for encrypting messages. -- Gerhard From user at domain.invalid Mon Sep 9 14:44:02 2002 From: user at domain.invalid (ryan) Date: Mon, 09 Sep 2002 18:44:02 GMT Subject: old ODBC module References: Message-ID: Perfect! Thanks. ryan. Gillou wrote: > Google for "Mark Hammond win32 python extensions". > It's in the package. > > --Gilles > > mailto:gilles at pilotsystems.net > "ryan" a ?crit dans le message de news: > f5ae9.2146$Qx1.35346 at news1.telusplanet.net... > >>Does anyone know where I can find the old free odbc module? Not the >>mxODBC module, but the other (apprently not very well supported) one. >>I've been looking for a while without success. Thanks! >> >>ryan. >> > > > > From Padraig at Linux.ie Mon Sep 30 12:22:52 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Mon, 30 Sep 2002 16:22:52 GMT Subject: redhat8 References: <873crr4fy6.fsf@flibuste.net> Message-ID: <3D987A16.2070401@Linux.ie> William wrote: > hi, > > anybody know wich version of python is /usr/bin/python on the new redhat > release ? > You only need the first 10M of the iso to get this info: (mount -o loop psyche-i386-disc1.iso somedir) pyOpenSSL-0.5.0.91-1.i386.rpm 482027 Sep 3 23:36 pygtk2-1.99.12-7.i386.rpm 1249637 Sep 5 05:42 pygtk2-libglade-1.99.12-7.i386.rpm 142016 Sep 5 05:42 python-2.2.1-17.i386.rpm 4371618 Sep 3 22:35 python-devel-2.2.1-17.i386.rpm 571688 Sep 3 22:35 python-optik-1.3-2.noarch.rpm 44828 Sep 3 22:35 P?draig. From see_reply_address at something.invalid Tue Sep 17 20:51:22 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 18 Sep 2002 12:51:22 +1200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: <3D87CE0A.9090609@something.invalid> Michael Chermside wrote: > (4) Stackless works on some architechures (including at least X86, > Sparc, PPC and Cygwin). But it does NOT work on some other > architectures. So (rather like the thread package) it is not > as portable as Python itself. Also, I believe that, even on the supported architectures, it plays dangerous tricks with the C stack. I'd prefer to see that fixed before making it a standard part of the distribution. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From findler_lambda at yahoo.com Sun Sep 8 15:39:04 2002 From: findler_lambda at yahoo.com (Robert Hanlin) Date: 8 Sep 2002 12:39:04 -0700 Subject: Larry Wall's comment on python... References: Message-ID: Rod Stephenson wrote: > "Python is cool to look at small bits of, but I think the "outline" > syntax breaks down with larger chunks of code. Looks like Larry is simplifying or making a novice mistake. Knuth wrote that whitespace indentation is good when languages can let you write small blocks of code. Python does this for you. In fact, Python is set up to gently prod you to write clear chunks of code. Perl is not. It's a different philosophy. If he believes there's more than one way to do things, he should realize that Python has its own way. Rob From ken at hotmail.com Fri Sep 20 20:34:26 2002 From: ken at hotmail.com (Ken) Date: Sat, 21 Sep 2002 10:34:26 +1000 Subject: Python question on printout to HTML Message-ID: Hi, I wonder how you make the program to print out onto HTML such that it prints at a time delayed setting of about 5-10 seconds between each line of text so that the steps can be more readable to the user of the interface? Thanks From cotabas at earthlink.net Tue Sep 3 21:47:48 2002 From: cotabas at earthlink.net (CotaBas) Date: Wed, 04 Sep 2002 01:47:48 GMT Subject: Executable Python Programs References: <1rtc9.108$LI2.7238@newsread2.prod.itd.earthlink.net> Message-ID: <8Ddd9.6311$6i4.491988@newsread1.prod.itd.earthlink.net> > > My personal opinion is that py2exe/Installer/etc. are for > > intermediate/advanced Python programmers. The reason is that it's > > sometimes difficult to fix the dependencies manually, if these tools are > > unable to hunt them down automatically for you. > > I think you may be overstating the difficulty here. The vast majority of > programs run through py2exe etc. with no problems at all. I can only think > ot a couple of times that I have even had to think about the dependencies: > > I had a case recently with py2exe was when it found some extra dependencies > that I didn't want: I was using jabber.py which for not very good reasons > imports site.py which indirectly imports a whole load of stuff such as > tkinter. Explicitly excluding site.py fixed this. Admittedly it took me a > little while to track down which import was the problem. An option to > py2exe to dump out why it decided to pull in each module would have been > helpful. > > The only time I had trouble with an import that wasn't being found was when > I used py2exe on a program using PIL. PIL demand loads a lot of converters > for different graphics formats which was beyond py2exe's capabilities. > Explicitly importing all the formats I wanted into the main program fixed > that one. I tried useing Installer and could not get it to work, but when I used py2exe I got it to work just fine Thank you for all your help and I'm sorry I didn't read the FAQ..... From park997 at aol.comnotospam Wed Sep 18 15:26:45 2002 From: park997 at aol.comnotospam (Park997) Date: 18 Sep 2002 19:26:45 GMT Subject: Tkinter:select directory dialog? References: <0x3i9.13118$HY3.2916659@newsc.telia.net> Message-ID: <20020918152645.03154.00006132@mb-dh.aol.com> Thanks this did the trick. I am still using Python 2.0. The addition of askdirectory to Python 2.2 was a good idea :-). Wendell Cropper >> from tkCommonDialog import Dialog >> class Chooser(Dialog): >> command = "tk_chooseDirectory" >> def _fixresult(self, widget, result): >> if result: >> self.options["initialdir"] = result >> self.directory = result # compatibility >> return result >> >> def askdirectory(**options): >> return apply(Chooser, (), options).show() > >(hmm. I think I've seen that code before...) > >the askdirectory function and a Directory class (same as >the Chooser above) was added to the tkFileDialog module >in Python 2.2: > > from tkFileDialog import askdirectory > > directory = askdirectory( > title="select directory", > mustexist=1 > ) > > if not directory: > print "cancelled" > else: > print "selected", directory > > > > > > From mhuening at zedat.fu-berlin.de Wed Sep 18 15:00:42 2002 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: 18 Sep 2002 19:00:42 GMT Subject: BibTeX module? References: Message-ID: Pearu Peterson wrote in news:mailman.1032359243.24708.python-list at python.org: > http://cens.ioc.ee/~pearu/misc/readbib.py > > that I use to maintain my bib file database. > Thanks. - Matthias From henrik.motakef at web.de Fri Sep 27 16:19:20 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 27 Sep 2002 22:19:20 +0200 Subject: [XML-SIG] well-formed xml References: Message-ID: <878z1nuqwn.fsf@pokey.henrik-motakef.de> "Mike Rovner" writes: > IIRC, double quotes are the must: > s = 'search' No, single quotes are perfectly OK. From florian.proff.schulze at gmx.net Mon Sep 30 15:46:24 2002 From: florian.proff.schulze at gmx.net (Florian Schulze) Date: Mon, 30 Sep 2002 21:46:24 +0200 (Westeuropäische Sommerzeit) Subject: Printing with python Message-ID: Hi! I would like to know what solutions exist for printing (on paper) with python. Preferable would be a crossplatform approach, but only for Windows would be good enough. I also thought about using the reportlab pdf lib and using the free Acrobat Reader for preview and printing. It has a nice API and I don't think it will be too hard to send it to Acrobat Reader. Any suggestions or thoughts about this? Regards, Florian Schulze From jepler at unpythonic.net Tue Sep 17 08:08:44 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 17 Sep 2002 07:08:44 -0500 Subject: Difflib question In-Reply-To: <886c5e4b.0209161208.25012958@posting.google.com> References: <886c5e4b.0209161208.25012958@posting.google.com> Message-ID: <20020917120842.GB18327@unpythonic.net> On Mon, Sep 16, 2002 at 01:08:44PM -0700, Robin Siebler wrote: > Is there a way to get difflib to output *only* the lines that are > different (instead of all of the lines)? you can almost certainly do this by going "lower-level" yourself, and using difflib.SequenceMatcher directly. roughly: # create a sequence matcher object m = difflib.SequenceMatcher(None, s1, s2) # get the opcodes ops = m.get_opcodes() for op, i1, i2, j1, j2 in ops: # Do something with each opcode pass see my pyunidiff program at http://unpythonic.net/~jepler/pyunidiff.py for a more complex example. Jeff From 53ab2750 at meowing.net Sat Sep 28 06:24:29 2002 From: 53ab2750 at meowing.net (itsy bitsy meowbot) Date: Sat, 28 Sep 2002 10:24:29 GMT Subject: print a % References: Message-ID: Claude wrote: > When I do > print "image size=%d%" %(50) > I've got an error > > Traceback (most recent call last): > File "", line 1, in ? > ValueError: incomplete format > > I do not know how to escape the second % print "image size=%d%%" %(50) From christina at iaeste.at Wed Sep 11 06:15:25 2002 From: christina at iaeste.at (Christina) Date: 11 Sep 2002 03:15:25 -0700 Subject: function pointer Message-ID: Hi! Does Python have function pointers? If not, is there a possibility to emulate them? Christina From sismex01 at hebmex.com Thu Sep 26 19:22:12 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 26 Sep 2002 18:22:12 -0500 Subject: Who knows somefunction? Message-ID: > > Marco Mariani > > Now you can harm yourself. :-) > > > > Tested with python 2.2.1 > > > > ;-) > > FWIW, against current cvs it crashes when you do: > > from pointer import pointer > x = range(3) > y = id(x) > del x > x1 = pointer(y) > print x1 > > Where's Houdini when you need him... > > > -- > > Emile van Sebille > emile at fenx.com > Well, that's more or less expected; when you do the "del x", the object is deallocated, and y contains the address of rubbish. I haven't compiled it yet; what happens when you don't "del x" before you declare x1? -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From codeapocalypse at msn.com Tue Sep 17 18:41:53 2002 From: codeapocalypse at msn.com (Brian) Date: 17 Sep 2002 15:41:53 -0700 Subject: Win32COM & Detaching from automation servers Message-ID: I've searched this newsgroup for an answer to my problem, but haven't come up with anything. (Perhaps the solution is obvious and I'm just not seeing the forest for the trees...) I want to write a Python program on Windows which will use the automation interface for Excel. What I want it to do is launch Excel, open a template, stuff data into it (based on command line parameters to the Python app), detach from Excel and exit, leaving Excel open. I know how to do everything except for the detach part. Any help is much appreciated. From hartmut.goebel at noris.de Wed Sep 11 12:08:09 2002 From: hartmut.goebel at noris.de (Hartmut Goebel) Date: Wed, 11 Sep 2002 18:08:09 +0200 Subject: ANN: shellwords.py 0.1 Message-ID: <3D7F6A69.C5CD2912@crazy-compilers.com> Announcing: shellwords.py ============= Version 0.1 Parse a string into words like a POSIX shell does. Why this module? ---------------- Out in the wild there are quite a few modules for executing commands in a sub-process. Most of them take a string (the command-line) as input and use os.exec* for executing the program. This requires splitting the string into words _exacly_like_the_shell_ does. If this parsing/splitting is incorrect you can have quite some funny time debugging. ;-) Since I didn't find found any other module that-like, I decided to develop this module. Benefits using this module -------------------------- Using this module has the following benefits: - Enables your application or module to mimic word splitting like a POSIX shell without effort. - Saves yourself debugginf-time then doing word-splitting. - Avoids confusin the users of you application/module when splitting shell command lines into words, since this module behaves _exactly_ like a POSIX shell does. - The Unittest-Suite proves the correct word-splitting. Currently 75 command lines are used, each testing a special pattern. The input data for this test-suite consists of command-lines which are split ba the shell on-fly fly. You can add your own test-patterns without any hassle. Semantics --------- This module parses a string into words according to the parings-rules of a POSIX shell. These parsing rules are (quoted after 'man bash'): 1) Words are split at whitespace charakters; these are Space, Tab, Newline, Carriage-Return, Vertival-Tab (0B) and Form-Feet (0C). NB: Quotes do _not_ separate words! Thus "My"Fancy"Computer" will be parsed into a single word: MyFancyComputer 2) A non-quoted backslash (\) is the escape character. It preserves the literal value of the next character that follows. 3) Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. This means: baskslash (\) has no special meaning within single quotes. All charakters within single quotes are taken as-is. 4) Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of \. The backslash retains its special meaning only when followed " or \. A double quote may be quoted within double quotes by preceding it with a backslash. Availablity ----------- 'shellwords' is available for download at http://www.crazy-compilers.com/py-lib/#shellwords Requirements ------------ Requires Python >= 2.0 Frequently Asked Questions -------------------------- Q: Hey, there is 'shlex' coming with Python. Why there is a need for this module? A: I know 'shlex' and I gave it a try. But 'shlex' takes quotes as word-delemiters which divers from the shell-semantic (see above). And even if 'shlex' would parse strings as needed, I would have written a (very, very) thin layer above, since 'shlex' is simple but seldomly used for this kind of job. Copyright/License ----------------- (C) Copyright 2002 by Hartmut Goebel License: Python Software Foundation License http://www.opensource.org/licenses/PythonSoftFoundation.html From maxm at mxm.dk Fri Sep 6 03:56:17 2002 From: maxm at mxm.dk (Max M) Date: Fri, 06 Sep 2002 09:56:17 +0200 Subject: What database should I use References: Message-ID: <3D785FA1.6090201@mxm.dk> A wrote: > I am going to program a small application (in Python and wxPython) which consists about > 2000 - 3000 records . Can you please recommend which database is the best for that. I > use Windows. > Maybe MS Access or FoxPro or MySQL or better? > I want to keep the program as small as possible. In such a small program why don't you just use shelve from the standard library? You can store your objects directly in it and you don't have to install any db. regards Max M From loewis at informatik.hu-berlin.de Fri Sep 6 09:11:22 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 06 Sep 2002 15:11:22 +0200 Subject: Python and Jython inconsistencies when encoding strings References: Message-ID: "Andre Michel Descombes" writes: > I've noticed the following inconsistency between Python 2.1 and > Jython 2.1 : when I do the following in Python : > >>> s = u'?' # Alt-0163, pound sign > >>> print s Please try >>> s u'\x9c' Notice that Unicode U+009C is a control character, STRING TERMINATOR, and not U+00A3, POUND SIGN. You may wonder where it gets the 9C value from: This is because, in a console window, Microsoft uses code page 850 (probably), which uses /x9c POUND SIGN So when you enter a Alt-0163, the terminal reports the byte 0x9c, not the byte 0x00A3. In Python 2.x, you can only use non-ASCII in Unicode literal if it is Latin-1. However, your pound sign is not entered in Latin-1, but entered in cp850. To really get a pound sign into a Unicode literal, you need to write >>> s = u"\u00A3" >>> print s.encode("cp850") You should use cp850 here, since your terminal uses cp850, not Latin-1. > now when I do the same thing in Jython 2.1 I get this: > > >>> s = u'?' # Alt-0163, pound sign > >>> print s > ? > >>> > > and if I do: > >>> print s.encode('latin-1') This is interesting, since you also get >>> s u"\u0153" Now, U+0153 is LATIN SMALL LIGATURE OE. It so happens that \x9c (what the terminal sends) is U+0153 in CP 1252 (which is the ANSI code page on your Windows installation). This might be a bug in Java, which assumes that bytes sent by the terminal are in the ANSI code page, when they are really in the OEM code page. > Does anybody know what is causing this inconsistency? Is there any way to > avoid it? Yes. Don't use the console. Regards, Martin From oren-py-l at hishome.net Tue Sep 17 08:30:28 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Tue, 17 Sep 2002 08:30:28 -0400 Subject: More on Protecting Source Code In-Reply-To: References: <20020917062412.GA85457@hishome.net> Message-ID: <20020917123028.GA19214@hishome.net> On Tue, Sep 17, 2002 at 03:22:20AM -0700, David LeBlanc wrote: > Oh yeah, and my views of intellectual property seems to be a lot > closer to the law of the land then yours. The Law is not a view, it is a set of rules and enforcement mechanisms. Our views are personal interpretations of the Law in the context of the society in which we live and our moral values. Here are two alternative interpretations of information restriction laws: 1. Information and knowledge is a scarce resource and should be closely held and treated as property just like physical goods. Information belongs to its creator or any entity to which it has been sold. Transmission, storage or use of information without the consent of its owner is theft. Expiration of copyrights and patents? Ummm.... must be some bug in the system. It will be fixed ASAP. 2. Information and knowledge is abundant. Information belongs to all of mankind. Sharing information promotes creativity and thus creates even more information, knowledge and wealth. In order to encourage individuals to create new valuable information and distribute it the state offers them an arrangement whereby they can use the power of the courts and police to restrict the rights of others to use this information in certain ways. These include restricting the right to copy and distribute information for profit (copyright) and restricting the right to build and sell goods based on the information (patents). This extraordinary power must be limited: it is only granted for a limited period and certain types of fair use are protected from it. In the case of patents the the inventor must fully disclose his invention in the patent application so when the restriction period expires it enters the public domain for the benefit of society instead of being lost as a trade secret. The first view may be a lot closer to the way the law of the land is seen by corporations and the politicians they buy. The second view is much closer to the intentions and beliefs of the noble people who originally drafted these laws. It grieves me to see how these laws have been perverted over time. I hope that my participation in the open source community makes a tiny contribution to improving the situation. We both respect the same laws, we just see them differently. For me, information restriction laws are a necessary compromise of my freedom while you appear to treat them as an inalienable right. Oren From pygta at engcorp.com Mon Sep 16 21:46:25 2002 From: pygta at engcorp.com (Peter Hansen) Date: Mon, 16 Sep 2002 21:46:25 -0400 Subject: Final reminder of PyGTA (Toronto Python/Zope group) first meeting Tuesday night Message-ID: <3d868963$1@news.sentex.net> This is the final reminder of the first meeting of the new Toronto-area Python and Zope user group. The meeting will take place Tuesday, September 17 at 7:00 pm the Willowdale United Church at 379 Kenneth Ave in North York (just to the south-east of the Finch subway station). Details including an agenda and a map are available here: http://web.engcorp.com/pygta/wiki/FirstMeeting We hope to see you out there. ActiveState has generously donated some goodies which we'll distribute Tuesday and at the second meeting. (Currently we have roughly twenty people registered to attend but you don't need to register to come out!) -Ian Garmaise, Peter Hansen, and the rest of the PyGTA organizing committee From peter at engcorp.com Wed Sep 4 08:35:04 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 04 Sep 2002 08:35:04 -0400 Subject: newsgroup for zope References: Message-ID: <3d75fddc@news.sentex.net> stephan wrote: > Hi perhaps a stupid question, > > but does there exist a newsgrup for zope centric items? ^^^^^^^^ You spelled "newsgroup" wrong. It's spelled "mailing list" and you can find out about them here: http://www.zope.org/Resources/MailingLists :-) -Peter (There's no actual newsgroup though.) From marco at sferacarta.com Fri Sep 6 11:24:18 2002 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 6 Sep 2002 17:24:18 +0200 Subject: ttySx In-Reply-To: <200209061708.25677.b.maryniuk@forbis.lt> References: <200209061708.25677.b.maryniuk@forbis.lt> Message-ID: <20020906152418.GA6937@sferacarta.com> On Fri, Sep 06, 2002 at 05:08:25PM +0200, Bo M. Maryniuck wrote: > I've tried do somethig like: > > modem = open('/dev/ttyS0', 'r+') > modem.write('ATZ\r') > modem.read() # Hang here forewer > > This is bad. Then I've tried use several modules for serial port, wheere I can > write, but if I read, always get ''. > > Perhaps I should figure out with DTR status and so on.... Any ideas? Here it is. Of course, the code is old and sucks. If you have problems with lock files, I don't want to know :-) If you or anybody patch it, I would like to know.. # # modem.py # import os, time, signal from termios import * def timeout(signum, frame): raise IOError, "Timeout!" speeds = { 2400:B2400, 4800:B4800, 9600:B9600, 19200:B19200, 38400:B38400, 57600:B57600, 115200:B115200, 230400:B230400, 460800:B460800 } class Modem: devname=None lockname=None locked=0 fd=-1 old_term=None new_term=[ # iflag oflag cflag IGNPAR, 0, CRTSCTS | CS8 | CLOCAL | CREAD, # lflag ispeed ospeed 0, 0, 0, # cc ['\000']*32 ] answer=[] def __init__(self,name): self.devname = name self.lockname = '/var/lock/LCK..%s' % name def purge(self): if self.fd>=0: self.alarm_on() try: os.close(self.fd) except: pass self.alarm_off() if self.locked: os.unlink(self.lockname) # # 0: OK # -1: Errore # def __lock(self,last_try=0): try: fd = os.open(self.lockname, os.O_RDWR | os.O_EXCL | os.O_CREAT, 0644) os.write(fd,'%10s\n' % os.getpid()) os.close(fd) self.locked = 1 return except: if not last_try: time.sleep(0.2) pid = int(open(self.lockname,'r').readline()) try: os.kill(pid,0) return -1 except OSError: os.unlink(self.lockname) return self.__lock(last_try=1) else: return -1 def alarm_on(self): signal.signal(signal.SIGALRM, timeout) signal.alarm(1) def alarm_off(self): signal.alarm(0) # # 0: OK # -1: Errore # def open(self): if self.__lock(): return -1 self.alarm_on() try: self.fd = os.open ('/dev/'+self.devname, os.O_RDWR | os.O_NOCTTY); except: self.fd=-1 self.alarm_off() return self.fd<0 def term_init(self): try: self.old_term = tcgetattr(self.fd) self.new_term[6][VMIN]=1 self.new_term[6][VTIME]=0 tcflush(self.fd,TCIFLUSH) tcsetattr(self.fd,TCSANOW,self.new_term) self.set_speed(B2400) return 0 except: return -1 def term_reset(self): self.alarm_on() try: tcsetattr(self.fd,TCSANOW,self.old_term) retval = 0 except: retval = -1 self.alarm_off() return retval def set_speed(self,rate): if rate in speeds.keys(): rate = speeds[rate] self.new_term[4] = rate self.new_term[5] = rate tcsetattr(self.fd,TCSANOW,self.new_term) def sendline(self,line): if not os.write(self.fd,line+'\015'): return 1 time.sleep(0.2) self.answer=[] s='' while 1: self.alarm_on() try: c = os.read(self.fd,1) except: retval = -1 break if c=='\015' or c=='\012': if s: self.answer.append(s) if s=='OK': retval = 0 break if s=='ERROR': retval = 1 break s='' else: s += c self.alarm_off() return retval From kennethg at pd.jaring.my Fri Sep 27 23:50:53 2002 From: kennethg at pd.jaring.my (Kenneth Gomez) Date: Sat, 28 Sep 2002 03:50:53 GMT Subject: Local Python Server Installation References: <3d8b47c6.277669@news.jaring.my> <3d8c993c.2190426@news.jaring.my> <3d8d4009.375344@news.jaring.my> <3d947c26.2656654@news.jaring.my> Message-ID: <3d952602.1791864@news.jaring.my> Dear Steve, I managed to get it to work!! I didnt configure the ScriptAlias directory to where my scripts were. How silly of me! Thanks a lot Steve. Regards, Kenneth Cheers, Kenneth Gomez. From aurin42 at yahoo.com Tue Sep 3 04:06:05 2002 From: aurin42 at yahoo.com (Ante Bagaric) Date: Tue, 3 Sep 2002 10:06:05 +0200 Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: > reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) I like your sig :) From beall at psych.ucsb.edu Thu Sep 26 14:16:03 2002 From: beall at psych.ucsb.edu (Andy Beall) Date: Thu, 26 Sep 2002 11:16:03 -0700 Subject: distributing apps w/embedded python & missing modules Message-ID: I working on an application in which I embed python to allow the end-user to customize the apps behavior with scripts. My question: Is there an easy way to compile all of Python's modules into the app so that the user does not need to separately download the core python package? If there's standard explanation for that which I've missed, just a reference to that would be greatly appreciated. Thanks, Andy- From tchur at optushome.com.au Sat Sep 7 17:37:34 2002 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 08 Sep 2002 07:37:34 +1000 Subject: Smoothing a discrete set of data References: <3csmdso5.fsf@morpheus.demon.co.uk> Message-ID: <3D7A719E.B8AE64E8@optushome.com.au> Fernando Pereira wrote: > > On 9/7/02 6:02 AM, in article 3csmdso5.fsf at morpheus.demon.co.uk, "Paul > Moore" wrote: > > I have a set of data, basically a histogram. The data is pretty > > variable, and I'd like to "smooth" it to find trends. [...] When I've tried to > formalise this, I've always stumbled over the fact > > that it's a trade-off exercise (there most be some sort of "tolerance" > > parameter in the algorithm) - on the one hand, the original data is > > "best" (in the sense that it matches exactly) whereas on the other > > hand, a single horizontal line at the average is "best" (fewest number > > of steps). > > > > My instinct is that you're looking for something that balances number > > of steps vs difference from the original data. But for the life of me > > I can't see how to make this intuition precise. > > > > Can anyone help me? I can't believe that this problem has never come > > up before, but I can't find any literature on it. > You must have been using the wrong search engine This is the problem > of *regression*, extensively studied in statistics and machine learning. The > tradeoff you mention is discussed in the literature under headings like > "bias-variance tradeoff", "generalization bounds", "structural risk > minimization"... If you want a single good book that covers this and related > topics with a minimum of prerequisites (elementary calculus and linear > algebra, a teeny bit of probability), I recommend > > I agree that the problems with which Paul is wrestling are addressed by the discipline of modern statistics. However, I suspect that the abovementioned book by Hastie, Tibshirani and Friedman, although truly excellent, might be a bit too specialised for Paul's needs. Some introductory texts which cover various regression techniques (linear, non-linear, local, polynomial etc) might be more appropriate. BTW, Paul, you describe your data as a "histogram" but say you want to find "trends". "Histogram" implies that the data represent a frequency distribution, but looking for "trends" implies that they are a time-series - you need to be clear in your own mind about this because different smoothing and regression techniques are used for each. Of course, there is no need to write your own routines to implement these statistical techniques. AFAIK, there is no native Python package which implements a comprehensive range of regression and smoothing techniques, but I can highly recommend the R package for statistics and statistical graphics - this mature, free, open source package has more statistical facilities than you are ever likely to need. It runs on all major platforms, and some excellent introductory (free) texts are available for it - see http://www.r-project.org If you are using a Unix, Linux or Mac OS X system, you can even use R from within Python, thanks to Walter Moreira's excellent RPy module - see http://rpy.sourceforge.net Hope this helps, Tim C From aleax at aleax.it Wed Sep 18 10:12:14 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 14:12:14 GMT Subject: monetary applications [was: Python GUI app to impress the boss?] References: Message-ID: <2R%h9.109893$ub2.2324479@news1.tin.it> Mark McEahern wrote: > [Oren Tirosh] >> I don't understand what exactly you are complaining about but is sounds >> interesting - can you elaborate? > > Perhaps the lack of a FixedPoint type? http://starship.python.net/crew/aahz/FixedPoint.py Alex From dstuartkelly at online.ie Thu Sep 12 05:09:51 2002 From: dstuartkelly at online.ie (Daniel Stuart Kelly) Date: Thu, 12 Sep 2002 10:09:51 +0100 Subject: Anyone got a logfile script? - Help a n00b Message-ID: <1031821791.3d8059df94ea8@mail.online.ie> What I'm looking for is a little script when run will dig into a log file and look for a variable. When it finds the variable I want it to print that line and the 20 or so right above it to either screen or a plaintext file. I know it sounds simple, but I've only started learning this and I've no idea where to begin.. Any tips or pointers would also be helpful... Thanks /Daniel From eugene at ulka.com Thu Sep 19 12:32:53 2002 From: eugene at ulka.com (Eugene Pervago) Date: 19 Sep 2002 09:32:53 -0700 Subject: Loading modules from several directories References: <33803989.0209172247.2e6afc1f@posting.google.com> <6Q1i9.1149$bh1.989@fe03> Message-ID: "Steve Holden" wrote in message news:... > "Eugene Pervago" wrote ... > > They do not intersect. Actually the structure is something like this: > > /onedir/foo > > dbutils.py > > utils.py > > auth.py > > > > /anotherdir/foo - Nothing > > /anotherdir/foo/projectA > > User.py > > Product.py > > [snip] > > I'm at something of a loss to understand why both directories have to be > called foo and what the relationship is between them. Why not foo1 and foo2? > Am I missing something? In this case 'foo' would be the company name. I just wanted to avoid polluting top-level namespace and have all my modules within the foo.* namespace. Eugene Pervago From jknapka at earthlink.net Thu Sep 5 17:57:20 2002 From: jknapka at earthlink.net (Joseph A. Knapka) Date: Thu, 05 Sep 2002 21:57:20 GMT Subject: Python class ( Prolog ) ??? References: Message-ID: <3D77D340.A1D6641@earthlink.net> > Luis wrote: > > Does anyone have a class that provides the functionality of prolog ??? There's a SourceForge project that enables you to call GNUProlog from Python: I've seen a similar product for SWI Prolog as well, but the reference escapes me at present. It would be possible to implement a Prolog-like inference engine in Python, but it would be rather slow compared to genuine Prolog. Of course, for simple things that might not be a problem. I have a Prolog-like unifier written in Python lying around somewhere, which I'll track down and post if you're interested. It's not a complete inference engine, just the unification piece, but once you've got that building a simple resolver is not too difficult. If you want to implement cut, or things with side effects, it may get a bit hairy. Cheers, -- Joe "I'd rather chew my leg off than maintain Java code, which sucks, 'cause I have a lot of Java code to maintain and the leg surgery is starting to get expensive." - Me From jepler at unpythonic.net Thu Sep 19 18:19:53 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Thu, 19 Sep 2002 17:19:53 -0500 Subject: sorry for this stupid question about struct module In-Reply-To: <3d8a4ae7$0$280$7a628cd7@news.club-internet.fr> References: <3d8a4ae7$0$280$7a628cd7@news.club-internet.fr> Message-ID: <20020919171953.A3473@unpythonic.net> >>> '\x00\x00\x00\n' == '\x00\x00\x00\x0A' True '\x00\x00\x00\n' Ascii code 10 is repr()'d as \n. If you don't like this, you could use a different function to print the quoted value of a string: >>> quote = lambda s: "'" + "".join(["\\x%02x" % ord(c) for c in s]) + "'" >>> print quote("\0\0\0\n") '\x00\x00\x00\x0a' Jeff From edream at tds.net Mon Sep 2 07:48:00 2002 From: edream at tds.net (Edward K. Ream) Date: Mon, 02 Sep 2002 11:48:00 GMT Subject: Does IDLE handle unicode? Message-ID: IDLE took an exception writing a .py file containing the copyright character. This happened a while ago; IIRC, I lost the file. Is this a known problem? I see nothing about this in the FAQ. Edward -------------------------------------------------------------------- Edward K. Ream email: edream at tds.net Leo: Literate Editor with Outlines Leo: http://personalpages.tds.net/~edream/front.html -------------------------------------------------------------------- From tismer at tismer.com Sun Sep 8 10:30:17 2002 From: tismer at tismer.com (Christian Tismer) Date: Sun, 08 Sep 2002 16:30:17 +0200 Subject: Python plugins References: Message-ID: <3D7B5EF9.60909@tismer.com> Tobias Klausmann wrote: > Hi there, > > For an open source project that needs to be extensible by its > users, I would like to create a plugin architecture. Mind you, > I'm not trying to use Python as a plugin language only like XChat > or Gnumeric do. Let me illustrate: > > I have a directory somewhere in PYTHONPATH (let's just assume > it's in the CWD) that contains lots and lots of *.py files with a > defined set of functions (or, at least one: register()). What I'd > like to do now is being able to load these plugins at program > start and reload them if I'd like to later. Problem is that the > program has to figure out by itself what *.py files are there - > and I have to make sure somehow that I get a grip on the loaded > files. You can avoid exec at all. The PIL package (Python Imaging Library) from Fredrik Lundh has a similar problem: There are lots of image drivers in a directory, and PIL cannot know in advance what's there. Here an excerpt from Image.py, that shows what it does: """ def init(): "Load all file format drivers." global _initialized if _initialized >= 2: return visited = {} directories = sys.path + [os.path.dirname(__file__)] # only check directories (including current, if present in the path) for directory in filter(isDirectory, directories): fullpath = os.path.abspath(directory) if visited.has_key(fullpath): continue for file in os.listdir(directory): if file[-14:] == "ImagePlugin.py": f, e = os.path.splitext(file) try: sys.path.insert(0, directory) try: __import__(f, globals(), locals(), []) finally: del sys.path[0] except ImportError: if DEBUG: print "Image: failed to import", print f, ":", sys.exc_value visited[fullpath] = None if OPEN or SAVE: _initialized = 2 """ ... > Now I can just "import pi" and execute pi.rel() which in turn > loads all the modules that are there ('cept the ones that only > exist as pyc or pyo, but that's okay). But now I have two > problems: first, I have no idea how to call, say > pi.someplugin.dostuff(args) except constructing each and every > call as a string and exec() it - which is both error-prone and > awkward IMHO. If you executed a proper __import__, all modules and funcs should be accessible in the normal way. There is no need to exec. > Second, reloading just does not seem to work right as Python is > too smart ;) for me: it knows all of them have been loaded. So I > added the reload code above but to no avail. Reloading should work. If you have imported some module into your current one, reload(module) should work as expected. You will get into trouble if you imported the contents of a module like "from mod import *", since these identifiers will not get refreshed when you reload. You would need to repeat the from... import after reloading, since it copies the identifiers again to your namespace. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From loewis at informatik.hu-berlin.de Mon Sep 2 12:26:32 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 02 Sep 2002 18:26:32 +0200 Subject: version independant object usage counting References: Message-ID: "Rolf Kalbermatter" writes: > > That is only a minor problem: those macros are correct across all > > released Python versions, back to 1.4 or earlier. > > But there is a serious difference between the DEBUG and NON-DEBUG > PyObject_HEAD structure layout which I would like to not have to worry > about if possible. I see. > Does anyone see any problems with this code? Looks fine. > > * PyObject_INIT relies on initializing the object members. > > - PyType_HasFeature relies on the position of the tp_flags field > > I'm not using these function at all until now. May have to do so when > I start to add an extension module however? You might be using HasFeature implicitly, e.g. in PyIter_Check, or PyType_IS_GC. You might be using PyObject_INIT if you define types. In short, I agree with you that it is desirable to have function versions of everything that implies knowledge about the layout - however, as soon as you start extension modules (e.g. sre, socket), you will find that you require a specific version of the pythonxy.dll, anyway. Regards, Martin From mark at mceahern.com Mon Sep 9 14:33:10 2002 From: mark at mceahern.com (Mark McEahern) Date: Mon, 9 Sep 2002 13:33:10 -0500 Subject: shell expansion Message-ID: Is this supposed to work: filename = "$HOME/foo" f = file(filename) ... It doesn't seem to. // m - From lu_gio at hotmail.com Sun Sep 22 19:55:44 2002 From: lu_gio at hotmail.com (Max) Date: Sun, 22 Sep 2002 23:55:44 GMT Subject: OpenGL alpha channel not working Message-ID: <4Msj9.150251$pX1.5386352@news2.tin.it> """ Hi! I wrote this little test... it's working without errors, only strange behavor. I have 2 texures RGBA, one loaded and blitted into another and one generated with pygame.font. Can someone tell me why the font over the picture is working and the picture over the font is not?? If you want to test it, please sobstitute the GIFNAME and COLORKEY. Thanks """ #-----------------------------------------------BEGIN #-----------------------------------------------BEGIN #-----------------------------------------------BEGIN GIFNAME='fish1ne.gif' #------------- PUT your image here!!! mine was 60x42 gif with colorkey (255,0,255) COLORKEY=(255,0,255) from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * import os.path import sys import pygame def TestI(): pygame.init() pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF|HWSURFACE,32 ) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0,640,480,0,0,-1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glEnable(GL_BLEND) glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_TEXTURE_2D) glEnable(GL_DEPTH_TEST) psurf=pygame.surface.Surface((16*8,16*8),SRCALPHA,32) psurf.set_colorkey((0,0,0,0)) immge = pygame.image.load(GIFNAME) immge.set_colorkey(COLORKEY) psurf.blit(immge,immge.get_rect()) spsurf = pygame.image.tostring ( psurf, "RGBA" ) tx1 = AllocateTexture(psurf) mfont=pygame.font.Font(None,64) im = mfont.render('A',0,(255,255,255)) im.set_colorkey((0,0,0,0)) tx2 = AllocateTexture(im) while 1: event = pygame.event.poll() if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): sys.exit() glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glPushMatrix() glTranslate(100,100,0.5) mdraw(psurf, tx1) glPushMatrix() glTranslate(100,0,0) glScalef(5,5,0) mdraw(im, tx2) glPushMatrix() glTranslate(300,100,0) mdraw(psurf, tx1) glPushMatrix() glTranslate(300,0,0.5) glScalef(5,5,0) mdraw(im, tx2) pygame.display.flip() pygame.time.wait(10) def mdraw(sf, txx): glBindTexture(GL_TEXTURE_2D, txx) w, h=sf.get_size() glBegin(GL_QUADS) glTexCoord2f(0, 0) glVertex2i(0, 0) glTexCoord2f(1, 0) glVertex2i( w, 0) glTexCoord2f(1,1) glVertex2i( w, h) glTexCoord2f(0,1) glVertex2i(0, h) glEnd() glPopMatrix() def AllocateTexture(surface): image = pygame.image.tostring ( surface, "RGBA" ) ix, iy = surface.get_size () idImg = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, idImg ) glPixelStorei(GL_UNPACK_ALIGNMENT,1) gluBuild2DMipmaps(GL_TEXTURE_2D, 4, ix, iy, GL_RGBA, GL_UNSIGNED_BYTE, image) return idImg TestI() #-----------------------------------------------END #-----------------------------------------------END #-----------------------------------------------END From theller at python.net Fri Sep 13 15:48:41 2002 From: theller at python.net (Thomas Heller) Date: Fri, 13 Sep 2002 21:48:41 +0200 Subject: Problem with HTTPS request References: Message-ID: "Steve Holden" wrote in message news:mYqg9.8349$WV.1529 at fe03... > "Gerhard H?ring" wrote ... > > Christian Reyes wrote in comp.lang.python: > [...] > > >> "Christian Reyes" wrote in message > > > news:... > > ^^ > > > > Broken quoting. > > > > >> > [...] Note: HTTPS support is only available if the socket module was > compiled > > > with > > ^^ > > > > Broken quoting again. Please throw away that OE crapware or fix it > > using Morver or whatever. > > > Gerhard: > > You're showing distinct signs of having too much time on your hands :-) > Can't you fix your brain instead so it will let you ignore other people's > mailer problems? At least the pointer to Morver was interesting... Thomas From 2002 at weholt.org Thu Sep 19 08:24:46 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Thu, 19 Sep 2002 12:24:46 GMT Subject: StructuredText -> HTML module?? References: <3d89b69d$1@news.sentex.net> Message-ID: I need to take a piece of structured text as a string into a method and get html out in the other end. As described on the page on Zope.org under StructuredText. My hacking with PyWiki gave me a list where each element had a '
' in front of it etc. I might be using it the wrong way, but ....

I was under the impression that StructuredText as described on the site
mentioned earlier was sort of a standard, that the parser etc. would produce
the same output.

All I'm actually after is to be able to write stuff like :

**Header**

List:
1. Foo
2. Bar
3. Python

    Heres an indented section of text.

And turn this into

Header

List:
  1. foo
  2. bar
  3. Python

Heres an indented section of text.

Or something similar. Since there's allready something that I believed was standardized it would be easier to use modules allready available than doing it all from scratch. Hope that makes it clearer. Best regards, Thomas "Peter Hansen" wrote in message news:3d89b69d$1 at news.sentex.net... > Thomas Weholt wrote: > > Need a module to parse StructuredText/Wiki into HTML. Looked at PyWiki, but > > the generated code was not what I expected. Does anybody have module or lib > > to do this? > > Maybe you could help us by telling us *what* you expected. > Otherwise we're likely to waste our time making suggestions > that are just as inadequate from your point of view. > > (For example, ZWiki... or the Zope structured text stuff.) > > -Peter > From ouhfos at dwdddaae.com Wed Sep 4 21:17:41 2002 From: ouhfos at dwdddaae.com (ouhfos at dwdddaae.com) Date: Thu, 5 Sep 2002 01:17:41 +0000 (UTC) Subject: JA FOSTE HUMILHADO ??? 3910 Message-ID: <1031187856.681346@spynews5> >>>> http://burlasdoleo.cjb.net <<<< ACTIVISM - HELP STOP A CRIMINAL ENTERPRISE OF DESTROYING PEOPLE ACTIVISMO - AJUDE A PARAR UMA EMPRESA CRIMINOSA DE DESTROIR PESSOAS >>>> http://burlasdoleo.cjb.net <<<< mumk From ark at research.att.com Tue Sep 24 09:44:48 2002 From: ark at research.att.com (Andrew Koenig) Date: Tue, 24 Sep 2002 13:44:48 GMT Subject: confusion about opening files References: <3d8fcda4$0$198$75868355@news.frii.net> <3D8FCFF3.FD52AFE5@alcyone.com> <3d8fd215$0$192$75868355@news.frii.net> <3D8FD2F3.81F3831C@alcyone.com> Message-ID: Erik> Because there are two different open functions here. One is in the Erik> builtins, one is in the os module. They are not the same: In fact, the builtin "open" function is now called "file"; the name "open" is there only for backward compatibility. So the original example: >>> import os >>> file = os.open("e:\\d12", "r") is bad news for two reasons: 1) It uses os.open when it should use the builtin function; 2) It uses a variable named "file", which will step on the name of the builtin function. If you write it this way: # no need to import os here myfile = file("e:\\d12", "r") you may find the resulting code easier to understand. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From uwe.schmitt at procoders.net Wed Sep 11 05:42:28 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 11 Sep 2002 09:42:28 GMT Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> <6afb9d2c.0209091641.1d9b652e@posting.google.com> Message-ID: Steve Holden wrote: > "Uwe Schmitt" wrote in message > news:allofr$lgscc$2 at hades.rz.uni-sb.de... >> Naveed Iqbal wrote: >> > Thank you all for your help. I am really a novice when it comes to >> > python. Will someone tell me how to install the win32ui module in >> > windows? >> > thanka >> > naveed >> >> I suceeded without win32all: I generated a postscript file >> and copied it to the 'file' "prn:" using shutil.copyfile(). >> > Disk Operating System Rules OK! shurely :-) > Uwe: you'll clearly do well with such lateral thinking abilities. What > software did you use to generate the PS? I just found this solution because I was to lazy to read the win32all ducomentation .... At first I use pdflib to generate pdf-files (which can be stored, send by email..) and then used ghostscript to convert pdf to ps. The only "problem" I have, is that ghostscript opens a window, even if I use it from the commandline... Greetings, Uwe. -- Dr. rer. nat. Uwe Schmitt Computer science is no more about Computers, uwe.schmitt at procoders.net than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From bdelmee at advalvas._ZAPME_.be Mon Sep 2 15:59:57 2002 From: bdelmee at advalvas._ZAPME_.be (Bernard Delmée) Date: Mon, 2 Sep 2002 21:59:57 +0200 Subject: Why it is so dramatical? References: <200209021228.58453.b.maryniuk@forbis.lt> Message-ID: <3d73c295$0$30449$afc38c87@sisyphus.news.be.easynet.net> > > $b = ''; > > $data = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAA'; > > for $a (0..0xffffff) { > > $b += $data; > > } > That should result in a 1.3 GIGABYTE string. > Watching the perl-process i see that perl doesn't use more than 1MB. > So probably perl does some optimization for this in-fact meaningless code. Nothing that magic: '+' does not concatenate strings. You need to use '.' or '.=' for that. Otherwise $b keeps getting the numerical value 0 when perl wants to use it with the arithmetic '+' addition. From bobx at linuxmail.org Sat Sep 14 12:32:23 2002 From: bobx at linuxmail.org (Bob X) Date: Sat, 14 Sep 2002 16:32:23 GMT Subject: [FEEDBACK] Is this script efficient...is there a better way? References: <4ZRf9.1782$Lg2.248733@news2.news.adelphia.net> <3hSf9.168947$l_4.98525@atlpnn01.usenetserver.com> <8PSf9.1796$Lg2.257378@news2.news.adelphia.net> <_oUf9.170870$l_4.126599@atlpnn01.usenetserver.com> <3pkg9.3313$WV.2782@fe03> Message-ID: Just a quick test at home. On a 690K file the results were: RE based script: 0.11 Original script: 0.12 I ran it a couple times and they were always with 1 or 2 ticks of each other but the RE one was always the faster. I will try the same at work with the 30MB files to see if that makes a difference as well. From anandpillai6 at yahoo.com Wed Sep 25 11:02:49 2002 From: anandpillai6 at yahoo.com (Anand) Date: 25 Sep 2002 08:02:49 -0700 Subject: Pygame event problem Message-ID: <41c203e.0209250702.160102d@posting.google.com> Hi ! I wrote a simple image viewer in python using pygame image api. The GUI is in wxPython. There are 2 classes, one for the window frame and one for the pygame image processing. I added an effect in the pygame class which is called from a menu in the wxPython GUI. Here is the code of the GUI class which makes the call. def OnLiquidEffect(self, event): #imgview is of type MyPyGameImgViewer which is the pygame #class used to load the images. self.imgview.LiquidEffect() pass Here is the method which it calls on the MyPyGameImgViewer class. class MyPyGameImgViewer: ... ... ... def LiquidEffect(self): anim = 0.0 if self.imgfile is not None: self.ShowImage(self.imgfile) self.flag = 0 bitmap = pygame.Surface((self.h, self.w)) bitmap.blit(self.screen, (0, 0)) print self.h, self.w while 1: anim = anim + 0.4 for x in range(0, self.h, 20): for y in range(0, self.w, 20): xpos = (x + (sin(anim + x * .01) * 15)) + 20 ypos = (y + (sin(anim + y * .01) * 15)) + 20 self.screen.blit(bitmap, (x, y), (xpos, ypos, 20, 20)) #I think this code will remove all the #events from the queue once it detects #a mouse event. if pygame.event.peek([MOUSEBUTTONDOWN]): pygame.event.get([MOUSEBUTTONDOWN]) break pygame.display.flip() else: print "No image loaded!" The effect is stopped by clicking with the mouse on the pygame display window. My problem is that if I try to invoke any other menu methods in the main GUI frame *without doing this*, the application ie both the wxFrame and the pygame display window, hangs. I have a gut-feeling that this is because I am calling a method on the MyPyGameImgViewer class without exiting the while loop. Is there a way around this, ie to call any method in the MyPyGameImgViewer class from the GUI class, while one of its methods is executing a while loop ? Thanks Anand Pillai From emile at fenx.com Sun Sep 22 16:32:03 2002 From: emile at fenx.com (Emile van Sebille) Date: Sun, 22 Sep 2002 13:32:03 -0700 Subject: sys.ps2 assignment has no effect References: <3d8e0aae@news.sentex.net> Message-ID: Lance: > print '...' works correctly, showing ... I can't duplicate this on winxp with 2.1.3, 2.2.1 or current cvs. All behaves as it should. If you start an interpreter session, import sys, and check ord(sys.ps2[0]) you should get 46. Anything else might indicate modifications to pythonrun.c, where ps1 & 2 are initialized, or that the prompt is getting changed before you see it. Try starting python with -S (skips importing site) to see if that makes a difference. Also, what does set show? Watch out in particular for PYTHONSTARTUP that may also be a source of a change like this. HTH, -- Emile van Sebille emile at fenx.com --------- From cs26 at tecco.at Mon Sep 16 03:21:50 2002 From: cs26 at tecco.at (Chris) Date: 16 Sep 2002 00:21:50 -0700 Subject: concurrent programming References: Message-ID: Thank you for the advice, but I have the instruction to write it in C++, so this is a point I cannot change. Only for the scripts, Python should be used. Well, I know a little bit about how to do concurrent programming in Python, and in C++ too, but my problem is that I don't know how to combine these two technologies for the PARBEGIN, PAREND block. From pyth at devel.trillke.net Thu Sep 19 21:11:38 2002 From: pyth at devel.trillke.net (holger krekel) Date: Fri, 20 Sep 2002 03:11:38 +0200 Subject: Minimal debug/rep functionality In-Reply-To: ; from tdelaney@avaya.com on Fri, Sep 20, 2002 at 10:47:54AM +1000 References: Message-ID: <20020920031138.C30315@prim.han.de> Delaney, Timothy wrote: > > From: Peter Hansen [mailto:peter at engcorp.com] > > > > I'm a commercial Python user as well, so I can imagine the kinds of > > things your employer think about whether to release or not. We have > > As I said, I *expect* to be able to release (there's no commercial reason > not to, and we have done so with such things in the past). Maybe we are turning circles [1] but why don't you do it, then? Maybe you need to invest some time in obfuscating your source code and you don't want to do it? Why do you *expect* others to solve this problem for you? holger [1] Sounds like a circular argument which might get GCed, soon :-) From LogiplexSoftware at earthlink.net Fri Sep 20 06:49:39 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 20 Sep 2002 03:49:39 -0700 Subject: Larry Wall's comment on python... In-Reply-To: References: Message-ID: <1032518979.7312.8.camel@localhost.localdomain> On Wed, 2002-09-18 at 23:06, Matt Gerrans wrote: > One of the niftiest things about Python is you never have to argue about > whether you should put your curlies in the wrong place, like this: > > void foo() { > //... > } > > ...or whether you should place them correctly, like this: > > void foo() > { > //... > } > > It saves the world from a lot of unnecessary creation and release of hot air > (so Python has probably done more to help reduce the greenhouse effect than > any other software technology!). Now all that's left to decide is whether to use tabs or spaces for indentation... ;) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From blarson at crary.com Fri Sep 6 16:41:52 2002 From: blarson at crary.com (Bradley D. Larson) Date: Fri, 06 Sep 2002 15:41:52 -0500 Subject: Larry Wall's comment on python... References: <3D7958DB.50903@nospam.free.fr> Message-ID: <3D79130F.73ED4E51@crary.com> That is what is nice about Vi paren,bracket matching! > if (something == something_else) > { > } // if (something == something_else) > > As you can see, using comments to label my end blocks explicitly. For me > this issue was never an issue. -------------- next part -------------- A non-text attachment was scrubbed... Name: blarson.vcf Type: text/x-vcard Size: 400 bytes Desc: Card for Bradley D. Larson URL: From gua81 at XXXyahoo.com Tue Sep 24 20:08:22 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Wed, 25 Sep 2002 10:08:22 +1000 Subject: Strange python and cgi! Message-ID: Hi I made a cgi script in python and successfully compiled it. the script is some thing like this #! usr/lib.../python import ... def kickass(xxx) ... ... print "
"
kickass(xxx)
print "
... when I go to the webpage, it stops halfway and in "view source: it only show the code till the open "pre". however when I output it to an html file: python nameofscript.cgi >app.html .... app.html works fine just as I want it to be. What seems to be the problem here. I think i''ve done evrything right I've got that "Content-type" and also \n\n after that line. Thanks in advance From tjreedy at udel.edu Mon Sep 23 21:33:03 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Sep 2002 01:33:03 GMT Subject: e vs exp()? / financial applications References: Message-ID: "Andrew Thompson" wrote in message news:mailman.1032801271.6597.python-list at python.org... > One must be aware of the representational issues and accuracy of > arithmetic within a datatype when using numerical types. This is not so > much a Python issue as one of representing the real number line with > float types. ... > W=0.89 / 4 > 1+w+w+w+w > w+w+w+w+1 > > which are both *different* according to the == operator, but for the > purposes of numerical accuracy are identical. Since 'W' != 'w' in Python, both give a NameError unless w defined elsewise 8<). However... >>> w=.89/4 >>> w 0.2225 >>> 1+w+w+w+w 1.8899999999999997 >>> w+w+w+w+1 1.8900000000000001 Although w appears to be exactly represented, it must not be. Cute example. Terry J. Reedy From gerhard.haering at opus-gmbh.net Fri Sep 20 13:36:21 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 20 Sep 2002 17:36:21 GMT Subject: Local Python Server Installation References: <3d8b47c6.277669@news.jaring.my> Message-ID: In article <3d8b47c6.277669 at news.jaring.my>, Kenneth Gomez wrote: > Dear Group, > > I would like to know wich software to install if I would like to learn > to use Python as a web development tool? > > I have installed Python 2.2.1 and Apache but I belive I would need a > Python Server Program to enable Apache to render .py files, am I > right? > > Could you kindly advise me? Add this line at the end of your .../Apache Group/Apache2/conf/httpd.conf: ScriptInterpreterSource Registry Then you can write Python CGI scripts that have the .py extension. I recommend to create a test.py script with the following two lines: import cgi cgi.test() After you verify that this works (http://localhost/cgi-bin/test.py) you can continue reading the documentation about the cgi module and writing your own CGI scripts. The cgitb and Cookie modules should come in useful, too. If you experience the limits of CGI one day, you can think about using a full-blown appliation server like WebWare. -- Gerhard From gstaniak at inka.zagiel.pl Fri Sep 6 08:45:57 2002 From: gstaniak at inka.zagiel.pl (Grzegorz Staniak) Date: Fri, 6 Sep 2002 12:45:57 +0000 (UTC) Subject: Access to shadow passwords? Message-ID: Hi all, I didn't succeed in finding a Python interface to the /etc/shadow system database - is anybody aware of a class/module that would allow me to check account/password expiry dates etc.? I'm a Python beginner, but I think there's no such thing in the standard library. I'll appreciate your help. Thanks, -- Grzegorz Staniak From shalehperry at attbi.com Wed Sep 11 12:10:44 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 11 Sep 2002 09:10:44 -0700 Subject: deleting the first and the last character of a string In-Reply-To: References: <20020911105818.GC2054@partagas.as.de.cw.net> Message-ID: <200209110910.44314.shalehperry@attbi.com> On Wednesday 11 September 2002 09:03, Duncan Booth wrote: > > This doesn't work on Python 2.2.1 (or earlier), I think you need to be > sitting astride the cutting edge of CVS development to do this. > > Specifically the change to implement this was April 22nd and 2.2.1 was > released April 10th. hmm, the 2.2.1 in Debian must have been updated then. How annoying. Thanks. Python 2.2.1 (#2, Aug 30 2002, 10:27:17) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 From maxm at mxm.dk Fri Sep 6 09:24:30 2002 From: maxm at mxm.dk (Max M) Date: Fri, 06 Sep 2002 15:24:30 +0200 Subject: tree data structure References: Message-ID: <3D78AC8E.4040900@mxm.dk> Raymond Hettinger wrote: >>>>tree = {} >>>>for key, value in original: >>> >>> tree.setdefault(key,[]).append(value) That is a darn nice way to do it, even though it's a bit more readable to:: for key, value in original: if map.has_key(key): map[key].append(value) else: map[key] = [value] I just hate to see something I have done a lot of times in four line boiled down to one... :-) I knew the setdefault() method, but would probably never have thought of using it like that on my own. regards Max M From shalehperry at attbi.com Tue Sep 17 03:30:52 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Tue, 17 Sep 2002 00:30:52 -0700 Subject: problems getting a single item out of a list In-Reply-To: <20020917071900.GB23629@partagas.as.de.cw.net> References: <20020917071900.GB23629@partagas.as.de.cw.net> Message-ID: <200209170030.52964.shalehperry@attbi.com> On Tuesday 17 September 2002 00:19, Manuel Hendel wrote: > I try to get a single item out of a list, but after this, the single > item is stil a list item. > > domainfield = fields[3:4] > > I just want to get a new variable with a the value of the 3rd item of > the list fields. > > Can anyone help? > > Thanks, > Manuel just use fields[2] (you start counting at zero). From max at alcyone.com Mon Sep 2 23:40:56 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 02 Sep 2002 20:40:56 -0700 Subject: what about things like __*** ? References: <7153651c.0209021927.16a3efaf@posting.google.com> Message-ID: <3D742F48.9267B5B7@alcyone.com> black wrote: > That is I couldnt figure out what __*** is. Here is the description of > that article but even confused me: > > There is limited support for class-private identifiers. Any identifier > of the form __spam (at least two leading underscores, at most one > trailing underscore) is now textually replaced with _classname__spam, > where classname is the current class name with leading underscore(s) > stripped. > > What's it trying to say please ??? The best way of finding out these kinds of things is playing with the interactive interpreter: max at oxygen:~% python Python 2.2 (#1, Feb 6 2002, 19:31:45) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class C: ... def __init__(self): ... self.__x = 1 ... >>> c = C() >>> dir(c) ['_C__x', '__doc__', '__init__', '__module__'] >>> c.__x Traceback (most recent call last): File "", line 1, in ? AttributeError: C instance has no attribute '__x' When you create an attribute beginning with two underscores (and not ending with two more underscores!), Python mangles the name and replaces it with an encoding of the class name. This is intended to obscure the name so that in effect it acts as a private variable. It doesn't prevent malicious people from accessing the attribute in its mangled form, it just prevents accidental accesses. There is also a fairly common but unenforced convention that identifiers starting with a single underscore are reserved and shouldn't be used externally. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From syver-en+usenet at online.no Mon Sep 16 12:38:34 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Mon, 16 Sep 2002 16:38:34 GMT Subject: pyro & parallel processing References: Message-ID: Robin Becker writes: > Has anyone used pyro to do symmetric parallel processing. The pyro > framework is nice with master slave type applications, but the remote > objects don't seem to be able to message back to their invoker. They can, checkout the callback examples in the Pyro distro. Basically what happens is that you pass a Pyro proxy as a parameter to the a method on the Pyro object. > > I thought I'd ask if any one has got pyro to work in a more symmetric > way? > -- > Robin Becker -- Vennlig hilsen Syver Enstad From wyojustin at hotmail.com Tue Sep 17 22:36:15 2002 From: wyojustin at hotmail.com (Justin Shaw) Date: Wed, 18 Sep 2002 02:36:15 GMT Subject: can wxpython do this? References: <737aefee.0209151702.3f735252@posting.google.com> <20929D5514805227.48A29064FC554044.5053D887939EB774@lp.airnews.net> Message-ID: > You might start with > from urllib import urlopen > > URL = "http://www.python.org" > page = urlopen(URL).read() Then use wxHtmlWindow to display it. Justin From jwbaxter at spamcop.net Mon Sep 23 19:36:47 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Mon, 23 Sep 2002 16:36:47 -0700 Subject: Elementary confusion References: <878z1s1kqf.fsf@smtp.blueyonder.co.uk> Message-ID: In article <878z1s1kqf.fsf at smtp.blueyonder.co.uk>, Keith wrote: > Hi, > > I am working through O'Reilly's "Learning Python". I am up to page 33, > and already I have a problem. The text outlines a cli entry about math > operators, all really straight forward; > > .>>>a=3 > .>>>b=4 > .>>>b/2+a > 5 > .>>>b/(2.0+a) > 0.8 > > This is so straight forward that I wasn't going to type it in, but I > did anyway, and got instead of '0.8' something I cannot account for. I > got '0.80000000000000004'. > > So after 32 pages, I am already flumoxed. What is going on In fact, the example is far from straight forward...it (now) exemplifies the fact that your computer can't represent 0.8 exactly in binary floating point, which Python uses for values like 0.8. It comes close (supposedly as close as possible). It's not a question of precision...double (or far more than double) the number of bits involved, and 0.8 still can't be represented exactly. The 0.80000000000000004 is as close as your hardware can come (or it isn't as close as your hardware can come, and there are issues with the libraries or the chip). Learning Python describes an older Python in which the interpreter lied about the value by rounding it to 0.8; the interpreter no longer does that, so you learn sooner about that problem. You will encounter this issue over and over...for example on my machine: $python Python 2.2 (#1, 07/14/02, 23:25:09) [GCC Apple cpp-precomp 6.14] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a=0.1 >>> b=0.2 >>> c=a+b >>> c==0.3 0 >>> c 0.30000000000000004 >>> d=0.3 >>> d 0.29999999999999999 >>> We "know" that c is 0.3. The computer has added two inexact values which are "too big" and produced a result which is therefore both "too big" and not the nearest representation of 0.3, which is "too small". --John From richie at entrian.com Fri Sep 20 10:31:40 2002 From: richie at entrian.com (Richie Hindle) Date: 20 Sep 2002 07:31:40 -0700 Subject: Minimal debug/rep functionality References: Message-ID: <8a6ba1da.0209200631.6f6e72bd@posting.google.com> Tim, > Having been writing a fairly comprehensive code and path coverage tool > (incomplete - currently working on determining what *is* an executable line > ... think I need to work with the AST) I've done this recently as well, and I'm now on my third iteration of the work-out-which-lines-are-executable code (!) The first version used the AST, but there are several holes in that - 'else' lines, for instance, are identified by the parser as executable lines, but the trace function doesn't always get called for them. I then wrote a system that found all the SET_LINENO instructions, and that gave perfect results (as long as you weren't using -O) but then I found out that SET_LINENO is going away in Python 2.3... My current system (which I think works 8-) uses co_lnotab, which is a delightful data structure that describes the relationship between bytecodes and line numbers. Here's the relevant piece of code, which builds in 'lineNumbers' a list of the execuable line number in the code object 'code': # Derive the line numbers from co_lnotab; that's a list of pairs of # increments, one for the bytecode address and one for the line # number (see compile.c in the Python sources). lineNumbers = [] lnotab = code.co_lnotab previousAddress = -1 previousLineNo = -1 lineNo = code.co_firstlineno byteCodeAddress = 0 for i in range( 0, len( lnotab ), 2 ): byteCodeAddress = byteCodeAddress + ord( lnotab[ i ] ) lineNo = lineNo + ord( lnotab[ i+1 ] ) # When the compiler wants to increment the line number by more # than 255 in one go, it increments it by 255 as many times as it # needs and then the remainder. Fair enough, but there's a bug # whereby the byte code address gets incremented along # with the *first* 255, not the last. Hence you get a line that # claims to have code on it when in fact it doesn't. We detect # that here. if byteCodeAddress != previousAddress and not \ ( lineNo - previousLineNo == 255 and len( lnotab ) > i+2 and ord( lnotab[ i+2 ] ) == 0 ): lineNumbers.append( lineNo ) previousAddress = byteCodeAddress previousLineNo = lineNo Hope that helps. The coverage tool that this belongs to is finished but unreleased (mostly because of lack of thorough testing, but I'm using it myself with no problems) - if you'd like a copy, drop me an email. -- Richie Hindle richie at entrian.com From cliechti at gmx.net Sun Sep 29 18:55:58 2002 From: cliechti at gmx.net (Chris Liechti) Date: 30 Sep 2002 00:55:58 +0200 Subject: tkinter & serial port References: Message-ID: user at domain.invalid wrote in news:IhKl9.45766$bX.8904 at sccrnsc02: > I'm new with Python/Tkinter, but have written LOTS of X windows code. > This may be the root of my problem. > > My program needs to talk over a serial port to a device AND update > the display. ... > How do I do this or its moral equivalent under Python so that it > runs without modification under both BSD and Windows? you can hook in an "idle function" in most gui toolkits. that function could poll the serial port then. (select is out of question on wiondowze anyway) i do prefer threads: start a worker thread that handled the serial IO and the main thread serves the GUI. that's the module "threading" and search for aahz page and the threding intro. (url found on all his messages' sig) adv: for an easy serial port handling on both platforms i can sugest my lib: http://pyserial.sf.net. chris -- Chris From marklists at mceahern.com Mon Sep 23 22:11:39 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 23 Sep 2002 21:11:39 -0500 Subject: Three dumb questions (ordered by dumbness descending) In-Reply-To: Message-ID: [Steven Feil] > Humm, what is is zip()[...] Steven, meet zip. $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> print zip.__doc__ 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. >>> l = range(10) >>> zip(l, l) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)] >>> d = dict(zip(l, l)) >>> d {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9} >>> Neato, huh? Cheers, // m - From gerhard.haering at gmx.de Tue Sep 17 03:41:07 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 17 Sep 2002 07:41:07 GMT Subject: pypgsql -- not preserving transactions ? References: Message-ID: Frank Miles wrote in comp.lang.python: > Gerhard H?ring wrote: >>* Frank Miles [2002-09-16 03:15 +0000]: >>> I've discovered that the 2.0 version of pyPgSQL packaged with Debian/woody >>> doesn't preserve transactions... > [snip] > >>I can't reproduce that behaviour here. What do you do to ignore the >>PgSQL.OperationalError? Or is it a different exception that gets thrown? > > Yes, that exception gets thrown. Perhaps this simply reveals a gap in my > understanding -- I thought that it was Postgres that was handling the > transactions. Yeah, but pyPgSQL keeps track of wether we're in a transaction > Presuming that the cursor wasn't starting a new transaction, Ignoring the autocommit behaviour that's off by default: In reality, the first cursor in a connection will automatically start a new transaction. So do all other methods on the cursor object, if there is no open transaction. > even if the dumb user used a try/except block to bypass the exception (and > continue with succeeding INSERT attempts), shouldn't Postgres prevent those > later INSERTs? An implicit rollback will be issued in case of an OperationalError. The next cursor.execute() will open a new transaction, because there is no open transaction now, which leads to the behaviour you describe. >>This area of code hasn't changed up to 2.2, IIRC. Could you provide >>a test case [...] > Sure, I've got some simple test code. But at this point I'm now > thinking that this is more likely a difference in conception -- what > _should_ pypgsql do? As far as I see, the current behaviour is what it should do. > Should the application have to track if/when exceptions occur? It's > probably more efficient, though ISTM less clean to do it this way. The problem as far as I can see is that you're using code like: for item in data: try: cursor.execute("INSERT INTO ...") except OperationalError: pass # better log error here conn.commit() which leads to the behaviour I described above. If you want either all or none of the inserts to succeed, you should use code like this instead: try: for item in data: cursor.execute("INSERT INTO ...") conn.commit() except OperationalError: pass # better log error here > Thanks for your reply, Gerhard. Can you (or someone else) confirm > that the "error" is a difference in conception? Looks like so. -- Gerhard From webagency at simail.it Tue Sep 3 08:38:33 2002 From: webagency at simail.it (Servizi Internet) Date: Tue, 3 Sep 2002 14:38:33 +0200 Subject: Servizi Internet Message-ID: Salve. Sono il titolare di "Web Ceating.it", una delle web agency piu' in vista sul mercato europeo. Volevamo informarLa che la nostra azienda si mette a Sua completa disposizione per qualsiasi esigenza o servizio Lei desideri. Ci occupiamo principalmente di: * Servizio Hosting e registrazione domini .com/.net/.org/.biz/.it; * Registrazione nei principali motori di ricerca; * Posizionamento garantito in testa ai motori di ricerca; * Creazione Siti Personali e Aziendali; * Consulenza Web Marketing; * Realizzazione Grafica; * Realizzazione di siti E-Commerce; * Virtual Store; * Banner e Loghi Aziendali; * Creazione di pagine HTML, ASP e FLASH; * Creazione di Database per il Web; * Manutenzione e gestione dei siti creati; * Manutenzione e gestione di altri siti; * Registrazione del Dominio .it .com .org .net; * E-mail Target Advertise; Per qualsiasi Sua esigenza o informazione La preghiamo di contattarci compilando il form all'URL: http://www.webcreating.it/contatti.htm I nostri consulenti saranno a Sua completa disposizione! L'URL aziendale e': http://www.webcreating.it _____________________________________________________________ L'87% degli utenti in internet utilizzano i motori di ricerca per trovare i siti che vogliono! Special Submitt Professional e' un servizio da noi elaborato che permette di effettuare l' inserimento mirato su 500 e piu' motori di ricerca e portali nazionali ed internazionali come: MSN - VIRGILIO - GOOGLE! - LYCOS - YAHOO - LOOKSMART - GOTO ecc.ecc. * PERCHE' ASPETTARE? In meno di tre giorni avverra' la sottoscrizione in piu' di 500 motori di ricerca. * IL TEMPO E' DANARO! Noi facciamo il lavoro per te! Basta passare notti in bianco per poi non essere certi di vedere il proprio sito ben posizionato e correttamente registrato sui principali motori di ricerca. * REPORT! Periodicamente invieremo dei report e ti terremo aggiornato su quello che succede sul tuo sito. * SUPPORTO TECNICO! Potrai sempre contare su di un supporto tecnico esperto nel settore e potrai porre tutte le tue domande. E allora che aspetti? vai su http://www.webcreating.it/special_submitt.htm e approfitta di questa vantaggiosa offerta. Scusandoci per l'invadenza speriamo aver fatto cosa gradita e cordialmente salutiamo. ________________________________________________________________ Questo messaggio non ? spam ma un semplice messaggio informativo che non verr? ripetuto.La ringraziamo della Sua cortese attenzione. Nel rispetto della Sua privacy e' doveroso comunicarLe che il tuo indirizzo e-mail ? presente su internet e nel nostro archivio e non verr? mai ceduto a terzi per nessun motivo. ________________________________________________________________ Web Creating.it - Soluzioni internet per le aziende. python-list at python.org www.python.it/faq/faq-1.html From aleax at aleax.it Fri Sep 20 14:56:30 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 18:56:30 GMT Subject: Copy with __slots__ References: Message-ID: Antonio Cuni wrote: > Alex Martelli wrote: > >> This doesn't deal with inherited __slots__. > [cut] > > you're right, I couldn't think of it :-( > >> Some care >> is needed, though (I can think of several possible anomalies). > > what kind of anomalies? For example, slots with the same name might be present in more than one base, but it would be better to only copy them once. Alex From tim.one at comcast.net Mon Sep 9 14:22:49 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 09 Sep 2002 14:22:49 -0400 Subject: Can't exponentiate zero in NumPy In-Reply-To: Message-ID: [Rick Muller] > Turns out it appears to be a more general problem than I thought. > > 1e-310 ** 2 > > Works on RH linux/1.5.2, overflows on RH linux 2.2 > > pow(1e-310, 2) > > Works on linux 1.5.2, overflows on linux 2.2 > > import math > math.pow(1e-310, 2) > > Works on linux 1.5.2, works on linux 2.2 (??!) > > 1e-310 ** 2.1 > > Works on linux 1.5.2, fails on linux 2.2 > > pow(1e-310, 2.1) > > Works on linux 1.5.2, fails on linux 2.2 > > math.pow(1e-310, 2.1) > > Works on linux 1.5.2, works on linux 2.2 > > In addition, exactly which version of Python are you using > (2.0, 2.1, 2.1.1, > > 2.1.2, 2.1.3, 2.2, 2.2.1, ...)? > > These are the standard python/python2 distributed with RedHat Linux 7.3. > > "Works" means returns 0.0 > "Fails" means raises an OverflowError > > Can someone suggest a decent workaround? Upgrade to Python 2.2.1, or downgrade to an older version of glibc. glibc changed its errno behavior in a way that nobody noticed before 2.2 final was released. While I've never seen the problem myself, I fixed it , and many people reported that this class of problem is indeed fixed in 2.2.1 without backing off to an older version of glibc. From jubafre at brturbo.com Mon Sep 16 13:41:12 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Mon, 16 Sep 2002 14:41:12 -0300 (GMT-03:00) Subject: search re and put in a list?? Message-ID: <-763904540.1032198072820.JavaMail.nobody@webmail1> i have 3 lists: mem=['7','8', '9'] labels['D1','D2','D3'] S=['20 D1', '30 D2', '10 D3', 'F0', ' 3', ' 2', ' 0'] I want to put mem in s trougth of labels. #+++++++++++++++++++++++++++++++++++++++++++++ final=[] for i in range(len(j)): for c in range(len(s)): p= re.compile(labels[i]) t1=p.search(s[c]) if t1: t=sub(p, j[i], s[c].strip()) final.append(t) print final #+++++++++++++++++++++++++++++++++++++++++++++ but doing like this i have just de nodes replaced, ['20 7', '30 8', '10 9'] and i want the replaced and the not replaced in order like this: ['20 7', '30 8', '10 9', 'F0', ' 3', ' 2', ' 0'] Juliano Freitas www.gebrasil.hpg.com.br From duncan at NOSPAMrcp.co.uk Fri Sep 13 06:38:59 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Fri, 13 Sep 2002 10:38:59 +0000 (UTC) Subject: wrapping yield ? References: Message-ID: "Michael Sparks" wrote in news:alsdpt$2nq$1 at nntp0.reith.bbc.co.uk: > Whereas if I could wrap up yield, I simply have to do: > > item = waitForSomethingCheckingPeriodically() > process(item) > > Which if I have lots of this sort of thing going on, results in much > clearer (and hence maintainable) code. > > If it can't (putting yield in a function, and not turning the function > into a > generator) be done, and AFAICT it can't, and this is a suggested work > around - many thanks :-) The syntax wouldn't look quite so bad if your function wasn't returning a value. At present 'for x in gen(): yield x' is the only way to nest generators, but there were discussions here recently suggesting a new syntactic sugar: yield every gen() as an equivalent for the for loop. There definitely isn't any way to put a yield in a function and not have it turn into a generator. When you yield from a generator, only a single frame is saved, not a stack, so you can only yield from the outer loop. By yielding at each level you effectively simulate the stack since each frame chains to the others. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From strat_addict at yahoo.com Tue Sep 24 16:33:56 2002 From: strat_addict at yahoo.com (strat_addict) Date: 24 Sep 2002 13:33:56 -0700 Subject: COM, Word problem References: Message-ID: "Emile van Sebille" wrote in message news:... > strat_addict: > > com_error: (-2147417846, 'The message filter indicated that the > > application is busy.', None, None) > > Google is your friend... perhaps this helps: > > http://groups.google.com/groups?selm=MPG.13553ec91f8cb3b98968e%40192.168 > .0.28 Thanks Emile, I never would have guessed to think it was my antivirus software. Thanks again, Glenn (strat addict) From NineOfSix at gmx.de Mon Sep 2 03:43:52 2002 From: NineOfSix at gmx.de (Axel Grune) Date: Mon, 02 Sep 2002 09:43:52 +0200 Subject: ascii value References: Message-ID: A sorry, I missed ord(), shoot me Axel From ark at research.att.com Fri Sep 20 15:07:16 2002 From: ark at research.att.com (Andrew Koenig) Date: Fri, 20 Sep 2002 19:07:16 GMT Subject: Python 2.2.1 compatible with Tcl/Tk 8.4? Message-ID: Now that Tcl/Tk 8.4 is out, can anyone tell me whether Python 2.2.1 will work with it? Or should I wait for 2.3? -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From freddie at madcowdisease.org Sat Sep 14 13:44:58 2002 From: freddie at madcowdisease.org (Freddie) Date: Sat, 14 Sep 2002 17:44:58 GMT Subject: Argh! Python 2.2 + threading + sockets = trouble References: Message-ID: Sandy Norton wrote: > A more precise description of your problem will often help others help > you; more specifically, stating that an app 'just stops working' is > not a great problem description. > > Localize the problem and someone may be able to point you in the right > direction. > > cia, > > Sandy I would if I could, but I don't know HOW to localize the problem. If I put a 'print alive!' statement in the main cowbounce loop, it prints alive! for a while, but it will stop when a random client manges to connect to a server. Ctrl-C stops working, and the server stops spawning a new thread to handle an incoming connection. This is after the connect() call in BounceClient succeeds. Other times, runnings threads (already connected to a server) will just stop passing data back and forth. The Python profiler is useless in a threaded application, and Linux doesn't have ktrace. MadCowOffer starts a thread for each 'task'. IRC, database, transfer queues, admin interface, etc. If I unroll the map(lambda x: x.start(), self.__Threads) loop, it goes something like this: Starting PackMan Starting HeadHoncho Starting Chatterbox Then it becomes unresponsive. Ctrl-C won't kill the process, I have to terminate it with kill. The problem is, the exact same code runs PERFECTLY FINE in Python 2.1.x. This is what has me stumped :( If you need any more info, feel free to contact me. Freddie From gerhard.haering at gmx.de Sat Sep 14 21:45:27 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sun, 15 Sep 2002 03:45:27 +0200 Subject: python + java for web development? In-Reply-To: References: Message-ID: <20020915014527.GA7233@lilith.ghaering.test> * eugene kim [2002-09-15 08:36 +0000]: > [...] since java passes objects , not just strings among servlets and > jsps i'm wondering if it is possible to mix java and other language.. Did you check out Jython, yet? http://www.jython.org/ Jython is an alternative Python implementation that runs on a Java Virtual Machine. Consequently, you can call Java class libraries from Jython, and the other way round. > how python can interact with these servlet/jsp..? Jython can be used to write servlets and with some determination, you can even use it as a language for JSPs [1]. Of course, CPython is very well suited for web development, too. I'd even prefer it, since you don't have to touch Java, then ;-) -- Gerhard [1] That's a little hard, though, it involves using BSF and some tag library from the Jakarta project, plus patching BSF to use Jython instead of JPython, Jython's predecessor). From dhein at acm.org Fri Sep 20 19:49:36 2002 From: dhein at acm.org (Coot) Date: 20 Sep 2002 16:49:36 -0700 Subject: Popup menu won't hide on Linux References: Message-ID: dhein at acm.org (Coot) wrote in message news:... > When a popup menu is displayed, I expect that it should goes away when > one of the menu items is clicked (button <1>) or when I click anywhere > else (such that the focus is no longer on the popup menu). > > However, on Linux, the latter behavior doesn't happen. The popup > remains on top of the main app window and the only way to get rid of > it is to click one of its menu command items or close the application. > > This behavior isn't there on Windows. > > Can anyone tell me how to solve, or work around, the problem??? > > Here is some example code you can use to demonstrate this problem for > yourself (taken from > http://www.pythonware.com/library/tkinter/introduction/x5819-patterns.htm): > > # menu-example-4.py > > from Tkinter import * > > root = Tk() > > def hello(): > print "hello!" > > # create a popup menu > menu = Menu(root, tearoff=0) > menu.add_command(label="Undo", command=hello) > menu.add_command(label="Redo", command=hello) > > # create a canvas > frame = Frame(root, width=512, height=512) > frame.pack() > > def popup(event): > menu.post(event.x_root, event.y_root) > > # attach popup to canvas > frame.bind("", popup) > > mainloop() OK, on Linux I have to watch for a event and "unpost" when that event fires. If I do that and click outside the window, then the popup disappears. Here is the new code: from Tkinter import * root = Tk() def hello(): print "hello!" def popup(event): menu.post(event.x_root, event.y_root) menu.focus_set() def popupFocusOut(self,event=None): menu.unpost() # create a canvas frame = Frame(root, width=512, height=512) frame.pack() # create a popup menu menu = Menu(frame, tearoff=0) menu.add_command(label="Undo", command=hello) menu.add_command(label="Redo", command=hello) menu.bind("",popupFocusOut) # attach popup to canvas frame.bind("", popup) mainloop() From gerhard.haering at gmx.de Sun Sep 1 21:18:18 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 2 Sep 2002 01:18:18 GMT Subject: Keyerror problem References: <_lyc9.7164$7N.29584@newsfep3-gui.server.ntli.net> Message-ID: davbucko wrote in comp.lang.python: > I have a class Flags as follows: > > class Flags: > def __init__(self): > self.flags = {} > > def getInverseFlags(self): > for i in self.flags.keys(): > #switch some keys/values around > > def setFlag(self,name,value): > self.flags[`name`] = value ^^^^^^ Here's the bug. It should read: self.flags[name] = value. `name` calls repr on name, which is most likely not what you want. Btw. if you want to invert a dictionary, there are probably hundreds of examples out there, here's a hopefully readable one: def invertdict(orig): new = {} for k, v in orig.items(): new[v] = k return new Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From sandorlevi at yahoo.com Fri Sep 6 19:50:51 2002 From: sandorlevi at yahoo.com (Levente Sandor) Date: 6 Sep 2002 16:50:51 -0700 Subject: Access to shadow passwords? References: Message-ID: <8b5e42a6.0209061550.1e786b7d@posting.google.com> Just take a look at the pwd module. levi Grzegorz Staniak wrote in message news:... [...] > I didn't succeed in finding a Python interface to the /etc/shadow system > database [...] From lu_gio at hotmail.com Thu Sep 26 18:37:11 2002 From: lu_gio at hotmail.com (Max) Date: Thu, 26 Sep 2002 22:37:11 GMT Subject: pygame.event.Event? Message-ID: Hi! I can't generate a QUIT event in pygame: pygame.event.Event(type, dict, [keyword_args]) -> Event What do I have to put in "dict"? From skip at pobox.com Thu Sep 5 16:24:00 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 5 Sep 2002 15:24:00 -0500 Subject: Why Python? In-Reply-To: References: <4f49d232.0209050418.7668c21@posting.google.com> <3D77FB95.3070300@nospam.free.fr> Message-ID: <15735.48480.165861.793285@12-248-11-90.client.attbi.com> Roy> I wrote: >>> If you're learning languages to study computer >>> science, lisp is looking a lot better. Roy> laotseu wrote: >> I think once you know them both, you know *how* to program, whatever >> the language you have to use. Roy> I believe we actually both said the same thing, just worded Roy> differently :-) Alas, to even get to a phone screen these days, it appears you need "at least five years experience" with a buzzword language on your resume. In most cases, neither Lisp nor Python qualify. -- Skip Montanaro skip at pobox.com From ckasso at sprynet.com Tue Sep 24 21:57:22 2002 From: ckasso at sprynet.com (Chris Kassopulo) Date: Tue, 24 Sep 2002 21:57:22 -0400 Subject: hex numbers?? References: Message-ID: <20020924215722.78b60f64.ckasso@sprynet.com> On Tue, 24 Sep 2002 12:30:48 -0300 (GMT-03:00) jubafre at brturbo.com wrote: > > x = [12,13,14] > y = ['0xc', '0xd', '0xe'] > > hex() create a list of string, how i can write in a file just the > real value of hexadecimal number? > x = [12,13,14] y = [] for char in x: y.append(str(hex(char)).replace ('0x','',1)) print y ['c', 'd', 'e'] Chris Kassopulo From sludtke at bcm.tmc.edu Mon Sep 30 13:11:09 2002 From: sludtke at bcm.tmc.edu (Steve Ludtke) Date: Mon, 30 Sep 2002 12:11:09 -0500 Subject: XMLRPC calls don't work in threads, or rather, they don't play well with others ! (help) References: <3D97D190.9030003@bcm.tmc.edu> Message-ID: <3D9885AD.2030603@bcm.tmc.edu> Martin v. Loewis wrote: > Steve Ludtke writes: > > >>Hi. I've been trying to write a python app that makes somewhat >>time-consuming XMLRPC calls. I planned to have several calls going at >>once using threads, but it seems like something in the XMLRPC client >>code isn't releasing the python interpreter lock properly. > > > This is unlikely. xmlrpclib does not use threads. I don't know what > xmlrpclib_auth is, so all bets are off. > > If it doesn't use any threading facilities, either, blocking calls > will occur eventually only in the socket read/write calls, which do > allow other threads to run, and do release the interpreter lock > properly. xmlrpclib_auth just adds a couple of header entries, and calls xmlrpclib. No actual functionality changes. What you describe is what I'd expect, but not what I get. >>Is there something I can do at the Python level to deal with this >>issue ? > > > I'd add print statements at all levels of the code, to see where > exactly it is blocking. Already did this. It definitely seems to be the xmlrpclib calls that are preventing the thread switching. I'll have to see if I can come up with a simple demonstration script to show the problem. From tismer at tismer.com Thu Sep 19 09:08:07 2002 From: tismer at tismer.com (Christian Tismer) Date: Thu, 19 Sep 2002 15:08:07 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: <3D89CC37.5080209@tismer.com> Thomas Heller wrote: > Martin v. Loewis wrote: > >> Greg Ewing writes: >> >> >>> So, the only way to find out whether a particular >>> extension is safe to use in Stackless is to try >>> it. >> >> >> >> That is not true. It is more reliable to inspect the source code. >> >> In general, it is very easy to do so: if there are no callbacks to >> Python, the module is stackless-safe. > > > So win32all probably wxPython are incompatible with stackless? PythonWin has a problem when locking Scintilla for printing, and a tasklet prints then, too. I will prohibit this by some magic which is already designed: I don't allow switching for modules which are not registered. (registrry to be done) wxPython: Nooooo, it works like a charm! I have a commercial application which runs multiple tasks in wxPython. There are some small imcompatibilities which I will discuss with the wxPython developers. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From nospam at bigfoot.com Fri Sep 6 19:39:11 2002 From: nospam at bigfoot.com (Gillou) Date: Sat, 7 Sep 2002 01:39:11 +0200 Subject: Larry Wall's comment on python... References: Message-ID: "Rod Stephenson" a ?crit dans le message de news: wkr8g7rn4c.fsf at yahoo.com... > Slashdot has a list of questions posed to Larry Wall (perl). When > asked his thoughts on other scripting languages, he makes the > following observation about python > > "Python is cool to look at small bits of, but I think the "outline" > syntax breaks down with larger chunks of code. I'm with Aristotle on > the structure of discourse--a story should have a beginning, and > middle, and an end. So should blocks" > > I'm not quite sure what he's trying to get at here - I guess that for > a long heavily indented chunk of code, you could lose track of the > overall structure, but I don't write code this way. > > Any comments? Long heavily indented chunks of code is a really bad programming style (whatever's the language). Modern python editors can find blocks, hide/show blocks, auto indent/dedent blocks, and find start/end of blocks. Tabnanny does a fine job on ugly indenting. def longfunction(): # 300 lines of code below ... return # end longFunction() From DennisR at dair.com Tue Sep 17 16:33:48 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Tue, 17 Sep 2002 20:33:48 GMT Subject: Source code References: Message-ID: > If I would like to write some code that would not be possible for others to > read, after I distribute the program, would Python be suitable? I am working on an unreleased system that may work out for you. I have an http (web) server distributed as a single AutoRunning EXE which serves CGI from memory. That CGI can be Python scripts and the GUI interface would be a web browser. See sample at http://www.dair.com/hellopy.zip Right now, I have not documented this. Import libraries are copied to a temp directory and erased when the browser is dismissed. Http pages are weakly encrypted in memory and only the current active page is decrypted. If the protection standard is "would not be possible for others to read" then it may well be that no finite protection scheme is adequate. The protection outlined is adequate for some casual attacks (e.g. dumping the exe). It is not adequate against a determined, knowledgeable attack. What is your time frame here? I am looking for an early October 2002 first release. Beta testers welcome (write me at email below) -- Dennis Reinhardt DennisR at dair.com http://www.dair.com From tim.one at comcast.net Sun Sep 22 14:45:34 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 22 Sep 2002 14:45:34 -0400 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? In-Reply-To: <3D8D3491.8010803@tismer.com> Message-ID: [Christian Tismer] > There is no reason to argue about that. > Decimal arithmetic is exact for most of the operations > bankers require. They have been demanding for it since > decades, and they will not drop it. Having "no rounding > issue at all" is better than any consideration about > neglectible errors, it cannot be beaten, since *they* > understand it. > Cannot be discussed. They pay the bill. Bless you, Christian! That's all the truth. It reminds me of my first job in this business, where after a few months my boss took me aside and reminded me that I was hired to be a prostitute, not a missionary . otoh-the-bankers-need-stackless-but-just-don't-know-it-yet-ly y'rs - tim From skip at pobox.com Thu Sep 12 13:59:32 2002 From: skip at pobox.com (Skip Montanaro) Date: Thu, 12 Sep 2002 12:59:32 -0500 Subject: Coding Style: Quotes In-Reply-To: References: Message-ID: <15744.54788.570744.899923@12-248-11-90.client.attbi.com> John> I'm curious if others have adopted any standards for choice of John> single vs. double quotation marks to delimit strings. A look John> through the standard library reveals the choice of one over the John> other is rather arbitrary. I suspect it really makes no John> difference, but the question has come up during a code review. In situations where it doesn't matter (one or the other of the quotes embedded in the string) I sort of half-heartedly pretend I'm programming in C. Single-character strings are single-quoted while multi-character strings are double-quoted. It really makes no sense to do it this way, and I'm not very consistent about it. It's just a carryover from C. Your code reviewers might appreciate the consistency if they have a C/C++/Java background. For multi-line strings I use triple quotes. (Again, the choice of style is a bit arbitrary.) Generally I use """ because long chunks of English text frequently contain contractions. For long strings which don't contain newlines (like embedded SQL statements) I tend to enclose multiple "-quoted literals in parens of some sort, like so: rows = self.executesql("select cities.city, state, country" " from cities, venues, events, addresses" " where cities.city like %s" " and events.active = 1" " and venues.address = addresses.id" " and addresses.city = cities.id" " and events.venue = venues.id", (city,)) -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From peter at engcorp.com Fri Sep 6 22:55:42 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Sep 2002 22:55:42 -0400 Subject: Larry Wall's comment on python... References: Message-ID: <3d796a95$1@news.sentex.net> Rod Stephenson wrote: > [about Larry Wall on Python] > > "Python is cool to look at small bits of, but I think the "outline" > syntax breaks down with larger chunks of code. I'm with Aristotle on > the structure of discourse--a story should have a beginning, and > middle, and an end. So should blocks" > > Any comments? Anyone know how long is the largest chunk of code Larry Wall has actually written in Python? The fact he has to say "I think" about this issue implies he is guessing. Maybe if he actually tried it he'd conclude differently. -Peter From oren-py-l at hishome.net Thu Sep 12 06:02:14 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Thu, 12 Sep 2002 06:02:14 -0400 Subject: [FEEDBACK] Is this script efficient...is there a better way? In-Reply-To: References: <20020912074400.GA22578@hishome.net> Message-ID: <20020912100214.GA41211@hishome.net> On Thu, Sep 12, 2002 at 02:31:44AM -0700, David LeBlanc wrote: > > > Have you actually tested this? I used to believe that larger buffers are > > always better for performance. > > > > Wrong. > > > > I ran some test on Linux for the effect of buffer size on file reading > > speed and the results were very interesting. I started with a buffer size > > of 32 bytes, tested file I/O throughput and increased it > > logarithmically by > > about 2% for each step. As expected, the time to read 1mb improved as the > > buffer size increased until it hit a minimum for a buffer size of around > > 4-8k (the graph is very noisy so it's hard to tell) and then rose back up > > to a value that is 10-20% worse for buffer sizes of 32-64k and remained > > more-or-less constant for anything higher. > > > > This performance curve may be a result of the CPU cache or the OS > > architecture. > > > > The chunk size used by xreadlines is 8k which is about the optimum > > value (at least for linux). > > > > Oren > > Disk cluster size? Fragmentation? Irrelevant. The file was entirely cached in memory. This means that the test was affected only by the CPU, caches, main memory bank and the way the OS architecture interacts with them. If the file isnt't already in memory there may be some advantage to using larger buffers - the disk readahead size used by the OS is a compromise between reading more to improve performance and reading less to avoid overhead in case the data wasn't needed after all. In this case the performance curve might not have the dip in the 4-8k area and keep improving with buffer size. Even so, it should rapidly come very close to its asymptotic limit. I doubt that a buffer size over 32-64k would make any difference. Slurping 30mb into memory only makes sense if you need to access it multiple times. For a single-pass operation there will always be a pretty small buffer size that will have equivalent or better performance. Oren From peter at engcorp.com Tue Sep 10 11:44:57 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 10 Sep 2002 11:44:57 -0400 Subject: PyGTA: First Meeting notice (Toronto area Python/Zope group) Message-ID: <3D7E1379.E0D2E231@engcorp.com> As mentioned here previously, the newly formed Toronto area Python/Zope user group (http://web.engcorp.com/pygta) will hold its first meeting on Tuesday, September 17, from 7pm to 9pm, at the Willowdale United Church, 379 Kenneth Ave, North York (near the Finch subway station). Doors will open at 7:00 sharp. Some free parking is available in a lot and on the street. More details and a map are available here: http://web.engcorp.com/pygta/wiki/FirstMeeting . Among other activities, members will speak on interesting uses of Python within their companies. Note that, contrary to earlier reports, this will not be merely an _organizational_ meeting, but a real first meeting. We will also be convening a post-meeting meeting at an area pub, the "Slug and Lettuce", apparently favoured by the local Smalltalk user group. Please join us if you're in the area! -Peter Hansen, for PyGTA From mcherm at destiny.com Wed Sep 11 09:29:56 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 11 Sep 2002 09:29:56 -0400 Subject: need Python and Zope experienced programers References: <3d647529.27575997@news.earthlink.net> <15717.3618.449268.769068@gargle.gargle.HOWL> Message-ID: Skip Montanaro wrote: > Mike> I need experienced programmers for jobs in the NY metro area. > Mike> ETR Technology Center > Mike> 180 Oser Ave Suite 0400 > Mike> Hauppauge, NY 11788 > > Mike> Call, e-mail, or fax > Mike> Attention: Mike Clemente > > Mike> Ph (631)952-1300 Ext. 15 > Mike> FAX (631)952-1248 > Mike> E-mail: mike at etrtechcenter.com > Mike> Web: http://www.etrtechcenter.com > > Mike, > > You might want to post to the Python Jobs board: > > http://www.python.org/Jobs.html > Unfortunately, it's for posting job LISTINGS only, not job REQUESTS. But it seems I've found something anyhow (though without Python :-( ). -- Michael Chermside From lopik at mail.telepac.pt Sun Sep 22 15:16:32 2002 From: lopik at mail.telepac.pt (Robert A.M. van Lopik) Date: Sun, 22 Sep 2002 20:16:32 +0100 Subject: Smalltalk vs. Python and COM was Re: Byte Magazine and Smalltalk References: <3d87a686@tobjects.> <3d87dd7c$1@tobjects.> <20020918.115128.1605894428.1527@cybermesa.com> Message-ID: <1032791839.61940@spynews5> When you ask this question on comp.lang.smalltalk.dolphin you will certainly hear that Dolphin Smalltalk is the way to go if you have to do COM stuff. And they are a very helpful (and knowledgable) bunch of people, those readers of clsd. hth rob van lopik "Pino Gargiulo" wrote in message news:amkpk0$or2$1 at fe2.cs.interbusiness.it... > > "Jay O'Connor" wrote in message > > > ... snip ... > > > I use Python in a lot of places where others would probably use Perl. > > Pythons regex support is not a strong as Perl's, but its support for data > > abstraction(and hence, more complicated problems) is much more powerful. > > This brings up a question I was about to ask. I'm getting involved in a > small project > that requires a couple of COM servers, whatevere these are exactly... the > nice thing > is that any developmente language can be chose. My backgroung is Unix & > CORBA, > dabble a bit with VWNC (no serious work) and this is my second time I write > something on m$ platform. > > For this project I was considering Smalltalk and Python. The first so I > could be > some real stuff done and Python because apparently it permits quite easy > access > the the mysterious (to me) m$ APIs. I really would want to stay away from > VC++, > and I'm looking for some quite turnaround environment since I'll be learning > COM on the job. > > Anybody care to give some advice? I played around with DST but never looked > much at the existance of a COM wrapper/interface. > > TIA > > Pino > > From martin at v.loewis.de Fri Sep 13 01:57:44 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 13 Sep 2002 07:57:44 +0200 Subject: Detecting Russian and Ukrainian character sets References: Message-ID: Tim Churches writes: > Is this correct? I would claim that the problem is, for many applications, slightly different. For a number of applications, in particular in the internet, there are well-established procedures for communicating the encoding/charset of data as meta-information. The problem then is that applications often ignore those declarations, when they should really consider them. For other applications, in particular with text files, it is true that the text file does not carry a charset declaration. However, a good estimate is that you find out what computer system is being used, and follow the local conventions of that system. Both approaches may go wrong: the charset declaration in an HTML file may be missing, and the text file may have been copied from one system to another. But so may auto-detection of encodings. That is not to say that auto-detection isn't useful - but I'd like to point out that it should be only one of many options. In addition to the Perl module, it appears that there are a number of other autodetection modules: Mozilla supports Cyrillic auto-detection, and the ru-xcode package (available atleast as a FreeBSD port) does autodetection as well. I'm not aware of a Python module, but it shouldn't be difficult to port any of these algorithms to Python. Regards, Martin From SBrunning at trisystems.co.uk Tue Sep 17 04:42:34 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Tue, 17 Sep 2002 09:42:34 +0100 Subject: two or more whitespace regular expression? Message-ID: <31575A892FF6D1118F5800600846864DCBD7EA@intrepid> > From: Manuel Hendel [SMTP:manuel at hendel.net] > On Sun, Sep 15, 2002 at 07:33:50AM +0000, Alex Martelli wrote: > > import re > > twoormorewhites = re.compile(r'\s\s+') > ^ > What is the "r" for? I tried to find something about this in the docs > (Regular Expression HowTo , etc.) but I couldn't find anything. It's a raw string - see n. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From imbosol at vt.edu Mon Sep 23 23:16:15 2002 From: imbosol at vt.edu (Carl Banks) Date: Mon, 23 Sep 2002 23:16:15 -0400 Subject: Three dumb questions (ordered by dumbness descending) References: Message-ID: Thorsten Kampe wrote: > Okay, here they are: > > 1. Why is 'zip(zip(x)) != x' (should be the same because it's the > transposed) Because zip doesn't transpose. If zip were a transpose, it would take a *single* argument, which is a sequence of sequences, and would return the sequences transposed. But zip doesn't do that. Rather, it takes *multiple* arguments, all of which must be sequences, and returns a list of tuples of the nth item of the arguments. Maybe you'll understand it this way, if you're a LISP programmer: zip = lambda x: apply(transpose,x) where transpose is the function that does what you think zip does. > 2. Peter Norvig mentions in "Python for Lisp Programmers" some > "don'ts": "[x] + y" and "x[1:]". Are there more things to avoid > (especially in a loop)? A common one is "don't use 'in' in a loop". The 'in' operator (for regular lists) does a linear search of the list. I did this recently for an file sync'ing program and that part goes slow. Really new versions of Python define an 'in' operation for dicts also, but that's ok to use in a loop because it does a hash lookup. -- CARL BANKS http://www.aerojockey.com From jpm at papercut.org Fri Sep 20 10:27:16 2002 From: jpm at papercut.org (Joao Prado Maia) Date: Fri, 20 Sep 2002 10:27:16 -0400 (EDT) Subject: Overriding all methods in a class Message-ID: Hi, I have been looking for an answer for this question for a while, but couldn't find anything that would work for what I want to do. I know that you can use __getattr__ to overload methods that your class don't have, but what about overloading all methods, so I could in a way 'intercept' calls to my methods and do something different if I wanted, is that possible ? What I want to do basically is create a caching system for a specific class, and have __getattr__ (or any other magic method name) handle the decision to sue the cached return value or to actually call the method. Maybe it would be just easier to rename my current class to _Classname and create a new Classname with just __getattr__. Any suggestions ? Cheers, Joao From mr.random at gmx.net Sun Sep 29 14:25:37 2002 From: mr.random at gmx.net (Dave Richards) Date: Sun, 29 Sep 2002 20:25:37 +0200 Subject: Python and GUI question References: <3d96b808_3@news.bluewin.ch> Message-ID: <3d97459e_2@news.arcor-ip.de> There are loads of GUIs for Python - Gtk, Qt, Tk, WxWindows, Fox etc. Which you use depends on what you need, and which platform you are developing for. Tk is simple to use, but doesn't have list and tree widgets. It also looks good on Win32, but crappy in Linux. I mostly use Gtk, because it's relatively simple, but powerful - though I've never tried it on Win32. The main reason to use Gtk is Glade - it makes building GUIs pretty quick work. WxPython looks good on Win32 and Linux, and it pretty powerful. The downside is it doesn't have a (free) GUI designer like Gtk or Qt. I would say use Tk, if it's a simple app, Wx if it's more complex. If it's a Linux app, use Gtk. I don't have much experience of Qt myself. Dave On Sun, 29 Sep 2002 11:21:36 +0200, Josef B?rgi wrote: > Dear NG > > I designed a CMS using mySQL and PHP. Now I like to write an > administrativ GUI Client Tool using Python. So I bought a few books > about it, saying that there is more then one GUI interface (Tk, Qt, > xvWindow). So can anyone tell me which one you use and why ? And how do > you Design GUI interfaces (IDE) ? > > Best wishes fromSwitzerland > > Joe From notvalid at hotmail.com Tue Sep 24 16:01:30 2002 From: notvalid at hotmail.com (jano) Date: Tue, 24 Sep 2002 13:01:30 -0700 Subject: cgi post problem References: <9aWj9.39314$V7.10439005@twister.socal.rr.com> Message-ID: There was an error in my prior post. See ^^^^ "jano" wrote in message news:amq8av$2cum$1 at agate.berkeley.edu... > > > "Jeff Davis" wrote in message > news:9aWj9.39314$V7.10439005 at twister.socal.rr.com... > > Hi, > > > > It looks as though you have a lot of code. It might be helpful to try to > > narrow the problem further by removing a lot of the code unrelated to your > > problem, which appears to be that "keys" does not contain any items. After > > you work that out, then put the other code back in. > > > > My first impression is that you have some "weird" form element names > > because they contain the "/" character. That might be perfectly legal, but > > perhaps the cgi.FieldStorage class does not properly handle such element > > names, or perhaps it considers such names erroneous. > > > > Next, it seems that the line "keys = form.keys()" might be out of > alignment > > with the rest of the code in it's block. Perhaps it's just the way it > > looks after you copied your code into the post. > > > > Regards, > > Jeff > > > > > > > > Yes, the problem is that keys does not contain any items. The 'weird' names > are not the problem, because i tried it also with regular 1-word names (no > slashes), with the same results. Also, the keys=form.keys() line is > properly indented in the code -- it was just a copy/paste problem. Here is > the code again, with the extraneous stuff stripped out: > > #!/usr/local/bin/python > > import cgitb; cgitb.enable() > import sys, traceback, cgi > > def main(): > try: > form = cgi.FieldStorage() > input = form.keys() > > print "Content-type: text/html\n\n" > print(""" > 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'> > > > test > > """) > print "

",keys,"

" # ^^^^ should be 'input' not 'keys', as it is in my script. > print "" > except: > pass > > if __name__ == "__main__": > main() > > And the form is: > >
> > > > > > >
> > > The script, again, is currently just supposed to return the keys, which I am > expecting to be Name, PartNumber, etc., but it returns only an empty list. > Any ideas. > > thanks, > > jano > > > From mstenner at phy.duke.edu Tue Sep 3 21:54:01 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Tue, 3 Sep 2002 21:54:01 -0400 Subject: simple xml pickle Message-ID: <20020903215401.A6097@phy.duke.edu> I would like to find a simple xml pickle module. I have very simple objects and so very simple needs. I've found two things: the "old" xml_pickle.py, which appears to not work at all with python2.2, but is otherwise appealing. It is a single file and could be easily included with a program. and the "new" xml.pickle as it appears in the Gnosis tools. This is less appealing because it's very large and distributed over several files, and would almost necessitate full installation, and just one more prerequisite. Besides, I can't get it to build (into an rpm, which is the only way that I'm really interested in installing software here). Does anyone know of anything else? Again, all I need is the ability to handle simple objects & types. I'd prefer something that I can include in my program/package, rather than something that would need to be installed separately. Thanks, Michael (I've looked through the vaults and put in lots of google time. If there are other resources, I'd love to hear about them.) -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From cotabas at earthlink.net Sun Sep 1 14:58:05 2002 From: cotabas at earthlink.net (CotaBas) Date: Sun, 01 Sep 2002 18:58:05 GMT Subject: Executable Python Programs Message-ID: <1rtc9.108$LI2.7238@newsread2.prod.itd.earthlink.net> This is probly a stupid question...... how do you make your python programs executable (without python IDLE). For example: I write a program that I want to give to a friend to run on his computer. He doesn't have Python. What can I do to make it so he can run it without Python? --------------------------- -CotaBas From gerhard.haering at gmx.de Tue Sep 3 16:29:19 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 3 Sep 2002 20:29:19 GMT Subject: basic cgi question References: <67f6bbe5.0209031225.56b1b7bd@posting.google.com> Message-ID: Jeffrey Keil wrote in comp.lang.python: > Greetings: > > I've used Perl in the past for cgi programs. I thought I'd play around > a little with Python. I've tried a few experiments. > > I have programs that prints out to the browser. Unfortunately, it > prints out everything, including the "import" statements, "print", > etc. I'm not quite sure what I'm doing wrong. Your web server doesn't handle the Python script as a CGI script, but as a normal document instead. So the answer is: configure your web server appropriately. Depending on your webserver, one of these groups is appropriate for questions about configuration: comp.infosystems.www.servers.mac comp.infosystems.www.servers.misc comp.infosystems.www.servers.ms-windows comp.infosystems.www.servers.unix You can also find some Python specific answers for at least IIS, Apache on http://python.faqts.com and IIRC also in the Python FAQ. -- Gerhard From pereira at cis.upenn.edu Sat Sep 7 12:06:07 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Sat, 07 Sep 2002 12:06:07 -0400 Subject: Smoothing a discrete set of data References: <3csmdso5.fsf@morpheus.demon.co.uk> Message-ID: On 9/7/02 6:02 AM, in article 3csmdso5.fsf at morpheus.demon.co.uk, "Paul Moore" wrote: > I have a set of data, basically a histogram. The data is pretty > variable, and I'd like to "smooth" it to find trends. [...] When I've tried to formalise this, I've always stumbled over the fact > that it's a trade-off exercise (there most be some sort of "tolerance" > parameter in the algorithm) - on the one hand, the original data is > "best" (in the sense that it matches exactly) whereas on the other > hand, a single horizontal line at the average is "best" (fewest number > of steps). > > My instinct is that you're looking for something that balances number > of steps vs difference from the original data. But for the life of me > I can't see how to make this intuition precise. > > Can anyone help me? I can't believe that this problem has never come > up before, but I can't find any literature on it. You must have been using the wrong search engine This is the problem of *regression*, extensively studied in statistics and machine learning. The tradeoff you mention is discussed in the literature under headings like "bias-variance tradeoff", "generalization bounds", "structural risk minimization"... If you want a single good book that covers this and related topics with a minimum of prerequisites (elementary calculus and linear algebra, a teeny bit of probability), I recommend -- F From DennisR at dair.com Wed Sep 18 16:54:24 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Wed, 18 Sep 2002 20:54:24 GMT Subject: Python comment stripper References: Message-ID: <4K5i9.674$HD4.41010424@newssvr13.news.prodigy.com> > One question: How big is your disk page size? My disk page size is 512. However, the object of the compression here has nothing to do with saving disk space. The intent here is speeding up internet download of an AutoRunning EXE that has Python DLLs and support libraries included. Perhaps, I should have stated my reasons for wanting to strip comments out up front. I apparently caused everyone who responded to question whether my objective made any sense at all. In retrospect, I should have stated my larger objective (speeding internet upload/download) in addition to my narrower objective (stripping comments for maximal compression). I am sorry for an misunderstanding. -- Dennis Reinhardt http://www.dair.com From paul at boddie.net Wed Sep 4 04:26:20 2002 From: paul at boddie.net (Paul Boddie) Date: 4 Sep 2002 01:26:20 -0700 Subject: RedHat 7.3 and Python2.2.1 References: <88bc63c6.0209030640.71e074ff@posting.google.com> Message-ID: <23891c90.0209040026.3b9a0691@posting.google.com> writeson at earthlink.net (Doug Farrell) wrote in message news:<88bc63c6.0209030640.71e074ff at posting.google.com>... > To everyone who responded, > > Thanks you for all your help, much appreciated. I ended up solving the > problem (at least I hope so, and didn't create more for myself! ) > by doing the following: > > rpm -ivh --replacefiles python-2.2* I do wonder if that should have been "-Uvh", but then my strategy with RPM installation tends to involve stripping away the conflicting packages (with "--erase") and installing the new ones in their place. Indeed, I did this recently with KDE and found Python very useful in the automation of the process - popen2 and os were most helpful in identifying and removing the 30 or so old packages. ;-) > The --replacefiles option seemed to eliminate the file conflicts and > the RedHat tools (like up2date) still are working. I suppose that Python 2.2.1 attempts to act just like Python 2.2 and that various files/directories are identically named. Whilst this is likely to confuse the RPM system, there's a reasonable chance that the replacement files will do more or less what the old ones did. There's still a risk that various extension modules won't exist in the newly-installed package, but then they probably won't have been deleted from the filesystem if you do a "package overwrite" in the manner illustrated, and the extension API probably won't have changed enough to cause severe problems when loading old extension modules from Python 2.2 into Python 2.2.1. Even though the concepts behind package management are sound, the RPM implementation seems to be a solid justification for building packages from source, however. Paul From maxm at mxm.dk Tue Sep 24 04:47:16 2002 From: maxm at mxm.dk (Max M) Date: Tue, 24 Sep 2002 10:47:16 +0200 Subject: confusion about opening files References: Message-ID: <3D902694.3090508@mxm.dk> Mark McEahern wrote: > I should have read the post I was replying to more carefully. I saw the > "integer required" error and didn't notice that the OP was using os.open. > So the 'from x import *' was a red herring. As Erik Max Francis pointed > out, the OP should use open instead of os.open. Actually he should use file() as open() is deprecated (well sort of ;-) ) "2.1 Built-in Functions The file() constructor is new in Python 2.2. The previous spelling, open(), is retained for compatibility, and is an alias for file(). " regards Max M From fb at frank-buss.de Sun Sep 1 04:58:32 2002 From: fb at frank-buss.de (Frank Buss) Date: Sun, 1 Sep 2002 08:58:32 +0000 (UTC) Subject: Crossword generator References: Message-ID: Frank Buss wrote: Sorry, this is the online link: http://www.pdos.lcs.mit.edu/cgi-bin/theme-cword -- Frank Bu?, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From see_reply_address at something.invalid Mon Sep 9 00:18:23 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 09 Sep 2002 16:18:23 +1200 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> Message-ID: <3D7C210F.7090708@something.invalid> Stephen Ferg wrote: > "Joseph A. Knapka" wrote in message news:<3D798461.B3FE0E06 at earthlink.net>... > >>Also, you should be aware of the "command" option > > I know about it, but I think that for beginners, it is very confusing. < ... So I think that > beginners should consistently use the more plodding technique of > explicit binding. I hope you're aware that what you're doing in your buttons example is NOT equivalent to using the "command" option. The latter does a number of extra things: it waits until the mouse is released, and triggers the handler only if the release is within the button. So if you insist on presenting things the way you are, you'd better include a clear warning that you're taking a big short-cut and that you'll explain how to do it correctly later, otherwise you'll lead people into a very bad habit. But I wonder whether this isn't going to be more confusing than just showing the use of the command option from the beginning. > For one thing, it leads down the path to lambda, Not if you present your examples using one of the several reasonable alternatives to lambda which exist. > For another, it doesn't automatically pass an event > object, which makes it even more difficult to use. In the case of buttons, this isn't usually a problem, since all you want to know is that the button was clicked. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From andrewm at object-craft.com.au Mon Sep 16 02:40:37 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Mon, 16 Sep 2002 16:40:37 +1000 Subject: Pickling slotted instances In-Reply-To: Message from martin@v.loewis.de (Martin v. Loewis) of "16 Sep 2002 07:37:23 +0200." References: Message-ID: <20020916064037.585853C8FF@coffee.object-craft.com.au> >I don't know what issues Guido had in mind, but here are a few for >consideration: > >1. How to determine all slots? It has been proposed that __slots__ > should return a tuple that includes base slots as well; > alternatively, iterate over base types yourself. Alternatively, > return slots in __dict__. How is this handled in an instance now? Does an instance have slots for all it's direct slots as well as the slots defined by it's base classes? If so, it should probably be serialised in exactly this manner? This is probably the nub of the matter - I'll need to look into the implementation to learn more. >2. Should all slots be pickled unconditionally? You seem to expect > this, but Samuele Pedroni points out that, in Java, some slots can > be marked transient, to avoid pickling them. That would be nice, but we already have this problem with traditional classes (I would guess this is one of the more common reasons to code your own __getstate__ machinery with traditional classes)? >3. How to pickle slots? You are suggesting that the list of slot names > is included, but that appears to be redundant - if you know the type, > you also know what slots it has. Very true (what happens if the class implementation is changed? Some sort of signature, at least, might be required, I guess). >4. How to pickle unset slots? If a type has a slot but the instance > has not assigned the slot, requesting the slot value raises an > AttributeError. It would seem simple enough to include a "not set" token in the serial stream. >If you are in doubt that this is really as tricky as presented, I'd >encourage you to come up with a patch. In the process of implementing >the patch, you may either find that all issues have a straight-forward >solution, or that there are really serious issues remaining. "Put your code where your mouth is"... 8-) I'm sort of surprised that slots were added without having all the bases covered, but I'm presuming that they are really a manifestation of the internal machinery that was added for class/type unification, and have been exposed in the language itself so people can see if it's a useful feature. -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From benji_75 at hotmail.com Wed Sep 18 05:31:05 2002 From: benji_75 at hotmail.com (Ben Gerblich) Date: Wed, 18 Sep 2002 19:01:05 +0930 Subject: try except ImportError failing to catch error! Message-ID: I am importing all module files in the CWD. This part works fine. I want to add the functionality to catch the error if there is a typo in the imported module file. The following does not catch the error! try: self.userDefs[file[:-3]]['class'] = __import__(file[:-3]) except ImportError, e: print 'cant do it', e I still get the runtime error: Traceback (most recent call last): File "./main.py", line 8, in ? application = testApp() File "/usr/lib/python2.1/site-packages/wxPython/wx.py", line 1581, in __init__ _wxStart(self.OnInit) File "./mainScript.py", line 3444, in OnInit self.frame = MainFrame(None) File "./mainScript.py", line 2836, in __init__ exec code File "", line 1, in ? File "./Display.py", line 33, in __init__ self.line(5, 60, 15, 60,999) TypeError: line() takes exactly 5 arguments (6 given) I expect this error! as the '999' should not be there. Why does not the 'cant to it' line print instead? And is there a way for my handler routine to return the line-number of the imported module file that caused the error? Thanks, Ben. Im using: Red Hat Linux 7.1 python2-2.1-5.i386.rpm wxPython-2.3.2.1-1-Py21.i386.rpm wxGTK-2.3.2-1.i386.rpm _________________________________________________________________ MSN Photos is the easiest way to share and print your photos: http://photos.msn.com/support/worldwide.aspx From marklists at mceahern.com Wed Sep 18 18:41:31 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 18 Sep 2002 17:41:31 -0500 Subject: When we say 'One obvious way...', do we mean 'generally obvious' or does that matter? In-Reply-To: <8d148763.0209181359.68cd789f@posting.google.com> Message-ID: [yaipa] > I LIKE the below code snippet. While it might be Pythonic, it will > only be 'obvious' to a Python programmer with some experience under > his/her belt. Actually (as the author of the code snippet), I would say it's decidedly unpythonic. Why go through contortions to restrict access to base class methods? Nonetheless, that's what the original poster wanted. Besides, I needed to fill in gaps in my understanding of metaclasses and this seemed like the perfect opportunity. Cheers, // mark - From m.faassen at vet.uu.nl Wed Sep 4 06:15:27 2002 From: m.faassen at vet.uu.nl (Martijn Faassen) Date: 4 Sep 2002 10:15:27 GMT Subject: Why Python? References: Message-ID: Benjamin wrote: > I just begun to learn how to program. And I choosed Python for > doing that. surfing around the web i found an article about this > language, they said it's the ideal language for beginners to the > world of programming. and i admit it, the syntax is very clear making > the code very readable, i learn easily the concepts of programming > and i soon wrote some nice programs. but since i finished my > newbie-tutorial, i am wondering about one question: is it worth to go > deeper into python? i talked to a friend of mine, he told me that i > should try php.. > what should i do?? ^_^ in other words: what is python good for? > why should i continue with python? Python's good for everything! Well, perhaps not everything, but it's a general programming language and it can take quite a while until you run into its limitations. And every language has its own limitations and advantages. Python's main limitation in my mind is that it is relatively slow compared to code written in C, say. However, don't let that scare you away -- it's fast enough for many purposes, there's a lot that you can do to improve performance without leaving Python, and performance is a subtle issue; as Python is a higher level language sometimes it is easier to write a performing but more complicated algorithm in Python, compared to a lot of time and struggle in C. Don't worry too much about performance when you're starting out. Besides, if you compare to PHP I would think Python wouldn't do so badly performancewise anyway. I wouldn't recommend learning PHP at this stage; from what I've seen and heard about it is it not very good at showing beginning programmers how to code cleanly -- Python is a lot better at that (though there are certainly other languages that would help there as well). PHP might obscure the concepts from you or expose you to bad practices. Then again, it might help to deliver quick results and thus stimulate you to program more, so I don't imagine it would do a lot of harm either as long as you stay aware of good programming practices. PHP was developed to create dynamic web pages on the server side, and grew from that. People still mostly use it to create web applications. It is certainly possible to write web applications with Python; I do that for a living using Zope (http://www.zope.org). Here's a page describing a whole range of options if you want to do web programming with Python: http://www.python.org/topics/web/ But Python can be used for many other purposes besides web programming. It depends entirely on what you want to do. Best way to learn is to set yourself a goal that's not too ambitious and try implementing it. Even if you fail you'll have learned new things. Regards, Martijn -- History of the 20th Century: WW1, WW2, WW3? No, WWW -- Could we be going in the right direction? From jim at dsdd.org Thu Sep 19 22:06:37 2002 From: jim at dsdd.org (Jim Meier) Date: Fri, 20 Sep 2002 02:06:37 GMT Subject: Smalltalk style inspector References: Message-ID: On Thu, 19 Sep 2002 12:00:08 +0100, Andrew Thompson wrote: > I don't even know the process for contributing the module... 1. Make it available for download. 2. ??? 3. Profit! -Jim From bkc at Murkworks.com Wed Sep 11 12:51:07 2002 From: bkc at Murkworks.com (Brad Clements) Date: Wed, 11 Sep 2002 12:51:07 -0400 Subject: UNIX processes References: Message-ID: <3d7f71e4$1_5@goliath.newsgroups.com> Can you describe your module more? I want to implement something like top/gtop on Linux, but using XWT as the client via Zope or a CGI. I also want to emulate gkrellm too. So, I need load averages (I can get via /proc) but I also want top style output, memory usage and current CPU usage by process. Folding threads together into a "single process object" would also be nice for presentation purposes. -- Novell DeveloperNet Sysop #5 _ "Bo M. Maryniuck" wrote in message news:mailman.1031755292.20295.python-list at python.org... On Tuesday 10 September 2002 13:52, Erno Kuusela wrote: > use the ps program (ps -e works on linux). there is no other > standard api for it. I already made native Python module for this, because I don't like 'ps' in this case. Well, module works even faster. ;-) -- Regards, Bogdan I doubt, therefore I might be. -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From dsavitsk at e-coli.net Mon Sep 9 11:13:31 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Mon, 09 Sep 2002 15:13:31 GMT Subject: PythonWin bug [very weird] Message-ID: This is PythonWin 145 (patched for asp), Python 2.1.3, Win2k. I have no means for testing other versions. The bug is that pressing the wrong sequence of buttons can render a file unsaveable. To reproduce it: 1. open a .py file 2. make some changes 3. press the X to close the file (not to close PythonWin) 4. when asked to save (Yes, No, Cancel) press Cancel 5. Save the file (File | Save) 6. Any new edits to the file are unsaveable (the buton is grayed out). To do so, you must copy the entire contents, close the file, re-open it, and paste the clipboard. -doug From gerhard.haering at opus-gmbh.net Mon Sep 2 07:51:27 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 2 Sep 2002 11:51:27 GMT Subject: Must have Python modules? References: <_THc9.42153$vY2.1039887@e3500-atl2.usenetserver.com> Message-ID: Robert Oschler wrote: > I've scanned Vaults of Parnassus and several other hot Python sites and > was overwhelmed by the amount of stuff that is available. So I'm asking > you, what is your favorite, absolute must-have Python module? What do you want to hear? Everyone's list of favourite Python extensions? There's likely is more than one for most of us. My favourite is the "this" module. Don't know what you expect :-) Maybe better ask a specific question as to what is the recommended module for a certain task, like parser generation, GUI, database access, etc. Previous similar discussion: http://tinyurl.com/19a9 -- Gerhard From tismer at tismer.com Sun Sep 15 14:24:18 2002 From: tismer at tismer.com (Christian Tismer) Date: Sun, 15 Sep 2002 20:24:18 +0200 Subject: Stackless Python, eventual merge? References: Message-ID: <3D84D052.1080600@tismer.com> Martin v. L?wis wrote: > "David Abrahams" writes: > > >>I think it still matters. You don't want people who need stackless' >>capabilities to have to use a non-standard Python forever, do you? > > > Unfortunately, the current implementation is processor-dependent; it > supports x86, SPARC, and PPC only (not really sure about PPC). Since today it supports X86, Sparc, PPC and Cygwin. > It also > limits extensions: if they call back to Python, they must not keep > "global" variables on the stack (global in the sense that their > address is known outside their function). > > These limitations require Stackless users to be more aware of the > inner workings of Python, or they risk crashes - something that would > be considered a bug in standard Python. Yes, but :-) Stackless is built in a way that by default there is no difference to the standard. No stack switching occours, all is identical. If you want stackless behavior, you must switch it on. And if you want to use task switching, you need to import the stackless extension (which is now apart). Therefore I'd claim that putting Stackless into the core trunk would not do any harm. Users who want to use it can use it, others may ignore it (and it is very tiny, about 50k). This could be something like the thread package, which also does not work on all platforms. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From fperez528 at yahoo.com Thu Sep 26 14:14:20 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 26 Sep 2002 12:14:20 -0600 Subject: Creating daily/monthly averages from datafiles References: Message-ID: At the risk of sounding stupid, may I suggest you look into Numeric for this? It has most of what you want already in it, and it's fast to boot. Multi-year data every 15 minutes is bound to be a lot, I can't imagine how slow doing that in raw python will be. Unless you are going to throw a 1024 node cluster at this simple problem :) Now, the trick with Numeric is that it wants homogeneous data, so none of that date/data mixing you want. But with a bit of helper tables, at some extra storage cost, I'm willing to bet you can fix this very easily. Store the numerical data in one or a few Numeric arrays, and have a few auxiliary python structures (dicts, probably) to help along with the indexing. This way you can quickly find where in the Numarray the data you want is, and then you can efficiently process it using Numeric. Just my $0.02. Cheers, f. From michael at stroeder.com Tue Sep 17 07:14:51 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 17 Sep 2002 13:14:51 +0200 Subject: More on Protecting Source Code References: Message-ID: David LeBlanc wrote: > Well, I think of it this way: machine coded binaries are more like a 128 bit > key and Python is more like a 40 bit key. I agree that nothing is safe from > reverse engineering; it's a matter of how much pain and money it takes to > unscrut the inscrutable. Python could do better - how I'm not totally sure. Dave, without knowing the business model for the software you write nobody can give any reasonable answer. As usual: Define your business model first and derive the technical solution from that afterwards. Ciao, Michael. From rajarshi at presidency.com Wed Sep 18 13:21:26 2002 From: rajarshi at presidency.com (Rajarshi Guha) Date: Wed, 18 Sep 2002 13:21:26 -0400 Subject: isFloat: Without Exception-Handling References: <%82i9.1366$bh1.943@fe03> Message-ID: On Wed, 18 Sep 2002 12:47:40 -0400, Steve Holden wrote: >> >> >> def isFloat(string): >> if type(string) == type(1.0): >> return 1 >> else >> return 0 >> >> This should do what you want without exceptions > > I doubt that VERY much. Please test your code before submitting, or > ensure you note it wasn't tested ... [snip] >>>> isFloat("banana") > 0 >>>> isFloat("1.2") > 0 If you call it as isFloat(1.2) it works From sross at connectmail.carleton.ca Tue Sep 24 22:57:53 2002 From: sross at connectmail.carleton.ca (Sean Ross) Date: 25 Sep 2002 02:57:53 GMT Subject: Removing all occurences of a character from a string. Message-ID: Hi. I have a string, say "'Hello World'", where Hello World is in single quotes(i.e., 'Hello World'). How can I remove the single quotes so that "'Hello World'" becomes "Hello World"? Thanks Sean Ross From cliechti at gmx.net Fri Sep 27 18:17:03 2002 From: cliechti at gmx.net (Chris Liechti) Date: 28 Sep 2002 00:17:03 +0200 Subject: Better terminal for windows? References: <3D94B037.2020202@motorola.com> <3D94D1DD.40407@motorola.com> Message-ID: Stephen Boulet wrote in news:3D94D1DD.40407 at motorola.com: > Gerhard H?ring wrote: >> cmd.exe isn't *that* bad once you activate tab completion in the >> registry. Have you done that? > > Nope. How do you do that? I couldn't figure it out just looking through > regedit. had to google for that too: http://www.winnetmag.com/Articles/Index.cfm?ArticleID=8746 chris -- Chris From aleax at aleax.it Mon Sep 23 02:39:23 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 23 Sep 2002 06:39:23 GMT Subject: Universally unpacking tuples References: <158d3913.0209222233.123a9675@posting.google.com> Message-ID: Peter Bittner wrote: ... > arbitraryTuple = ('abc', '123', 'qwert', ...) > while len(arbitraryTuple) > 0: > elem, arbitraryTuple = arbitraryTuple > print elem > > Well, I know this doesn't work since unpacking requires the correct > number of elements on the left side... :-( ... > mylist = ['abc', '123', 'qwert', ...] > for i in range(len(mylist)): > elem = mylist[i] > print elem The second snippet works just as well whether name mylist refers to a list, or to a tuple. Tuples are indexable just like lists are -- they're not _modifiable_, but that's a different issue. However, the simplest solution of all, also universally applicable to all sequences (lists, tuples, strings, ...) and other iterables (directories, files, ...) is: for elem in whatever: print elem Back to the problem of what you try to accomplish in the first statement of the first loop above: elem, whatever = whatever[0], whatever[1:] this sets elem to the first argument of 'whatever' (can be a tuple, list, string, ...) and re-binds name 'whatever' to all elements except the first (keeping the same type as was in use before -- again, could be tuple, list, string, etc, etc). You do not need it here, and it would be a substantial waste of both programming and computational effort to use it, but in some other cases it might indeed come in handy. Alex From aleax at aleax.it Tue Sep 17 07:31:40 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Sep 2002 11:31:40 GMT Subject: Regular expression help needed References: <3D870A74.5D2D7595@fast.no> Message-ID: Torkil Grindstein wrote: ... > Btw, I have no knowledge of SAX. Perhaps I should dig into that? Yes, I WOULD suggest looking into Sax (and minidom, and Prescod's pulldom) for any kind of XML processing. Jones and Drake, "Python & XML", O'Reilly, is a good book dedicated to the subject (very little on pulldom -- i'm learning to appreciate pulldom myself just quite recently, as it's saving my bacon on a complex XML transcript- with-mods project, one that needs to work on large enough files that minidom is not an option, but also needs enough localized "dig into this node and change it like this and like that" that SAX would be rather a PITA). Alex From jp at NOSPAMdemonseed.net Wed Sep 11 11:07:33 2002 From: jp at NOSPAMdemonseed.net (jason petrone) Date: Wed, 11 Sep 2002 15:07:33 +0000 Subject: Python iCalendar API? References: Message-ID: Erik Price wrote: > Is there a Python module that provides capability of processing files > in .ics (iCalendar) format? I found nothing concrete on Google or at > python.org ... I have a horrible, messy, rats nest of an ical module. It converts my gnomecal/evolution calendars into html fragments. If you promise to not tell anyone I'm the one that wrote it I can send it to you. jason From Pekka.Pessi at nokia.com Tue Sep 17 06:56:39 2002 From: Pekka.Pessi at nokia.com (Pekka Pessi) Date: 17 Sep 2002 13:56:39 +0300 Subject: Detecting IPv6 support References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: loewis at informatik.hu-berlin.de (Martin v. L?wis) writes: >- the IPv6 patches took about 15 months to integrate. For many months, > the patches were unreviewed, because nobody thought to have the > expertise to review them. I eventually tought myself the necessary > background to review the patch, after which about 4 further > iterations where necessary before the patch was installed, and about > 10 changes after the patch was installed. Speaking of IPv6: is the IPv6 enabled on the Pythonlabs Windows distribution by default (sorry, I don't have a Windows box in my use at the moment)? Does Python support the older IPv6 stacks for NT4 and W2K? What is the recommended method of finding out if Python and the underlying OS support IPv6? I can, for instance, create an IPv6 socket with a Python version that does *not* support IPv6. Pekka From erikprice at mac.com Wed Sep 18 08:57:59 2002 From: erikprice at mac.com (Erik Price) Date: Wed, 18 Sep 2002 08:57:59 -0400 Subject: Will "Python in a Nutshell" be too short? In-Reply-To: <02091723502402.21243@arthur> Message-ID: <4278C014-CB06-11D6-B699-00039351FE6A@mac.com> On Tuesday, September 17, 2002, at 05:50 PM, Alex Martelli wrote: > The number of pages I had to devote, in particular, to tkinter and > xml, still boggles my mind -- yet, I do see that they add to the book's > usefulness more than they take away from it. I just hope that the "Sample Chapter" that ORA offers from its website isn't the XML chapter. It's not that I'm not interested in XML or that I don't think it will be worthwhile, but rather because it seems like almost every "Sample Chapter" offered on their site is "the XML chapter" for the given book!! ;) Erik PS: I know this is an overstatement. -- Erik Price (zombies roam) email: erikprice at mac.com jabber: erikprice at jabber.org From sholden at holdenweb.com Mon Sep 30 13:35:47 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 30 Sep 2002 13:35:47 -0400 Subject: rank-0 arrays? References: <3d988160.79509684@news> Message-ID: wrote in message news:3d988160.79509684 at news... > In Numeric Python, what are rank-0 arrays? > Must not arrays have at least 1 dimension? > Only if they must contain data. A xero-rank array will (sort of) be the None of Numeric arrays. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From tdelaney at avaya.com Thu Sep 19 21:18:35 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 20 Sep 2002 11:18:35 +1000 Subject: Minimal debug/rep functionality Message-ID: > From: holger krekel [mailto:pyth at devel.trillke.net] > > Delaney, Timothy wrote: > > > From: Peter Hansen [mailto:peter at engcorp.com] > > > > > As I said, I *expect* to be able to release (there's no > commercial reason > > not to, and we have done so with such things in the past). > > Maybe we are turning circles [1] but why don't you do it, then? > > Maybe you need to invest some time in obfuscating your > source code and you don't want to do it? > > Why do you *expect* others to solve this problem for you? Holger, what the hell are you talking about? I'm not releasing yet because: 1. The tool is not feature-complete. 2. The code is not in a fit state for release - needs more documentation, etc - it's in a state of high flux, and it's a personal (but work-related) project so I've been a bit lax ;) 3. I have not even approached my employer as to whether I am allowed to release it (but I expect that when I do so I will be given permission). As I stated, I would like this to get into the core library eventually - how does that in any way suggest that I want to: 1. Obfuscate the code or 2. Expect others to do the work for me ??? Tim Delaney From max at alcyone.com Fri Sep 6 16:06:51 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 06 Sep 2002 13:06:51 -0700 Subject: Interrupting Python References: Message-ID: <3D790ADB.912B9E3E@alcyone.com> Bob Easton wrote: > I have a script that can run, accessing network resources, for several > days. > Since the script does not normally need keyed input, exception > processing > does not raise the keyboard exception until after the program ends > normally. > I would like to be able to interrupt if from the keyboard, but have > not > learned the trick. How can I do this? If you're under a UNIX-like operating system, kill its process ID with the -INT signal. kill -INT processID You can find the process ID with ps if you don't already know it. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From Gareth.McCaughan at pobox.com Sun Sep 15 10:31:42 2002 From: Gareth.McCaughan at pobox.com (Gareth McCaughan) Date: Sun, 15 Sep 2002 15:31:42 +0100 Subject: Extending a C++ App References: <996eade8.0209120912.3a653d7@posting.google.com> <996eade8.0209122352.45721938@posting.google.com> Message-ID: David Abrahams wrote: > > "Bwuce_Wee" wrote in message > news:996eade8.0209122352.45721938 at posting.google.com... > > > I'm busy investigating Boost.Python... > > In that case, get Boost.Python v2 using the instructions at > > http://mail.python.org/pipermail/c++-sig/2002-May/001100.html > > It's nearing release, and v1 isn't long for this world. If you recommend new users to start with v2 rather than v1, then it's already time for a (pre-)release, no? -- Gareth McCaughan Gareth.McCaughan at pobox.com .sig under construc From brian at sweetapp.com Mon Sep 23 13:41:33 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 23 Sep 2002 10:41:33 -0700 Subject: WSDL for XML-RPC ?? In-Reply-To: <_YAj9.21316$0p1.377838@news2.ulv.nextra.no> Message-ID: <001001c26328$75194ff0$df7e4e18@brianspiv1700> > SOAP has WSDL to describe a webservice. Doeas XML-RPC have something > similar? XML-RPC has an optional set of methods that allow introspection. They are: system.listMethods() system.methodSignature(method_name) system.methodHelp(method_name) Here is a usage example: >>> from xmlrpclib import Server >>> s = Server('http://www.sweetapp.com/cgi-bin/xmlrpc-test/rpc1.py') >>> s.system.listMethods() ['add', 'get_source_code', 'mul', 'pow', 'system.listMethods', 'system.methodHelp', 'system.methodSignature', 'system.multicall'] >>> print s.system.methodHelp('pow') pow(x, y[, z]) -> number With two arguments, equivalent to x**y. With three arguments, equivalent to (x**y) % z, but may be more efficient (e.g. for longs). >>> For information on how to create servers that automatically support these methods, see: http://www.sweetapp.com/xmlrpc/ Cheers, Brian From hwlgw at hotmail.com Sat Sep 28 06:41:52 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 28 Sep 2002 03:41:52 -0700 Subject: comp.lang.python... References: Message-ID: "Vincent A. Primavera" wrote in message news:... > Hello, > Stupid question... What information do I need to set up > comp.lang.python with my news client(Pan)? > > Thank you, > > Vincent A. Primavera. Perhaps stupid answer: did you know that you can read news using only a web browser? And sent messages too. Have a look at http://groups.google.com/groups?q=comp.lang.python ''' Alexander Graham Bell is alive and well in New York, and still waiting for a dial tone. ''' From erikprice at mac.com Tue Sep 17 10:26:09 2002 From: erikprice at mac.com (Erik Price) Date: Tue, 17 Sep 2002 10:26:09 -0400 Subject: OT: Re: Python on MacOS X 10.2: a warning and instructions In-Reply-To: <1F30F09A-CA06-11D6-8521-00050287C0A6@earthlink.net> Message-ID: <691A8B2C-CA49-11D6-888F-00039351FE6A@mac.com> On Tuesday, September 17, 2002, at 02:24 AM, Kow K wrote: > I probaby won't migrate to Jaguar for a while. > I can't trust Apple these days. Now, Apple is such a > shameless company that they don't care privileges > of previous users. Why do 10.1.x users have to pay as > much as $129??? No matter how tight their budget is, > that sucks. Well, 10.0.x came with my computer, so I guess I paid for that version. And it sucked. Then 10.1.x came out and I got an upgrade package for free from a nearby Apple store. You could also get one mailed to you for $20 directly from Apple. That version was a much-needed improvement. Now 10.2.x is out and costs $129, but if I only have to pay for every even-numbered point release, it doesn't seem so bad. Let's see if they offer 10.3.x for free (or $20). It's the other things Apple is doing that worry me: stealing from 3rd party developers putting Watson into Sherlock. [Though I do appreciate the decision to move "Find" back into the "Finder"] To the OP: Did you say that you were able to get a Mac OS X version of Python working with GNU readline without using Fink?? Erik -- Erik Price (zombies roam) email: erikprice at mac.com jabber: erikprice at jabber.org From jb at cascade-sys.com Tue Sep 17 06:54:36 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Tue, 17 Sep 2002 03:54:36 -0700 Subject: threads or queue for this task References: Message-ID: <3D8709EC.8020208@cascade-sys.com> Alex Martelli wrote: >James J. Besemer wrote: > ... > > >>>>Generally, Queues never get "full" and you generally don't care if >>>>they're empty. >>>> >>>> >>>You can define Queues that can hold a maximum number of items; [...] >>> >>> > >And I proceed to give a very detailed and rather realistic example. >How come you don't address it at all? > I certainly meant no disrespect. Nor did I mean to contradict anything material that you said. I took your point to be that a bounded queue also is sometimes useful, which I do not and did not dispute. Your example and discussion seemed complete and thorough. I read it as an extension to what I had offered and I had nothing to add or to contradict. In summary, you expressly classed it as an "optional embellishment" which seemed consistent with my own view. It goes without saying that if the designer knows in advance that he doesn't have the throughput to handle incoming requests, then a significantly more complicated solution is called for. I alluded to more complex topologies and scenarios but I lacked the time and patience to spell out the solutions. Attempting to do so seemed doubly pointless as you seemed to be taking the lead on more elaborate scenarios. So at a high level I am at a loss, as you seem to be picking a fight I did not intend to participate in. Like I said, I thought we were largely in agreement, while expanding upon different scenarios. >>Generally," NOT having a limit is by far the more elegant solution. >> >> > >I dispute the generality you assert, > I agree there are situations where unbounded queues might be inappropriate. I only meant to suggest to this particular novice that it was a complication that I would avoid in a first cut solution. In this, I am "coming from" the standpoint of Extreme Programming -- you may recall -- that dictates you start by writing the simplest solution you don't know won't work. Performance optimization and other "embellishments" are always deferred unless/until you can't avoid it. That simplest, initial solution IMHO, is an unbounded queue. I further characterize it as "elegant" as it's fully functional for many applications and it's as simple as it gets. To me, real world complications, however realistic, tend to result in less "elegant" solutions but perhaps you disagree. >and, again, I gave a >specific example: where the time to produce work requests >(posted to a queue) is always far less than the time to >consume/process a work-request taken from the queue. > >This >is hardly a RARE situation: on the contrary, it's quite a >normal state of affairs that processing a work-request is >much more time-consuming than producing it. > Incidentally, the ratio of the "time to produce work requests" vs. the time to process them is immaterial (since the work requests may be created on a different machine). Queuing theory usually refers to "the arrival rate" of the requests vs. the the average processing time that matters. Little's result tells us that in a steady state system, if the average arrival rate is R (arrivals per unit) and the average processing time is T (units) then the average queue length will be N: N = R * T Of course, Little's result only holds for steady state systems, where the arrival rates are relatively low or the processing times are relatively short. It may be more useful to consider inter-arrival times (the inverse of arrival rates), I: N = T / I. Then it's easy to see that as the inter-arrival times shrink then the queue length can become arbitrarily large. Of course, this all is assuming stochastic processes, with random variable arrival rates and processing times. If you're looking at a static system with a fixed processing time and known arrival rates then it's a matter of simple arithmetic Bottom line is if the requests exceed the capacity of the machine then your queue length grows without bounds and eventually you're hosed. Frankly, any time you do NOT have enough capacity to handle the expected traffic then your system design is flawed on a fundamental level. You can perhaps mitigate the problem with bounded queues or what not but that still leaves you with possible data overruns or other problems upstream from the writer end of the queue. Bounded queues only push the problem of to some other point in the system, since the writer is suspended and not responding to the requests. Ultimately, at some level, the designer is going to have to deal with the problem of requests that cannot be fulfilled. Conversely, if it is given that there is ample CPU power then he can dispense with all the complexity and use unbounded queues or something even simpler. In my experience, computer queuing systems first and foremost have to be designed so that they can handle the max throughput without fail. In a few embedded systems, throughput considerations drove the choice and speed of the CPU(s) and other hardware "assist." More commonly, the CPU speed was fixed and max throughput drove constraints on request rates or processing times, usually both. In a number of systems I worked on, queues always only had 0 or 1 items in them. In one system like this, the queues actually were implemented in hardware and writer CPUs actually locked up until the reader emptied the previous request. In another, the CPUs themselves did not lock but all further communication was effectively blocked until the "queue" cleared. Blocking for any length of time was considered a bug and the system was designed never to do that. In other systems, queues had fixed sizes but this was in cases where the RTOS required the developer to declare a fixed amount of space. In this case, the queue size was determined by measuring the average arrival rates and processing times (plus a fudge factor), but the limits were chosen to conserve RAM; like the CPU's stack they were designed never to be exceeded in normal operation. Then there were many, many cases where throughput was known to be sufficiently low that queue length was never a consideration. Usually arrivals were low enough and processing time fast enough that the average queue length was virtually zero. As far as producers outperforming consumers being the "normal state of affairs" -- while I agree once it was a common problem, I find it to be increasingly not to be the case, now that we have computers with multiple Giga Hz and hundreds of Mega Bytes of RAM. Hell, my present desktop machine's RAM is 50X larger than my first hard drive. This is results in a qualitative difference in programming. One of the really cool things about Python in these modern machines is you can do all sorts of things that previously were virtually impossible. E.g., reading and writing multi megabyte files as a unit and treating them internally as a big string, where previously only line at a time processing was possible. Used to be you'd never think of using "unbounded" strings -- or lists or other large, dynamic structures. Now they're the norm. Or -- in this case -- Python's unbounded queues are useful over a much wider range of conditions than previously thought. Used to be all your elegant little CS algorithms never worked on a real computer because you had to translate them from their ideal world to the real world of extremely limited memory, disk and CPU power. While we may always be machine limited for some applications, I find it delightful that increasingly we can ignore those nasty details, merely write cosmic-simple Python code and have it all work. Really and truly, unbounded Queues seem to me to be the Pythonetic way to go. ;o) >Therefore, I consider your assertion "Generally, Queues never >get *full*" a dangerous over-simplification: they get full >if you specifically define them to have a maximum size (and >post more items than you peel off), > Yes. If you make them too small they will overflow. I was saying DO NOT do this. >and it's not a rare case >to want that ("an optional embellishment", as I said, but one >that does happen quite normally in general cases). > I don't know how to react to your shift in emphasis on this point from mere "optional embellishment" to "dangerous over-simplification". I think you're exaggerating the "danger." What is the "dangerous" outcome you're striving to avoid? I think you were right the first time. >If the number of work requests is not unbounded, > The total number of requests is immaterial. You mean if the arrival rate is sufficiently high or the processing time too long. >you may be >thrashing your computer into disgraceful performance rather >than having your program fail with an exception -- wasting >unbounded amounts of memory on an unbounded queue, > Yes, I acknowledged that your system can thrash or fail some other way if you don't have enough power to process the requests. >where a >single, simple call to make it bounded would solve it all >like magic. > Magic sounds good but what about the time-critical requests that don't get serviced in time? Bounded queues are A solution to some problems but not The solution for all situations. And as I said, they push part of the problem to some other place in the design, which may or may not be a good thing. >>Anyway, I felt the "general" case was more applicable to this novice's >>line of questioning. He/she already was confounded by some >>non-essential details. >> >> > >We disagree on didactics. I think over-simplification is a >bad way to teach: everything must be kept as simple as possible, >*but no simpler than that*. > Is it my turn to retort with a Monsieur de La Palice allusion? Actually, it sounds like we agree on didactics but disagree on exactly where to draw the line. And I don't see that we're all that far apart. I'd be curious to hear Robin's opinion on the matter. I also sense that I've somehow done something to piss you off. I'm sorry if I did but I can't think what it would have been. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From maciej at maciejsobczak.com Tue Sep 17 13:20:50 2002 From: maciej at maciejsobczak.com (Maciej Sobczak) Date: Tue, 17 Sep 2002 19:20:50 +0200 Subject: Socket server and threads References: <1032217212.2735.21.camel@caspian.everglade> Message-ID: Hi, "Rob Brown-Bayliss" wrote in message news:mailman.1032223099.23141.python-list at python.org... > > Hi, I am trying to write an app. it Has a gui, and I am using xmlrpc via > socket server to communicate with other apps on other machines. I envite you to try this library: http://www.maciejsobczak.com/prog/yami/ You can go directly to: http://www.maciejsobczak.com/prog/yami/impl/index.html#python It uses sockets to provide object-based communication abstraction for C, C++, Tcl and Python. It can greatly simplify your code (including threading issues), unless you need to use some specific protocol for some reason. Note that there is work in progress on 2.0 version. Do not hesitate to contact me if you have any questions. Cheers, -- Maciej Sobczak http://www.maciejsobczak.com/ From mhammond at skippinet.com.au Mon Sep 23 20:12:41 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 24 Sep 2002 00:12:41 GMT Subject: COM: Returning IDispatch or NULL References: Message-ID: Juan Carlos CORU?A wrote: > Hello, > > I'm trying to develop a COM Server in python, that has a method that > returns an IDispatch object but sometimes it must return nothing. See > the following example programmed in C/SIDE (Microsoft Navision > Financials ERP): > > ---> > otherCOMServer := COMServer.returnOtherCOMServer(); > IF ISCLEAR(otherCOMServer) THEN MESSAGE('otherCOMServer is clear'); > <---- > > Definition of ISCLEAR (extracted from MS Navision help): > The return value is TRUE if: > -the automation variable has not been created. See CREATE. > -the automation variable has been cleared. See CLEAR. > -the automation variable has been assigned NULL by an automation > server. > > I thing that in this case I must assign NULL to the otherCOMServer > variable in order to keep the otherCOMServer variable CLEARED. > What must I return from "COMServer.returnOtherCOMServer()" method to > assign NULL? > I have tried: > return None > return wrap(None) > return 1==0 > return > > but without success. The environment responds "data type not > supported". None is the way to do this. What responds "data type not supported"? Have you registered your object for debugging and seen the output? There may be a traceback printed. Mark. From peter at engcorp.com Thu Sep 19 07:36:09 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 19 Sep 2002 07:36:09 -0400 Subject: StructuredText -> HTML module?? References: Message-ID: <3d89b69d$1@news.sentex.net> Thomas Weholt wrote: > Need a module to parse StructuredText/Wiki into HTML. Looked at PyWiki, but > the generated code was not what I expected. Does anybody have module or lib > to do this? Maybe you could help us by telling us *what* you expected. Otherwise we're likely to waste our time making suggestions that are just as inadequate from your point of view. (For example, ZWiki... or the Zope structured text stuff.) -Peter From peter at engcorp.com Wed Sep 4 22:37:05 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 04 Sep 2002 22:37:05 -0400 Subject: default tuple unpacking? References: <3d758180$1@news.sentex.net> <3d7584d2$1@news.sentex.net> <6qd6rtdg0e.fsf@thetis.intevation.de> Message-ID: <3d76c336$1@news.sentex.net> Bernhard Herzog wrote: > Peter Hansen writes: > > >>Hmm... I think there might be an inconsistency or an unexpected >>result in this. What if e already contains a tuple? >> >> e = (1, 2, 3) >> *a = e # a is ((1, 2, 3), ) >> >>That seems sensible, and it's just what happens if you pass >>"e" in to a function defined as "def func(*a)". > > No it isn't. If you call func as func(e) the tuple being unpacked into > the function's parameters is (e,) not e. So the situation is more like > calling func as func(*e) so that *a = e would be the same as a = e or > perhaps a = tuple(e) Quite right... my mistake. >>Now what about this: >> >> a, *b = e # a is 1, b is (2, 3) >> >>That's one possible result, and presumably the one you want with >>this syntax, but it's not what you'd get with the function syntax: >> >> def func(a, *b): >> print a >> print b >> >> func(e) > > > Again the tuple being upacked to a, *b is (e,)... > >>Here of course you get (1, 2, 3) in "a" and () in b. > > ... so this is obviously what you should get. A sign that even when one can use these effectively in programs, one can be confused by the arbitrary choice of syntax when talking about it. Thanks for the corrections. -Peter From peter at engcorp.com Wed Sep 18 00:07:37 2002 From: peter at engcorp.com (Peter Hansen) Date: Wed, 18 Sep 2002 00:07:37 -0400 Subject: can wxpython do this? References: <737aefee.0209151702.3f735252@posting.google.com> <3d854b44@news.sentex.net> Message-ID: <3d87fbfc@news.sentex.net> Erick wrote: > > A better option, although I haven't tried it myself, would be > > to use py2exe to build an executable, then package that up > > thanks Peter, but I was talking about something cross-platform. As py2exe's > page says: > > py2exe is a distutils extension to convert python scripts into > executable windows programs, which are able to run without > requiring a python installation. > > > do you know if it works across platforms? I don't believe the current solutions are cross-platform, but it could be feasible to build a meta-packager which uses the appropriate package to build executables for different platforms by calling on the appropriate platform-dependent packager. Anyway, do you really want all platforms, or a specific subset? -Peter From jacek.generowicz at cern.ch Mon Sep 23 08:00:45 2002 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 23 Sep 2002 14:00:45 +0200 Subject: Python Compiling References: Message-ID: loewis at informatik.hu-berlin.de (Martin v. L?wis) writes: > The question is: why do you want to have a compiler? Using it is much > more difficult than an interpreter, and more time-consuming during > development of an application. People often expect significant speed > increases from compilation, but it turns out that those don't > materialize. How would you reconcile the above statements in context of Common Lisp compilers ? For example, working with the CMU Common Lisp compiler (which, funnily enough, is called Python, and compiles to native code), should provide a practical demonstration that your statements are, how shall I put it ... not entirely true. Specifically: 1) Compiling your code with CMUCL is no more difficult than leaving the code uncompiled. 2) It is not more time consuming (on any significant scale - by which I mean that a human rarely notices the time-taken-to-compile during a normal coding-testing-debugging session). 3) Significant speed increases (wrt the uncompiled code) are usually observed. From alanmk at hotmail.com Mon Sep 23 17:03:02 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: 23 Sep 2002 14:03:02 -0700 Subject: Strange values in Accept-Language header? Message-ID: Dear all, I know that this is not quite the correct place to post this question, but I'm not sure where else to go with it (suggestions? nice ones :-). And I know that there are plenty of web developers/masters here, and they might be interested..... On looking at my server logs for the Accept-Language headers (to answer another post in this group), I came across some strange values that are definitely not ISO language codes. For example, Accept-Language: en-us,x-ns1rDGeT4e2FpA,x-ns2f67971hgDw1 Accept-Language: x-ns13V8cN8S1Xz9,x-ns2T329gfxKa7d I have no idea what these could mean (I've changed the actual values BTW, on the remote off-chance that somebody's highly personal information was coded in there) They are obviously not meant to convey language preferences, in a general sense. Perhaps they are A: A method of communicating language preference between bespoke clients/servers coded to recognise them? B: An experimental method of communicating language preferences which has yet to be standardised? C: The result of header anonymization through some form of anonymising proxy? (why bother?) D: Some form of cracking attempt involving a buffer-overrun vulnerability? E: A secret "digital handshake" for the Python Secret Underground ;-) None of the search engines turned up anything relevant. Stumped, Alan. From timh at zute.net Tue Sep 24 09:10:13 2002 From: timh at zute.net (Tim Hoffman) Date: Tue, 24 Sep 2002 21:10:13 +0800 Subject: Saving & Restoring Python objects in XML? References: <3D8F7800.F757A72D@wyeth.gsfc.nasa.gov> Message-ID: <3D906435.2030304@zute.net> Hi Zope does this, you may like to have a look at the export code in zope, to get some ideas. Tim Tom Bridgman wrote: > Hello, > > I'm setting up some codes where I want to save the state of the code in > an XML file at some time and reload it later to continue the processing. > > It's relatively easy to save out the innards of Python objects into XML > regardless of how the objects are nested. But what about loading this > state information back in from the XML file? > > Is there a way to write the parser handlers and/or other components (I'm > using PyXML 0.7 and higher) such that they can assemble the required > objects as they read in the file? I'm wondering if there is an elegant > solution that might not be immediately obvious from the 'brute force' > method I keep coming up with. I'd prefer to do this using SAX (since > I've worked with it some), but using DOM is not out of the question if > it solves the problem in a straightforward way. > > Thanks, > Tom > -- > Dr. William T."Tom" Bridgman Scientific Visualization Studio > Global Science & Technology, Inc. NASA/Goddard Space Flight Center > Email: bridgman at wyeth.gsfc.nasa.gov Code 935 > Phone: 301-286-1346 Greenbelt, MD 20771 > FAX: TBD http://svs.gsfc.nasa.gov/ From Padraig at Linux.ie Mon Sep 16 11:24:09 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Mon, 16 Sep 2002 15:24:09 GMT Subject: python performance References: <3D84E66F.6020701@linux.ie> Message-ID: Syver Enstad wrote: > loewis at informatik.hu-berlin.de (Martin v. L?wis) writes: > > >>Padraig Brady writes: >> >> >>>>Calling functions adds overhead. Running code within functions >>>>reduces overhead for object access. >>> >>>Ah OK, this because it has to search a smaller namespace? >> >>No. Inside a function, local variables are accessed with integer >>indices, instead of by name. This is possible because there is static >>knowledge about the local variables in a function. >> >> >>>Wouldn't compiling overcome this? >> >>Not if you want to preserve Python semantics; the compiler would need >>to emit code that performs the same actions that the interpreter >>currently does. > > What about Psyco? Interesting. I wonder why something like this isn't done when creating pyc files, hmm I suppose it would be non portable. Anyway it didn't help for my very simple program. Well it seemed to make the timings more volatile (a few microseconds each side of the previous measurements). P?draig. From dsavitsk at e-coli.net Tue Sep 17 00:46:44 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Tue, 17 Sep 2002 04:46:44 GMT Subject: More on Protecting Source Code References: Message-ID: "David LeBlanc" wrote in message news:mailman.1032232999.22661.python-list at python.org... > I have read what I consider to be the narrow minded and short sighted views > wrt to protecting IP in the form of Python source code, and I would like to > make a few points. > > * Not everyone believes that all or most software ought to be free. I for > one, don't. > > * Owners of property have the right to control it. If you disagree and own a > nice car or house, I'll be right over :-> > > * Why invest a substantial amount of time and money developing in a language > that makes it trivial to gain access to the work product? > > Python may be easy to use, but if it's also easy to steal software written > in it, that's an impediment to it's being widely used in commercial > products, especially shrink-wrapped products. Perhaps that's a reason why > there seems to be so few commercial products in Python, beyond those that > are fairly closely licensed and/or have substantial parts of the app written > in C/C++. > > I suppose one solution is to modify the Python interpreter with different > op-codes and that ought to make it somewhat painful for the average hacker. > A better solution is to make a .pyc file approximately as hard as a binary > .exe file to decompile - however that could be done. > > David LeBlanc > Seattle, WA USA > I agree that some things should not be open source, but at some point, however obfuscating the source seems like the wrong way. In truth most homes, and all cars, are trivial to break into. Yet we still park on the street relying on our neighbors to respect the law. In the same way, a software license should be enough to stop theft. Further, there are daily calls in newsgroups requesting decompilers to recover lost source code. I am comforted knowing that as long as it runs I can get it back. I trust my users to respect my rules for software I develop. Perhaps for widely distributed projects Python is not the proper choice. But no single tool is always appropriate, and for times that one can expect some level or honesty, Python works. -doug From LogiplexSoftware at earthlink.net Fri Sep 20 08:17:14 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 20 Sep 2002 05:17:14 -0700 Subject: Source code In-Reply-To: <3D88B0E6.AC08EC27@crary.com> References: <3D88B0E6.AC08EC27@crary.com> Message-ID: <1032524234.2820.26.camel@localhost.localdomain> On Wed, 2002-09-18 at 09:59, Bradley D. Larson wrote: > I might have missed it... (I read most of the posts on this subject). > Why not just use a significant info registration key. The registration > key would be sensative to date, registered name and/or some other > piece of information that would be required to get the software to work. The problem with this approach is that, by decompiling the software, these protections can be easily found and removed. -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From jolsen at mailme.dk Tue Sep 10 03:01:39 2002 From: jolsen at mailme.dk (Jesper Olsen) Date: 10 Sep 2002 00:01:39 -0700 Subject: Graph algorithms - minimisation Message-ID: Do you know of python extentions that implement efficient graph algorithms? In particular I am interested in minimising the number of nodes & arcs used for representing directed graphs. If you know of implementations in other languages than python - e.g. C/C++, I am interested as well. Cheers Jesper From sandorlevi at yahoo.com Thu Sep 26 07:54:17 2002 From: sandorlevi at yahoo.com (Levente Sandor) Date: 26 Sep 2002 04:54:17 -0700 Subject: Dynamic Event Handling in wxPython References: Message-ID: <8b5e42a6.0209260354.3a419f40@posting.google.com> Try this: def OnMenuSelection(event): id = event.GetId() # ...your code here... ---- levi "Mikey at Work" wrote in message news:... > I'm trying to design a menu in wxPython that connects to an SQL server to > get its menu commands. So far, I've been able to display the records from > the SQL server in the menu. The problem, however, occurs when I try to > connect event handlers to the menu items. I know how to connect the event > handlers (I'm either going to use EVT_MENU_RANGE or assign a EVT_MENU to > each menu item when the items refresh from the server), but the function > called by the event handler has no way of determining the id of the menu > item (at least as far as I know). > > If I use... > > EVT_MENU_RANGE(lowID, highID, OnMenuSelection) > > ... OnMenuSelection doesn't know which menu item was selected. Is there a > way to pass the menu item's id to the function OnMenuSelection or retrieve > the id in the function? Thanks for your help. I'm sorry if some of my > terminology is off -- I'm kinda new to Python and programming in general. From steve at ferg.org Fri Sep 13 09:03:37 2002 From: steve at ferg.org (Stephen Ferg) Date: 13 Sep 2002 06:03:37 -0700 Subject: [newbie] Buying an introductory/reference text References: Message-ID: > I believe that "Python: Essential Reference" is about all you need if you > have programmed in at least one other language. Top notch book. Absolutely! For a very clear and readable introduction, rather than a reference manual, I suggest "The Quick Python Book" by Daryl Harms. From Janssen at rz.uni-frankfurt.de Mon Sep 16 18:39:40 2002 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Tue, 17 Sep 2002 00:39:40 +0200 Subject: pickle magically not working Message-ID: <3d865dac@nntp.server.uni-frankfurt.de> Hello at least i've solved it (as a workaround), but it's pretty annoying. Maybe someone has an answere :-) i wanted to pickle a dictionary. The code was fine on my own maschine but throwing RuntimeError: "maximum recursion depth exceeded" on other maschines (same Linux, same Python-Version 2.2). The mindthrilling thing was (and is), that i can copy the dictionary content with mouse2 into a working dictionary. Original dic still refused working. Have a look: m is a single-key version of the bad dic. mm is hand-made >>> m == mm 1 >>> m {(2002, 9, 16, 0, 0, 0, 0, 259, 1): {'virus': 1, 'batches': 186, 'scan': 152, 'mail': 307, 'spam': 0, 'bytes': 6213773}} >>> mm {(2002, 9, 16, 0, 0, 0, 0, 259, 1): {'virus': 1, 'batches': 186, 'spam': 0, 'mail': 307, 'scan': 152, 'bytes': 6213773}} >>> try: pickle.dump(m, fo); print "functional" ... except RuntimeError: print "not functional" ... not functional >>> try: pickle.dump(mm, fo); print "functional" ... except RuntimeError: print "not functional" ... functional copy.copy or copiing via: d = {} for key in dump_dic.keys(): d[key] = dump_dic[key] doesn't help. finally i've improved ;-) the copiing-code to: d = {} for key in dump_dic.keys(): d[key[:]] = dump_dic[key] i.e. making copies of the keys (which are tupel as returned by time.localtime(), by the way). Pickling is now functional, but the question remains: *what can cause this???* Furthermore: is there a way to examine somewhat deep data-structure, or is it more reliable to blame voodoo and "computer-logik" for this ;-) Michael PS: Don't ask me, how i've build those nasty dics. Hundreds lines of slightly confused code have done it ;-) From sismex01 at hebmex.com Fri Sep 13 09:34:18 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 13 Sep 2002 08:34:18 -0500 Subject: [ANN] PySQLite 0.3.0 released Message-ID: > -----Original Message----- > From: Bob X [mailto:bobx at linuxmail.org] > Sent: Thursday, September 12, 2002 8:19 PM > To: python-list at python.org > Subject: Re: [ANN] PySQLite 0.3.0 released > > > Gerhard H?ring wrote: > > NAME: > > pysqlite - Extension module for SQLite databases. > > > > ...[snip] > > Windows binary? > Yeesh! You had to quote the whole message just to add two words? :-( -gus -- -- Please disregard offensive and arrogant corporate -- legalese at end of this message. -- Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From henrik.motakef at web.de Fri Sep 27 17:54:42 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 27 Sep 2002 23:54:42 +0200 Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> <3D934C5C.4000603@mxm.dk> <20020926.130938.1789366143.1524@cybermesa.com> <3D94BFAB.5060506@sschwarzer.net> Message-ID: <87znu3t7x9.fsf@pokey.henrik-motakef.de> Stefan Schwarzer writes: > Tim Hochberg wrote: > > "Jay O'Connor" wrote: > >>How about "underder"?? > > > > Or maybe "dunder"? > > I think, you shouldn't use two words which sound very similar when > spoken. IRL, I tend not to speak __ at all, I just say "def init self...". For the rare cases when I have to make a distinction between, say, __foo__ and foo, I use stuff like "special foo" for "__foo__", "private foo" for "__foo" or "protected foo" for "_foo". But that is usually followed by a remark that one should really invent better names ASAP. From fredp at mygale.org.nospam Wed Sep 18 08:53:54 2002 From: fredp at mygale.org.nospam (Fred Pacquier) Date: 18 Sep 2002 12:53:54 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <6_Ph9.479711$q53.16315681@twister.austin.rr.com> <3d8868b1$0$28683@echo-01.iinet.net.au> Message-ID: "Rob Hall" said : > I settled on wx for the following reasons... > - I needed to settle on something, and pretty soon > - wx has a native look and feel > - wx is fast - compiled C++, whereas tkinter is a script. I found it > - to be > almost unacceptably slow in some instances. > - PythonCardPrototype would simplify things even further. not "would" -- "does" :-) -- YAFAP : http://www.multimania.com/fredp/ From PoulsenL at capanalysis.com Thu Sep 5 14:22:43 2002 From: PoulsenL at capanalysis.com (PoulsenL at capanalysis.com) Date: Thu, 5 Sep 2002 14:22:43 -0400 Subject: Psycos and Pyros don't seem to play well together Message-ID: <72F73B808A78D511A73600034771D9FF717EB7@dc_exchange2.howrey.com> I am working on a distributed application using Pyro that I thought would benefit from Psyco. All is well until I add "from psyco.classes import *" and then it gives me some Pyro based error messages (be happy to send them along if requested) when I launch the client. I am using the "quickstart" method to get my objects up and running on Pyro quickly. Anyone try to use these two modules together before? What were your results? Thanks, Loren From pinard at iro.umontreal.ca Wed Sep 4 18:04:15 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Wed, 04 Sep 2002 18:04:15 -0400 Subject: Garbage collection slowdown? [was: Re: efficient list merging] In-Reply-To: (Eric Brunel's message of "Wed, 4 Sep 2002 17:56:38 +0200") References: Message-ID: Hi! Curious about timings, I played with some of the suggestions from the "efficient list merging" thread, but not considering lists of lists. I am surprised by the impressive slowdown coming from leaving the garbage collector enabled. Here are a few results: 0.51 gc-on 0.34 gc-off 1.50 ratio test_comprehension 0.52 gc-on 0.37 gc-off 1.41 ratio test_zip_and_update 0.43 gc-on 0.29 gc-off 1.48 ratio test_zip_with_none 0.51 gc-on 0.28 gc-off 1.82 ratio test_zip_with_self Here is the testing code. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: xx.py URL: -------------- next part -------------- -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From dwelch91 at nospam.attbi.com Mon Sep 2 18:04:13 2002 From: dwelch91 at nospam.attbi.com (djw) Date: Mon, 02 Sep 2002 22:04:13 GMT Subject: Why it is so dramatical? References: <200209021107.25761.b.maryniuk@forbis.lt> Message-ID: <3D73E035.2040300@nospam.attbi.com> holger krekel wrote: > Bo M. Maryniuck wrote: > >>The task: >> Adding a text to a text. >> >>The problem: >> It is tragically slow to add string to huge string. > > > That's because strings are immutable objects. When you issue > > somestring += otherstring > > a new string object is allocated where the contents of > somestring and otherstring are copied in. Then the > name 'somestring' is bound to this new string. > > If you have something like this in a loop it's often > *much* better to work with a list and later do a > > "".join(stringlist) > > As you observed yourself this is around 100-1000 times faster. > > And consider: if strings were not immutable but modified in-place > (like lists) you couldn't use them as dictionary keys. > > if-it-hurts-don't-do-it-ly, yours Holger > Stupid question: If ""join() is 100-1000 X faster, why doesn't the Python interperter translate s = s1 + s2 + ... into s = "".join( [ s1, s2, ... ] ) automatically? Just curious... D From eric.brunel at pragmadev.com Fri Sep 20 10:43:45 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Fri, 20 Sep 2002 16:43:45 +0200 Subject: Setting cursor colors in tkinter References: Message-ID: Edward K. Ream wrote: > Hi, > > I would like to set the foreground an background colors of a cursor. > > Following: > > http://www.tcl.tk/man/tcl8.3/TkLib/GetCursor.htm#M4 > > I am synthesizing a cursor description with > > cursor="xterm " + fg + " " + bg > > yielding, e.g., > > cursor = "xterm red green" > > I then call: > > body.configure(cursor=cursor) > > However, Tcl complains: > > self.tk.call((self._w, 'configure') > TclError: bad cursor spec "xterm red green" > > Can anyone say how this should properly be done? Put another way, I may > be asking what the proper format of > > "name [fgColor [bgColor]]" > > is in the URL above. What platform are you on? On Linux, doing: from Tkinter import * root = Tk() root.configure(cursor='xterm red green') doesn't produce an error. The colours seem to to be taken into account, but the xterm cursor isn't really a good example. I tried root.configure(cursor='gumby red green') and the result was what I expected. Maybe there are some issues on Windows? -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From marklists at mceahern.com Fri Sep 6 18:11:37 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 6 Sep 2002 17:11:37 -0500 Subject: Larry Wall's comment on python... In-Reply-To: <200209062206.g86M6UVm092251@mail.hcsmail.com> Message-ID: [mmaddox at hcsmail.com] > Although this layout may be considered more elegant from a > readability standpoint, it's the enforcement of the layout that is > irritating to the more Libertarian of us. It's a mindset difference > similar to that between Pascal and C++. So does the fact that C++ forces you to use { } as block delimiters irritate the Libertarian in you? // m - From peter at engcorp.com Mon Sep 16 22:00:59 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 16 Sep 2002 22:00:59 -0400 Subject: Source code References: Message-ID: <3d868ccc$1@news.sentex.net> Cliff Wells wrote: > On Mon, 2002-09-16 at 13:17, BT wrote: > >>Ok, let's say I make a software in two years and I market it on internet. >>The software is good and sell some copy. >>You find the software, like it, change the name, add some feature and resell >>it. My time: 2 years, yours: 1 month. > > And that would be illegal, hence the suggestion to *copyright* your > work. Just a note about the copyright issue, as I agree with most of the comments about the futility of spending much, and often any, effort obscuring the source. (There are disassemblers for almost any processor on the planet, and most of the value is not in the code anyway, but in the more concrete representations of the requirements behind the program, such as the user interface designs and the overall feature set.) Copyright is actually a passive thing now, as opposed to active. That is, you don't have "to copyright your work", because unless you explicitly disclaim the copyright, you automatically get it. As I recall, this was not always the case in at least the U.S., but has been the case for a number of years now. In other words, if you don't write something like "placed in the public domain" then you still have copyright on it and could take steps in courts of law to recover lost income if someone else attempts to profit from your work without permission. There *are* steps you can take that are considered by some to increase the strength of the copyright (registering it officially and so forth), but others believe this is mostly a waste of time. The usual disclaimers about lawyers and advice on Usenet apply... -Peter From kowald at molgen.mpg.de Tue Sep 3 05:22:26 2002 From: kowald at molgen.mpg.de (Axel Kowald) Date: Tue, 03 Sep 2002 11:22:26 +0200 Subject: string reading bug in ActiveState Python 2.2 ? References: <3D74757D.1010405@molgen.mpg.de> Message-ID: <3D747F52.4080101@molgen.mpg.de> Of course, binary mode !! How stupid of me. Many thanks to all, Axel From ark at research.att.com Tue Sep 3 23:21:36 2002 From: ark at research.att.com (Andrew Koenig) Date: Wed, 4 Sep 2002 03:21:36 GMT Subject: Memory fault - core dumped while compiling 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> Message-ID: Anton> Any ideas? Looks like the same symptom I had. If you are using binutils 2.13, try going back to 2.12.1 and see if that fixes the problem. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From aleax at aleax.it Thu Sep 26 08:31:10 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 12:31:10 GMT Subject: How to send Email using Python? References: Message-ID: Ken wrote: > Hi all, I like to know how to send a HTML featured Email from Python? I > know how to do a text based version using SMTPLib, but not sure how to do > it with a HTML featured Email. Can someone help me? Can someone provide me > with sample code? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/67083 or, of course, the edited and enhanced version thereof we prepared for O'Reilly's paper-edition of the Python Cookbook (I know you can download all of the printed coobook's recipes' code from O'Reilly's site, but don't have the exact URL for that at hand). Alex From brendon.co at asia.bigfoot.com Thu Sep 19 05:07:48 2002 From: brendon.co at asia.bigfoot.com (dd) Date: 19 Sep 2002 02:07:48 -0700 Subject: execfile syntax & zope error Message-ID: Hi, Im having problem using execfile. Using execfile('filename.exe') on zope for web purpose, generate an error: An error has occurred. The Site Admistrator has been notified. global name 'execfile' is not defined and Traceback (innermost last) should I import something on python like: import sys execfile('filename.exe') but this gives me an error, refer above..... Any help...thanks dd From aleax at aleax.it Wed Sep 18 12:21:19 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 16:21:19 GMT Subject: Copy with __slots__ References: Message-ID: <3K1i9.110352$ub2.2335897@news1.tin.it> Griebel, Peer wrote: ... > I'm using Python 2.2 (Cygwin). There I don't get the exception you > mentioned. > >> This is with Python 2.2.1 -- as you see, it doesn't get anywhere I suggest you upgrade to Python 2.2.1 -- it has enhancements such as this one, which help a lot. >> class C2(C1): >> __slots__ = "s2" >> def __copy__(self): >> x = self.__class__() >> x.s1 = self.s1 >> x.s2 = self.s2 >> return x > > Yes I know this works. But this hat two drawbacks (at least in my eyes): > > 1. Formerly I used the approach of copy: I simply updated the dict of a > newly created empty object. This is fast and works well - but not with the > new classes. I think your approach runs much more slowly. It's of course not a matter of new vs old classes -- new classes would let you use the dictionary-update method just as well... as long as you didn't use __slots__. Regarding performance -- *measure* things, man! Intuition about what runs slowly, what rapidly, is notoriously misleading. E.g.: import time, copy class noslots(object): pass class withslots(object): __slots__ = 's1', 's2' def __copy__(self): result = self.__class__.__new__(self.__class__) result.s1 = self.s1 result.s2 = self.s2 return result x1 = noslots() x1.s1 = 23 x1.s2 = 'bebop' x2 = withslots() x2.s1 = 23 x2.s2 = 'bebop' repetitions = [None] * 10000 def copyalot(x): start = time.clock() for i in repetitions: copy.copy(x) stend = time.clock() return '%.2f %s' % (stend-start, x.__class__.__name__) for x in x1, x2: print copyalot(x) [alex at lancelot ~]$ python -O slorno.py 1.04 noslots 0.29 withslots "much more slowly", hmm...? Looks over 3 times faster to *ME*... > 2. The approach is error prone. When simply updating a dict I'm not going > to miss a newly added attribute. But using your method I have to remember > the method whenever I add an attribute. Yes, that IS part of the price you pay for getting the optimization that __slots__ affords: you do have to know exactly what you're doing. Thus, __slots__ should be used when the program is working, in the optimization phase, for classes such that saving a __dict__ per instance IS an important optimization, only (classes of which MANY instances exist, basically). At the price of a small slow-down, if the __slots__ are all defined in the current class, you can safeguard against this, e.g.: class withslots(object): __slots__ = 's1', 's2' def __copy__(self): result = self.__class__.__new__(self.__class__) for s in self.__slots__: setattr(result, s, getattr(self, s)) return result This slows my timing test down from 0.29 to about 0.36. If you must also consider _inherited_ slots, e.g; class withslots_base(object): __slots__ = ('s1',) class yetanother(withslots_base): pass class withslots(yetanother): __slots__ = ('s2',) def __copy__(self): result = self.__class__.__new__(self.__class__) for base in self.__class__.__mro__: for s in getattr(base, '__slots__', []): setattr(result, s, getattr(self, s)) return result the slowdown is even more severe -- to 0.62. Still nothing like the 1.04 you pay for NOT having the slots at all, of course, but it's starting to undermine performance improvement, the only real rationale for having __slots__ at all. Still, you pays your money, and you makes your choices. >> The way to cover copy.copy, copy.deepcopy AND pickle is to have the >> class supply a special method __reduce__. __reduce__ can return a >> pair where the first item is callable, the second item is the tuple >> to pass as arguments to the first. Thus, for example: > > Here once again I have the two disadvantages mentioned above. You mis-count, I think. You have only one disadvantage: you have to write more code and decide how fail-safe you want it to be wrt changes to __slots__ in the inheritance hierarchy, depending on whether you need just a LITTLE optimization wrt not using __slots__, or really crave for all you can get. The advantage is the optimization. The disadvantage is that you have to write more code, with some care, to get the optimization, particularly if you also want flexibility (more optimization, of course, is gained by foregoing flexibility and nailing things down). That's how MOST optimization activities work, in my experience. Is yours so different? > Yes this would work. But I'm looking for speed (as you already abserved). > And my constructor is a little more heavy weight. So it is much faster to > use the old mechanism (update dict) than always calling the constructor. So, write that little extra factory function -- that's hardly the problem! The ability to reuse the constructor is just a handy work-saver when feasible, as it often is. > Thanks Alex! You're welcome. > I'm still in hope to find a fast and secure solution... I think you need to choose your preferred tradeoff point between 'fast' and 'handy'. It's not a matter of security -- none of these solutions run higher security risks than others -- it's that handiness, flexibility and other admirable qualities (including ease of changing the software later) ARE more often than not things you can sacrifice if and when you really need to increase performance. Alex From s3v3n3v3s73 at yahoo.com Mon Sep 16 02:17:51 2002 From: s3v3n3v3s73 at yahoo.com (7) Date: 15 Sep 2002 23:17:51 -0700 Subject: basic question Message-ID: I am using Pythonwin. How can I always make sure when I make a change to a script and save it, that when I go to run it, that I run the changed version. I know there is a very basic answer, this has been getting to me. Thanks in advance. From whisper at oz.net Fri Sep 6 16:56:07 2002 From: whisper at oz.net (David LeBlanc) Date: Fri, 6 Sep 2002 13:56:07 -0700 Subject: Interrupting Python In-Reply-To: Message-ID: > I have a script that can run, accessing network resources, for > several days. > Since the script does not normally need keyed input, exception processing > does not raise the keyboard exception until after the program > ends normally. > I would like to be able to interrupt if from the keyboard, but have not > learned the trick. How can I do this? > > -- > Bob Easton I have had the experience of Python progs not responding to ctrl-c or ctrl-d on Windows, but I found that ctrl-break works every time. Dave LeBlanc From lbrannma at cablespeed.com Sun Sep 22 15:32:47 2002 From: lbrannma at cablespeed.com (Lance) Date: Sun, 22 Sep 2002 12:32:47 -0700 Subject: send to Mitya Message-ID: 9.2 Python Scopes and Name Spaces Before introducing classes, I first have to tell you something about Python's scope rules. Class definitions play some neat tricks with namespaces, and you need to know how scopes and namespaces work to fully understand what's going on. Incidentally, knowledge about this subject is useful for any advanced Python programmer. Let's begin with some definitions. A namespace is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries, but that's normally not noticeable in any way (except for performance), and it may change in the future. Examples of namespaces are: the set of built-in names (functions such as abs(), and built-in exception names); the global names in a module; and the local names in a function invocation. In a sense the set of attributes of an object also form a namespace. The important thing to know about namespaces is that there is absolutely no relation between names in different namespaces; for instance, two different modules may both define a function ``maximize'' without confusion -- users of the modules must prefix it with the module name. By the way, I use the word attribute for any name following a dot -- for example, in the expression z.real, real is an attribute of the object z. Strictly speaking, references to names in modules are attribute references: in the expression modname.funcname, modname is a module object and funcname is an attribute of it. In this case there happens to be a straightforward mapping between the module's attributes and the global names defined in the module: they share the same namespace! 9.1 Attributes may be read-only or writable. In the latter case, assignment to attributes is possible. Module attributes are writable: you can write "modname.the_answer = 42". Writable attributes may also be deleted with the del statement. For example, "del modname.the_answer" will remove the attribute the_answer from the object named by modname. Name spaces are created at different moments and have different lifetimes. The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits. The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called __main__, so they have their own global namespace. (The built-in names actually also live in a module; this is called __builtin__.) The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function. (Actually, forgetting would be a better way to describe what actually happens.) Of course, recursive invocations each have their own local namespace. A scope is a textual region of a Python program where a namespace is directly accessible. ``Directly accessible'' here means that an unqualified reference to a name attempts to find the name in the namespace. Although scopes are determined statically, they are used dynamically. At any time during execution, exactly three nested scopes are in use (exactly three namespaces are directly accessible): the innermost scope, which is searched first, contains the local names, the middle scope, searched next, contains the current module's global names, and the outermost scope (searched last) is the namespace containing built-in names. Usually, the local scope references the local names of the (textually) current function. Outside of functions, the local scope references the same namespace as the global scope: the module's namespace. Class definitions place yet another namespace in the local scope. It is important to realize that scopes are determined textually: the global scope of a function defined in a module is that module's namespace, no matter from where or by what alias the function is called. On the other hand, the actual search for names is done dynamically, at run time -- however, the language definition is evolving towards static name resolution, at ``compile'' time, so don't rely on dynamic name resolution! (In fact, local variables are already determined statically.) A special quirk of Python is that assignments always go into the innermost scope. Assignments do not copy data -- they just bind names to objects. The same is true for deletions: the statement "del x" removes the binding of x from the namespace referenced by the local scope. In fact, all operations that introduce new names use the local scope: in particular, import statements and function definitions bind the module or function name in the local scope. (The global statement can be used to indicate that particular variables live in the global scope.) 9.3 A First Look at Classes Classes introduce a little bit of new syntax, three new object types, and some new semantics. 9.3.1 Class Definition Syntax The simplest form of class definition looks like this: class ClassName: . . . Class definitions, like function definitions (def statements) must be executed before they have any effect. (You could conceivably place a class definition in a branch of an if statement, or inside a function.) In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful -- we'll come back to this later. The function definitions inside a class normally have a peculiar form of argument list, dictated by the calling conventions for methods -- again, this is explained later. When a class definition is entered, a new namespace is created, and used as the local scope -- thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here. When a class definition is left normally (via the end), a class object is created. This is basically a wrapper around the contents of the namespace created by the class definition; we'll learn more about class objects in the next section. The original local scope (the one in effect just before the class definitions was entered) is reinstated, and the class object is bound here to the class name given in the class definition header (ClassName in the example). From ianholmes01 at lycos.com Fri Sep 6 08:10:00 2002 From: ianholmes01 at lycos.com (Ian Holmes) Date: 6 Sep 2002 05:10:00 -0700 Subject: Python "compiler" is too slow for processing large data files??? References: Message-ID: "Ron Horn" wrote in message news:... > test on my Windows 2000 machine, 1.5GHz, Pentium 4: > > C:\test>python compiletest.py 8000 10 comp.py > C:\test>timer r "python -c \"import comp\"" > 8000 > Time passed: 00:00:09.39 > > C:\test>python compiletest.py 8000 20 comp2.py > C:\test>timer r "python -c \"import comp2\"" > 8000 > Time passed: 00:00:26.47 What else is your p4 running? - it seems to running a tad slow on my celeron 500Mhz win2k 384meg py 2.2.1 runs at 15-17s for 8000x20 and python never got above 2meg (though cpu was at 80-98% through out) Also I imported psyco and proxied the main method which reduced the time to ~6s see below. psyco is available from psyco.sourceforge.net - I imagine that if the other functions are proxied to then it may speed up some more. #modified with psyco and in script timing # gen.py # create a script to generate modules that will stress # out the python compiler a bit? import sys, random, time, psyco def GenLine(numArgs, outfile): outfile.write(" (") for i in range(numArgs): outfile.write("%d, " % random.randint(0,1000)) outfile.write("),\n") def Generate(numLines, numArgs, outfile): outfile.write("list1 = [\n") for i in range(numLines): GenLine(numArgs, outfile) outfile.write("]\n") outfile.write("print len(list1)\n") def main(): outfile = None try: if len(sys.argv) != 4: print "Usage: gen " return numLines = int(sys.argv[1]) numArgs = int(sys.argv[2]) outfile = open(sys.argv[3], 'wt') Generate(numLines, numArgs, outfile) finally: if outfile: outfile.close() if __name__ == "__main__": START_TIME = time.time() mainx = psyco.proxy(main) mainx() print "end",time.time() - START_TIME From oren-py-l at hishome.net Wed Sep 11 01:14:00 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 11 Sep 2002 01:14:00 -0400 Subject: Reset a generator function? In-Reply-To: <%Lrf9.30107$w51.7961593@news2.news.adelphia.net> References: <%Lrf9.30107$w51.7961593@news2.news.adelphia.net> Message-ID: <20020911051359.GA664@hishome.net> On Tue, Sep 10, 2002 at 07:31:07PM +0000, Robert Oschler wrote: > How can I reset a generator function so that it begins yielding values as > it did when first called? You need to call the function again with the same arguments. Assuming that its result depends only on the arguments and that it does not modify them it should regenerate the same sequence. Look at the regen function in http://tothink.com/python/dataflow/xlazy.py It wraps a generator function with a wrapper class that behaves just like the generator function except that its return value is an iterable object instead of an iterator. Each time iter() is called on this object it calls the generator function again with the original arguments. example: >>> from __future__ import generators >>> def f(n): ... for i in xrange(n): ... yield i*10 ... >>> x=f(10) >>> list(x) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] >>> list(x) [] >>> >>> from xlazy import * >>> f = regen(f) >>> >>> x = f(10) >>> list(x) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] >>> list(x) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] >>> Oren From marklists at mceahern.com Tue Sep 17 23:31:36 2002 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 17 Sep 2002 22:31:36 -0500 Subject: Splitting a list of strings In-Reply-To: Message-ID: > Okay. Here is some representative sample data: This does everything except ignore the last attribute--easy enough to add either here or have the caller do it. def getDataAndAttributes2(filename): attrib_prefix = "@" comment_prefix = "%" attributes = [] data = [] f = file(filename) lines = f.readlines() f.close() for line in lines: # Ignore empty lines and comments. line = line.strip() if not line or line.startswith(comment_prefix): continue # Put attributes and data into separate lists. if line.startswith(attrib_prefix): attributes.append(line) else: data.append(line) return data, attributes // m - From kseehof at neuralintegrator.com Tue Sep 3 16:27:53 2002 From: kseehof at neuralintegrator.com (Ken Seehof) Date: Tue, 3 Sep 2002 13:27:53 -0700 Subject: efficient list merging In-Reply-To: Message-ID: > [Peter Saffrey] > > > I have two lists of lists of strings which I would like to merge > > efficiently without repeats. [...] Or is there a better way? > > I am not sure about the relative speed of everything, but I would be > tempted to try: > > dict(zip(list1 + list2, [None] * (len(list1) + len(list2)))).keys() > > It seems to work: > > >>> list1 = list('abcdebxyz') > >>> list2 = list('pqqr') > >>> list1 > ['a', 'b', 'c', 'd', 'e', 'b', 'x', 'y', 'z'] > >>> list2 > ['p', 'q', 'q', 'r'] > >>> dict(zip(list1 + list2, [None] * (len(list1) + len(list2)))).keys() > ['a', 'c', 'b', 'e', 'd', 'q', 'p', 'r', 'y', 'x', 'z'] > > -- > Fran?ois Pinard http://www.iro.umontreal.ca/~pinard This is a bit faster, but assumes that the first list does not initially contain duplicates. It eliminates duplicates that would be introduced by merging items from list2. Also, this maintains the original list order (i.e. list1+list2 without adding duplicates). def merge(list1,list2): d1 = dict(zip(list1,list1)) return list1+[s for s in list2 if s not in d1] - Ken Seehof From anthony_barker at hotmail.com Mon Sep 16 14:34:55 2002 From: anthony_barker at hotmail.com (Anthony_Barker) Date: 16 Sep 2002 11:34:55 -0700 Subject: FYI: Oreilly Programming Python book $6 Message-ID: <899f842.0209161034.1e587611@posting.google.com> For those on a budget - I just picked up Programming Python (note - 1st Edition so parts of it are dated) for $5.99 at http://www.bookcloseouts.com. They have 37 more copies. They also have the pocket reference listed for $3. I don't have anything to do with that company. The order arrived fairly promptly. Anthony http://xminc.com/anthony/ From see_reply_address at something.invalid Mon Sep 2 21:18:52 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Tue, 03 Sep 2002 13:18:52 +1200 Subject: Would you like a Snobol pattern matcher? (Re: Making regex suck less) References: <3d725881.345921@news.t-online.de> Message-ID: <3D740DFC.1040009@something.invalid> John Roth wrote: > http://www.perl.com/pub/a/2002/06/04/apo5.html > > http://www.perl.com/pub/a/2002/08/22/exegesis5.html I just had a brief look at this, and the underlying ideas seem to be a lot like the way Snobol patterns work. Maybe it's time for me to resurrect the Snobol-style pattern matching module that I started on a while back and never got around to releasing. Would anyone be interested in this? Its syntax is similar to that of Plex REs, except that the primitives are Snobol-like, and it uses a backtracking matching algorithm that's much more powerful than a DFA (you can write entire parsers in it, for example). -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From klaus.hoeppner at bigfoot.de Mon Sep 30 08:26:47 2002 From: klaus.hoeppner at bigfoot.de (Klaus Hoeppner) Date: Mon, 30 Sep 2002 14:26:47 +0200 Subject: Find out link location Message-ID: <7uf9na-vd9.ln@lbdb01.gsi.de> Hi, with the os.path module I can use the islink function to check, wether a file is symbolic link. But how can I find out, where the link points to. E.g. if I have readme.txt --> ../packages/mypackage/readme.txt how do I get the "../packages/mypackage/readme.txt" with python? Regards Klaus From peter at engcorp.com Thu Sep 19 20:08:23 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 19 Sep 2002 20:08:23 -0400 Subject: Minimal debug/rep functionality References: Message-ID: <3d8a66ec$1@news.sentex.net> Delaney, Timothy wrote: >>From: Peter Hansen [mailto:peter at engcorp.com] > >>I'm looking forward to seeing your tool though, Timothy. :) > > I'd love it to eventually become part of the core - I *expect* I'll be able > to release it (but of course, it's up to my employer ...). It's doing > everything I want now except for determining exactly which zero-count lines > can be safely ignored (comments, multiline expressions). Oh - and I haven't > got an actual "trace as you go" mode (which is the topic of this thread ;) > but that will be easy to add. And I haven't got any path coverage analysis > yet - the data is captured, but no analysis is performed. And it currently > does a relatively primitive text-only coverage dump. And ... Heh. :-) I'm a commercial Python user as well, so I can imagine the kinds of things your employer think about whether to release or not. We have some items which we simply wouldn't consider releasing, but there are a number of tools which we hope to release at some point. They have similar limitations to yours (well, okay, they're actually much more primitive even than that :-) yet with a little more work they would be useful to others. More helpfully in convincing my own employer that we should release back to the community is pointing out how with our limited resources these tools will always remain primitive and simplistic. If we can do a little more work *and* release them, we stand a chance of seeing them improved by others, and taking advantage of the improvements ourselves. See, it's easy to convince those conservative, selfish minds that they can profit by giving things away. :-) Well, if you can't release it (I guess I just assume from all your mentions of it that it was going to be open), we'll probably be building some of the same types of things ourselves. It would be a real shame if we both (and others) went to all that effort in parallel without sharing. :( -Peter From tim.one at comcast.net Sat Sep 21 01:25:59 2002 From: tim.one at comcast.net (Tim Peters) Date: Sat, 21 Sep 2002 01:25:59 -0400 Subject: e vs exp()? In-Reply-To: Message-ID: [Tim] >> ... The implementation of a decent x**y function is one >> of the> most difficult tasks in a platform's math library.... >> I've written such a beast without benefit of an extended hardware >> precision; I wouldn't want to do it again . [Terry Reedy] > What was your basic approach? Power series? Rational function? > Continued fraction? ??? exp(log(x)*y) -- really . It was a combination of table-driven and economized power series approaches, like the Tang algorithm I mentioned last time, carefully faking just enough extra precision to guarantee < 1 ulp worst-case error in the end. > http://functions.wolfram.com/ElementaryFunctions/Power/ > gives 343 formulas (many only relevant to complex domain) but doesn't > seem to indicate which Mathematica actually uses (trade secret I > presume). Those kinds of references won't do you any good at this level: good-to-the-last-bit library functions are a whole different game. Check out Peter Tang's celebrated paper on the implementation of exp (sorry, it's not free): http://portal.acm.org/citation.cfm?doid=63522.214389 That's still much the state of modern art for native-precision transcendentals, and, with enough pain (in x**y's case, transcendant pain), all can be approached in a similar way. Dynamic-precision calculations are yet another entirely different kind of game. David Bailey's MPFUN is freely available, and so is Dave Gillespie's Emacs calc mode; you can get as much precision out of those as you want. Jurjen N.E. Bos's real.py for Python is yet another entirely different game: an implementation of the constructive reals, where the result of an arbitrarily complex chain of calculations (not just one!) can be obtained to any desired accuracy. As you climb up this chain of wilder ambitions, runtime increases accordingly, of course. For best speed, exp(x) can be approximated by 1 . From aleax at aleax.it Sat Sep 14 15:51:46 2002 From: aleax at aleax.it (Alex Martelli) Date: Sat, 14 Sep 2002 19:51:46 GMT Subject: Skipping Parts of a For Loop References: Message-ID: Thomas Guettler wrote: > Hi! > > Is there a way to skip some parts in a for loop? > > > for i in range(3): > print "i before", i > i=2 > print "i after", i > > #Results in: > > i before 0 > i after 2 > i before 1 > i after 2 > i before 2 > i after 2 > > Is there a way to skip some parts? > > "continue" skipps one element. But how can > I skip several? In Python 2.2, a for loop like: for x in something: "any statements here" is equivalent to: _aux = iter.something() while True: try: x = _aux.next() except StopIteration: break "any statements here" You can take advantage of this as long as you bind the iterator to a name, exploiting also the fact that iter(iter(x)) is iter(x) [i.e., iter is idempotent on iterators]: aux = iter(range(3)) for i in aux: print "i before", i for i in range(i,3): aux.next() print "i after", i Each calls to the next method of the iterator object "skips" a whole coming leg of the for loop. Alex From NWMoriarty at lbl.gov Thu Sep 19 12:58:47 2002 From: NWMoriarty at lbl.gov (Nigel W. Moriarty) Date: Thu, 19 Sep 2002 09:58:47 -0700 Subject: thread error Message-ID: <3D8A0247.B87A7CD@lbl.gov> Folks I have a app using a threading TCP server which ocassionally spits out the following error when it exits. Unhandled exception in thread: Traceback (most recent call last): File "/usr/local_cci/Python-2.2.1t/lib/python2.2/threading.py", line 415, in __bootstrap s = _StringIO() File "/usr/local_cci/Python-2.2.1t/lib/python2.2/StringIO.py", line 42, in __init__ if type(buf) not in types.StringTypes: AttributeError: 'NoneType' object has no attribute 'StringTypes' A look at the code shows that the object types is the standard module types. Any ideas? Nigel -- Nigel W. Moriarty Building 4R0230 Physical Biosciences Division Lawrence Berkeley National Laboratory Berkeley, CA 94720-8235 Phone : 510-486-5709 Fax : 510-486-5909 Email : NWMoriarty at LBL.gov Web : CCI.LBL.gov From maxm at mxm.dk Sat Sep 14 04:59:07 2002 From: maxm at mxm.dk (Max M) Date: Sat, 14 Sep 2002 10:59:07 +0200 Subject: Calling Python from C# - please help References: <6de16ac9.0209130508.5d1b56c6@posting.google.com> <0iCg9.2350$Ee4.6516@news-server.bigpond.net.au> Message-ID: <3D82FA5B.3050003@mxm.dk> Mark Hammond wrote: > I have no examples of this, but I should. I'm co-authoring a .NET book > which is nearly out :) - That sounds great. I enjoyed the win32 book, and still use it as a reference. Are you by any chance still developing Pyhton .NET, or has it completely stopped? regards Max M From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Fri Sep 13 10:37:14 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Fri, 13 Sep 2002 16:37:14 +0200 Subject: calling Oracle functions Message-ID: <3d81f811$1@news.mt.net.mk> Does anyone know, how can I call Oracle stored functions from Python. I'm using cx_Oracle. The function takes three parameters and returns one result. I tried: params = ['param1', 'param2', 'param3'] v_Cursor.callproc("SCH.PKG.MyFunction", params) and I got the error: cx_Oracle.DatabaseError: ORA-06550: line 1, column 8: PLS-00221: 'MyFunction' is not a procedure or is undefined But I can execute the function from sqlplus declare result number; BEGIN result := SCH.PKG.MyFunction('param1', 'param2', 'param3'); END; Any hints? -- ?????? Yes, I've heard of "decaf." What's your point? From bbin__ at hotmail.com Tue Sep 24 09:36:21 2002 From: bbin__ at hotmail.com (Benjamin Binford) Date: Tue, 24 Sep 2002 09:36:21 -0400 Subject: Three dumb questions (ordered by dumbness descending) References: Message-ID: On Tue, 24 Sep 2002 01:45:29 +0000, Steven Feil wrote: > On Mon, 23 Sep 2002 16:03:21 -0500, Thorsten Kampe wrote: > >> Okay, here they are: > > Ok, I'll take a stab at the first two questions. I do think that a > little more clarity on your part could make it a bit easer. > > The first thing to remember is that Python is a dynamically typed > language. It is typed and each object has a type, It would be a little > easer if you would disclose the type for each object you are referring > to. > > >> 1. Why is 'zip(zip(x)) != x' (should be the same because it's the >> transposed) > > Humm, what is is zip(), a function in the standard Python library or is > it something you or someone else made up? I did a quick search in the > Python docs and the only zip I found referred to zip compression. If > this is something from the standard Python libraries please state the > library it comes from. > > If zip is some general function, then in general, zip(zip(x)) is not > equal to x. This comes from fundamental abstract algebra. In trig > sin(sin(x)) is not x. There do exist functions who are there own inverse > and if zip is one of them then zip(zip(x)) is equal to x. > > Zip is a builtin function in Python versions >= 2 zip(seq1, ...) This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences. At least one sequence is required, otherwise a TypeError is raised. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple argument sequences which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. >From the definition you can see that zip is not the transpose of itself. zip(zip((1,2,3))) = [((1,),), ((2,),), ((3,),)]. If the original sequence is represented by a list like (1,2,3), the result of a double zip is a doubly nested set of lists or a tree. Thus the result could also be represented as: 1 / list / / 2 / / list / root \ 3 \ / list From oren-py-l at hishome.net Wed Sep 4 14:57:04 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Wed, 4 Sep 2002 14:57:04 -0400 Subject: Daemonize? In-Reply-To: References: Message-ID: <20020904185704.GA28154@hishome.net> On Wed, Sep 04, 2002 at 08:36:57AM -0500, sismex01 at hebmex.com wrote: > Sorry to ask here, but I don't have any "unixy" python > documentation at hand. > > Normally, I put an app into "daemon" mode, by first > forking, then reopening stdin/out/err to /dev/null, > and then forking again. Works good enough for my > purposes. > > But, am I right? Is this the correct way to do this? > Also, I can't find any "reopen" in python to apply > to sys.stdin/out/err. No need to do anything to the sys.std* objects - you can manipulate the underlying file handles directly with os.close, os.dup2, etc. Oren From marklists at mceahern.com Thu Sep 26 10:10:56 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 26 Sep 2002 09:10:56 -0500 Subject: Tabs vs. Spaces, VIM vs. EMACS (Was Re: Larry Wall's comment on python...) In-Reply-To: <006101c2651b$0df0c340$0101010a@local> Message-ID: [Chris Gonnerman] > Surely emacs can do as well as VIM... (and I expect a rabid > emacs user to fill me in posthaste). Yup. Here are the relevant portions of my .emacs file: ;; Turn tabs off by default. (setq-default intend-tabs-mode nil) ;; Set tab width to 4 by default. (setq-default tab-width 4) ;; Use Python mode for .py files. (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist)) ;; Load Python mode. (autoload 'python-mode "python-mode" "Python editing mode." t) ;; Set up initialization parameters for python mode: (setq python-mode-hook '(lambda () (progn (set-variable 'py-indent-offset 4) (set-variable 'py-smart-indentation nil) (set-variable 'indent-tabs-mode nil) ))) ;; Define untabify-buffer. (defun untabify-buffer() (interactive) "Untabify the current buffer. Return nil. Must return nil, if added to write-file-hooks." (save-excursion (goto-char (point-min)) (while (re-search-forward "[ \t]+$" nil t) (delete-region (match-beginning 0) (match-end 0))) (goto-char (point-min)) (if (search-forward "\t" nil t) (untabify (1- (point)) (point-max)))) nil) ;; Untabify buffers on write file. (defun do-on-write-file() (untabify-buffer)) ;; Add the hook. (add-hook 'write-file-hooks 'do-on-write-file) // m From martin at v.loewis.de Mon Sep 2 01:11:13 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 02 Sep 2002 07:11:13 +0200 Subject: Tix/Tk Module frustrations HELP! References: Message-ID: Jonathan S writes: > I tried rebuilding Tix from sources, yet it still has the same trouble. I > guess I'll try rebuilding my X11 libs... Can you please report the linker line used to link libtix.so? It appears that it sometimes fails to link -lX11, which would also explain this problem. HTH, Martin From jon at csh.rit.edu Mon Sep 30 15:32:24 2002 From: jon at csh.rit.edu (Jon Parise) Date: Mon, 30 Sep 2002 15:32:24 -0400 Subject: About data structure In-Reply-To: <3d98a5d8$0$496$7a628cd7@news.club-internet.fr> References: <3d98a5d8$0$496$7a628cd7@news.club-internet.fr> Message-ID: <20020930193223.GB19636@csh.rit.edu> On Mon, Sep 30, 2002 at 09:29:52PM +0200, malan wrote: > I need to build a data structure like this : > > size 4 bytes ( example 0x0000000A ) > flag 1 byte ( example 0x87 ) > trans 8 bytes ( example 'URTVMI1' ) > F5 3 bytes ( example 0x00125C ) > > How can I define that structure, format it and send it via a socket ? > My problem is to code / decode the message to and from the server. You want to use the 'struct' module: http://www.python.org/doc/current/lib/module-struct.html -- Jon Parise (jon at csh.rit.edu) . Information Technology (2001) http://www.csh.rit.edu/~jon/ : Computer Science House Member From keith_s at ntlworld.nospam.com Thu Sep 5 04:45:29 2002 From: keith_s at ntlworld.nospam.com (Keith S.) Date: Thu, 05 Sep 2002 09:45:29 +0100 Subject: linking embedded python Message-ID: <3D7719A9.8050804@ntlworld.nospam.com> Hi, This might be a dumb question, but how does one link a C++ application in Unix with embedded python? Under Solaris 2.8 I found what appears to be the link library /usr/local/lib/python2.1/config/libpython2.1.a (the python installation came from the Sun freeware site). However, when I try and link, I get errors like: Undefined first referenced symbol in file dlsym /usr/local/lib/python2.1/config/libpython2.1.a(dynload_shlib.o) (symbol belongs to implicit dependency /usr/lib/libdl.so.1) dlopen /usr/local/lib/python2.1/config/libpython2.1.a(dynload_shlib.o) (symbol belongs to implicit dependency /usr/lib/libdl.so.1) dlerror /usr/local/lib/python2.1/config/libpython2.1.a(dynload_shlib.o) (symbol belongs to implicit dependency /usr/lib/libdl.so.1) Anyone shed any light on what I'm doing wrong? - Keith From mfranklin1 at gatwick.westerngeco.slb.com Wed Sep 25 04:53:06 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 25 Sep 2002 08:53:06 +0000 Subject: how to change font and its size in IDLE (in UNIX)? Message-ID: <200209250853.06075.mfranklin1@gatwick.westerngeco.slb.com> On Wednesday 25 Sep 2002 5:22 am, Kow K wrote: > Hi all, > > I'm trying to figure out how to change the font and its size in IDLE. > It's Courier in 10pt. I don't like Courier, and what's worse, > 10pt is too small for me. I wish I could change it to Fixed 7x13. > > Any input will be appreciated. > > Kow Take a look here (from http://groups.google.com/advanced_group_search) http://groups.google.com/groups?q=font+size+idle&hl=en&lr=&ie=UTF-8&scoring=r &selm=3a942c61_4%40corp.newsfeeds.com&rnum=1 Cheers Martin -- ### Python Powered Signature I started writting this email on Wed Sep 25 08:51:33 2002 From Minews at ms6.de Mon Sep 9 09:01:16 2002 From: Minews at ms6.de (Michael Schwarz) Date: Mon, 09 Sep 2002 15:01:16 +0200 Subject: Tkinter: How to "break" class-event-bindings from within tag-bindings? Message-ID: <3D7C9B9C.60603@ms6.de> A "break" as the return value of a tag-event-binding for the Text-widget seems not to prevent the standard event-handling of the widget to occur. This seems to be an error! How can it be done another (elegant) way? See the following example: === # How can tag-events "break" class-bindings? from Tkinter import * def Jump(e): # Sprung: targetFrom, targetTo = "3.5", "3.9" F.Text.tag_remove("sel", "0.0", "end") F.Text.tag_add("sel", targetFrom, targetTo) F.Text.mark_set("insert", targetFrom) return "break" # Doesn't do it !!! F = Tk() F.Text = Text(F) # , width=120, height=35, bg="white") F.Text.pack() # (side="right", fill="both", expand=1) F.Text.focus_set() F.Text.insert(INSERT, """\ Link Jump HERE """) F.Text.tag_bind("link", "<1>", Jump) F.Text.tag_config("link", underline = "on") F.Text.tag_add("link", "1.0", "1.4") # Comment the following line and the jump won't do it anymore # due to the standard class-bindings of the text-widget F.Text.bind("<1>",lambda e: "break") F.mainloop() From richie at entrian.com Mon Sep 16 12:33:27 2002 From: richie at entrian.com (Richie Hindle) Date: 16 Sep 2002 09:33:27 -0700 Subject: possibly OT - delete char? References: <3pch9.10253$Ee4.26056@news-server.bigpond.net.au> Message-ID: <8a6ba1da.0209160833.154251f5@posting.google.com> > - is there a character which deletes the previous printed character when > printed? Yes, \b, in a reasonably portable manner: $ uname -sr Linux 2.4.7-10smp $ python Python 2.1.3 (#1, May 15 2002, 14:56:49) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "copyright", "credits" or "license" for more information. >>> print "12\b3" 13 >>> C:\>ver Microsoft Windows XP [Version 5.1.2600] C:\>python Python 1.5.2 (#0, Feb 4 2002, 16:19:07) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> print "12\b3" 13 >>> -- Richie Hindle richie at entrian.com From sross at connectmail.carleton.ca Tue Sep 17 22:55:52 2002 From: sross at connectmail.carleton.ca (Sean Ross) Date: 18 Sep 2002 02:55:52 GMT Subject: Splitting a list of strings References: Message-ID: Okay. Here is some representative sample data: % Relevant Information: % This data set includes descriptions of hypothetical samples % corresponding to 23 species of gilled mushrooms in the Agaricus and % Lepiota Family (pp. 500-525). [snip] % % Number of Instances: 8124 % % Number of Attributes: 22 (all nominally valued) % [snip] @attribute 'cap-shape' { 'b', 'c', 'f', 'k', 's', 'x'} @attribute 'cap-surface' { 'f', 'g', 's', 'y'} @attribute 'cap-color' { 'b', 'c', 'e', 'g', 'n', 'p', 'r', 'u', 'w', 'y'} [snip] 'x','s','n','t','p','f','c','n','k','e','e','s','s','w','w','p','w','o','p', 'k','s','u','p' 'x','s','y','t','a','f','c','b','k','e','c','s','s','w','w','p','w','o','p', 'n','n','g','e' 'b','s','w','t','l','f','c','b','n','e','c','s','s','w','w','p','w','o','p', 'n','n','m','e' 'x','y','w','t','p','f','c','n','n','e','e','s','s','w','w','p','w','o','p', 'k','s','u','p' [snip] So, essentially, there are three types of strings in the file: comments, attribute descriptors, and data. I'm pulling out the attribute descriptor and data strings and storing them in separate lists. I'll be doing stuff with those latter; making a decision tree, for instance. Anyway, the code I've written does what I need, but I'm thinking there may be a more efficient method. Hence, the post. As for str, I agree and the name has been changed. Thank you. "Mark McEahern" wrote in message news:mailman.1032309381.3626.python-list at python.org... > > I need to read a list of strings from a file[...] > > For those of us who are lazy and lacking in imagination, why not share a few > lines of representative sample data? > > // m > > p.s. Don't use str as the name of a variable, you'll clobber the builtin > str. > > - > > From emile at fenx.com Wed Sep 18 10:39:51 2002 From: emile at fenx.com (Emile van Sebille) Date: Wed, 18 Sep 2002 07:39:51 -0700 Subject: Splitting a list of strings References: Message-ID: Sean Ross: > However, I guess what I was looking for was a > side-effect, or some such mechanism where, by extracting the nickels, I get > the two piles: one of nickels, one of pennies and dimes. lines = ["sdflkj","@;lkjdsa","#lkjasdf", "sdflkj","@;lkjdsa","#lkjasdf", "sdflkj","@;lkjdsa","#lkjasdf", "sdflkj","@;lkjdsa","#lkjasdf",] vals = [[],[],[]] for line in lines: vals["@#".find(line[:1])+1].append(line) data, attrs, comments = vals print data, attrs, comments Or, if you want to use an lc: [ vals["@#".find(line[:1])+1].append(line) for line in lines] -- Emile van Sebille emile at fenx.com --------- From member at dbforums.com Sun Sep 15 06:50:13 2002 From: member at dbforums.com (hpyhpy) Date: Sun, 15 Sep 2002 10:50:13 +0000 Subject: Anyone can tell me why? References: <1815200.1031973626@dbforums.com> Message-ID: <1817360.1032087013@dbforums.com> But I try,change the filename as "example.so","_example.so", "examplemodule.so",#_#,same error......have other advise?^_^ -- Posted via http://dbforums.com From aleax at aleax.it Fri Sep 20 10:18:19 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 14:18:19 GMT Subject: general thoughts References: Message-ID: Eddie Corns wrote: > If you want to learn "how it (computer languages) works" I suggest reading > "Structure and Interpretation of Computer Languages" by Abelson and > Sussman. This is about understanding the principles rather than how to do > things in a particular language and is probably the best book on the > subject. I'll second this (well, third this, I guess, since P. Rubin recommended the very same book independently in another post a while ago:-). SICP is the best book I know about the "deep principles" of programming. I think you need substantial capacity and appetite for abstract thought to really _enjoy_ SICP -- it doesn't spoon-feed you, nor does it use baby-talk, lots of somewhat-repetitive examples, and other standard didactical techniques. But if the book's style does match your own character and inclination, you're likely to fall in love with it. Alex From bokr at oz.net Wed Sep 4 16:38:39 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2002 20:38:39 GMT Subject: Regexp Over Multiple Lines References: <565e316f.0209040740.36573b56@posting.google.com> Message-ID: On 4 Sep 2002 08:40:22 -0700, vetter at lincom-asg.com (Keith) wrote: >In Python can I have a regular expression that spans multiple lines... Yes, see X flag on http://www.python.org/doc/current/lib/node99.html and read about the re module at http://www.python.org/doc/current/lib/module-re.html wherefrom you can find the syntax at http://www.python.org/doc/current/lib/re-syntax.html etc. etc. It should look familiar. [...] Regards, Bengt Richter From torkil at fast.no Tue Sep 17 06:56:52 2002 From: torkil at fast.no (Torkil Grindstein) Date: Tue, 17 Sep 2002 12:56:52 +0200 Subject: Regular expression help needed References: Message-ID: <3D870A74.5D2D7595@fast.no> Harvey Thomas wrote: > 1) There are no comments or processing instructions that could > contain similar data > 2) The attributes always come in the order specified i.e. name > first, content second, any others following > 3) The attributes are always double quoted and there are no > spaces surrounding the = Thank you very much! I have set up a little extended version: re.compile("""""", re.IGNORECASE) Which should rule out point 3) (except that it accepts "michael' and michael' etc). 1) and 2) I think I can live with for my application (due to knowledge of the documents). Btw, I have no knowledge of SAX. Perhaps I should dig into that? Torkil. From fgeiger at datec.at Wed Sep 25 03:01:11 2002 From: fgeiger at datec.at (F. GEIGER) Date: Wed, 25 Sep 2002 09:01:11 +0200 Subject: Saving & Restoring Python objects in XML? References: <3D8F7800.F757A72D@wyeth.gsfc.nasa.gov> Message-ID: <3d915f2b@news.swissonline.ch> IIRC the Gnosis XML utilities offer XML/object mapping. Cheers Franz "Tom Bridgman" schrieb im Newsbeitrag news:3D8F7800.F757A72D at wyeth.gsfc.nasa.gov... > Hello, > > I'm setting up some codes where I want to save the state of the code in > an XML file at some time and reload it later to continue the processing. > > It's relatively easy to save out the innards of Python objects into XML > regardless of how the objects are nested. But what about loading this > state information back in from the XML file? > > Is there a way to write the parser handlers and/or other components (I'm > using PyXML 0.7 and higher) such that they can assemble the required > objects as they read in the file? I'm wondering if there is an elegant > solution that might not be immediately obvious from the 'brute force' > method I keep coming up with. I'd prefer to do this using SAX (since > I've worked with it some), but using DOM is not out of the question if > it solves the problem in a straightforward way. > > Thanks, > Tom > -- > Dr. William T."Tom" Bridgman Scientific Visualization Studio > Global Science & Technology, Inc. NASA/Goddard Space Flight Center > Email: bridgman at wyeth.gsfc.nasa.gov Code 935 > Phone: 301-286-1346 Greenbelt, MD 20771 > FAX: TBD http://svs.gsfc.nasa.gov/ From fredrik at pythonware.com Wed Sep 4 03:14:09 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Sep 2002 07:14:09 GMT Subject: Max line coords canvas.create_line() can display? References: Message-ID: <5pid9.5885$e5.1033551@newsb.telia.net> "revyakin" wrote: > Is there a limit of line coords (x1,y1,...xn,yn) which a Tk Canvas > create_line method can display? I found that I can display a line > consisting of 5000 x,y points, but a line of 20 000 points does not > get displayed. there shouldn't be a limit. can you perhaps post a (short) code snippet that illustrates the problem? From dance_code at hotmail.com Tue Sep 3 03:04:26 2002 From: dance_code at hotmail.com (lion) Date: 3 Sep 2002 00:04:26 -0700 Subject: syntax error in Pyton shell Message-ID: I'm learning exception handling, I type these code in Python shell: >>> try: f=open("nofile") ... except IOError: pass ... print "The exception is just passed!" File "", line 3 print "The exception is just passed!" ^ SyntaxError: invalid syntax But these code run without any error as a program(or script). Could anyone tell me why? Thanks in advance, lion From ianb at colorstudy.com Mon Sep 23 23:58:55 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 23 Sep 2002 22:58:55 -0500 Subject: Three dumb questions (ordered by dumbness descending) In-Reply-To: References: Message-ID: <1032839942.11325.106.camel@dsl-65-184-205-5.telocity.com> On Mon, 2002-09-23 at 16:03, Thorsten Kampe wrote: > 2. Peter Norvig mentions in "Python for Lisp Programmers" some > "don'ts": "[x] + y" and "x[1:]". Are there more things to avoid > (especially in a loop)? He's probably thinking about x[1:] because it is slower than (cdr x) -- in Python you are creating a new list. You can use "del x[0]" instead. The same is true of "[x] + y", as compared to (cons x y) -- you aren't reusing the y list. y.insert(x, 0) is considerably faster (as long as you don't mind mutating y). I haven't read what he said, but I think rather you shouldn't use: x = x[1:] # or y = [x] + y both these cases are suboptimal, even if they seem similar to some Lisp cognate. > 3. random.shuffle: the documentation says: "Note that for even rather > small len(x), the total number of permutations of x is larger than the > period of most random number generators; this implies that most > permutations of a long sequence can never be generated." I translate > this to "don't shuffle lists with more than 15 elements if you want a > randomly ordered list". > > Alex Martelli says the same: "For example, Python users who are > calling random.shuffle on a sequence of substantial length have a need > for an underlying random generator with a *HUGE* period, as a > necessary although not sufficient condition towards ensuring that all > permutations of the shuffled sequence get generated with equal > likelihood. > > Wichman-Hill has a period of less than 7,000 billions (7e12), > insufficient to account even for the permutations of a sequence > whose length is just 16 (16! > 2e13)." > > Otherwise in the "Python Cookbook" (Selecting Random Elements from a > List Without Repetition) the shuffle version is called "the winner". > > So: can I use random.shuffle or do I have to write my own - slower - > version to get a random list? Well, it depends what you require of shuffle. If you want to do modeling on large sets with many permutations, maybe so. The only way I see to get around this is to use a true random number source -- like /dev/random on Linux. All pseudo-random sources will have a period based on their potential seed size and amount of internal state. For long lists, it seems unreasonable to create a better pseudo-random source -- though I haven't thought about it that hard. random.shuffle is not optimized -- it's written in Python, and is very short, and I don't think well implemented: def shuffle(x): for i in xrange(len(x)-1, 0, -1): # pick an element in x[:i+1] with which to exchange x[i] j = int(random() * (i+1)) x[i], x[j] = x[j], x[i] I would implement it like this: def shuffle(x): newList = [(random(), i) for i in x] newList.sort() return [i[1] for i in x] Anyway, in either case you could create your own random number source and copy and paste that algorithm using that new source. Ian From mike at frcatel.fri.utc.sk Thu Sep 19 09:54:02 2002 From: mike at frcatel.fri.utc.sk (Michal Kaukic) Date: Thu, 19 Sep 2002 15:54:02 +0200 (CEST) Subject: Python sequences reference - problem? In-Reply-To: Message-ID: Hi, we like Python - I use it (with Numeric and SciPy modules) for teaching of Numerical analysis and my colleague is doing some research in discrete optimization in Python. And he often surprises me with non-conformal use of language :-) We are mathematicians, not programmers. I suppose, he believes that Python "thinks" like Mathematician. Yesterday, he was struggling with the code shown below (somewhat simplified): L_L=[[1,2,3], [2,3,4], [3,4,5]] def do_process(LL): n=len(LL[0]) rec = [0]*n Res=[] for row in LL: rec[0] = row[0] # further code - modifying rec # lots of conditional processing and such... # ... Res += [rec] return Res --------------------------------------------- After calling do_process(L_L), the "expected" result should be [[1, 0, 0], [2, 0, 0], [3, 0, 0]] but the true result is [[3, 0, 0], [3, 0, 0], [3, 0, 0]]. Yes, this is fully in accordance with how the Python language should behave: Res += [rec] inserts references to list object rec, which are further modified... (he should use copy(rec) instead). But there is nothing to make this behaviour clearly VISIBLE in code. If I work with pointers in C/C++ I know and see they are pointers. You can say - we also know that rec is list object and so be careful with it. Yes, but consider the complex code where the similar constructs are very easy to overlook. And debugging of such code can be frustrating. My colleague was in state of despair and made thoughtful remarks about FORTRAN and Python similarity. He believes that Python is corrupting his (computer) memory... So what is the point? I wrote this message in hope that there are more people with similar experience. My question is - how to explain to novice non-programmer users (maybe mathematically "infected") the quirks of Python sequence objects? Which methodology to use in programs so we can clearly see we work with "pointers"? Or maybe someone can propose the changes to the Language to overcome this (psychological) barrier? I feel this as a serious obstacle in using Python (my students experienced it too). Thanks, Mike From thehaas at binary.net Thu Sep 12 08:55:11 2002 From: thehaas at binary.net (thehaas at binary.net) Date: Thu, 12 Sep 2002 12:55:11 GMT Subject: Regexp Over Multiple Lines References: <565e316f.0209040740.36573b56@posting.google.com> <565e316f.0209110529.30e61ea4@posting.google.com> Message-ID: Duncan Booth wrote: > Once you learn the idioms you should do fine. > BTW, one of the idioms is not to use regular expressions as often as in > Perl. I have done a lot of text processing using just the string module and the built-in string methods (Py 2.x) and never touching regexes. If you read the regex how-to, you will remember it saying that for a lot of tasks (like looking for an exact string) it's best to use string.find, etc., mostly because it's faster, and (to me) seems easier. Just throwing it out there . . . -- mikeh -- Mike Hostetler thehaas at binary.net http://www.binary.net/thehaas GnuPG key: http://www.binary.net/thehaas/mikeh.gpg From tismer at tismer.com Wed Sep 18 09:27:12 2002 From: tismer at tismer.com (Christian Tismer) Date: Wed, 18 Sep 2002 15:27:12 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D881B66.1080200@something.invalid> Message-ID: <3D887F30.5000601@tismer.com> Greg Ewing wrote: > Martin v. Loewis wrote: > >> >> They aren't really dangerous, just unconventional. > > > > Last I heard, Christian was moving pieces of the C > stack while there could be pointers to it in use. > That's definitely dangerous, as he discovered when > it broke Tk. And I fixed it by adding some small locking code to _tkinter that prevends stack slicing in that context. > I'd be very nervous about using Stackless until > it stops doing that. > > > And that cannot be > > fixed, as it is essential to operation of Stackless. > > Seems to me it could be fixed by just copying the > C stack as a whole, instead of piecemeal. See my other posting. Everything is there already. Everything is under your control and optional. hard-to-discuss-if-people-haven't-even-looked-at-it - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From thorsten at thorstenkampe.de Tue Sep 17 14:36:24 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 17 Sep 2002 20:36:24 +0200 Subject: Python equivalent to perldoc? References: <%Avh9.7933$Lg2.1392332@news2.news.adelphia.net> Message-ID: * Bob X > Bob X wrote: >> In Perl you can run "perldoc warnings" and get the definition of what >> "warnings" does. Is there a equivalent in Python? >> > Well...I found "pydoc". However I have to explicitly tell python to > execute it on Windows XP. I cannot type "pydoc sys" nor "python pydoc > sys" but I have to type "c:\python22\libs\pydoc sys" to get it to work. Tough > Shouldn't Python know its own libs? It does: ,--- | Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 | Type "help", "copyright", "credits" or "license" for more information. | >>> import pydoc | >>> `--- > Or at least put the "libs" in the ENV variable? Windows XP doesn't have a ENV variable. Thorsten From marklists at mceahern.com Wed Sep 25 11:04:49 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 25 Sep 2002 10:04:49 -0500 Subject: What function called this function ?? In-Reply-To: <98jk9.22340$0p1.391334@news2.ulv.nextra.no> Message-ID: > Is it possible, by hacking the traceback/stack/etc, to get > information about the function, that functions class and in what > module that function and class are defined, from inside a function > located elsewhere? Something like a way of answering the question > of "who called me?" without sending the answer along as a parameter. Some variation on this theme: ** #!/usr/bin/env python def mycaller(): """mycaller() Return the name of the caller of the caller of this function. """ import sys steps_back = 2 return sys._getframe(steps_back).f_code.co_name def foo(): print "foo called by %s." % mycaller() def bar(): foo() bar() ** Output: foo called by bar. // m From loewis at informatik.hu-berlin.de Wed Sep 18 03:58:56 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 18 Sep 2002 09:58:56 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D881B66.1080200@something.invalid> Message-ID: Greg Ewing writes: > Last I heard, Christian was moving pieces of the C > stack while there could be pointers to it in use. Yes, that's how stackless works, and that cannot change. > That's definitely dangerous, as he discovered when > it broke Tk. What is the danger? A program crashes? It is dangerous to cross a street at rush hour; sitting in front of a computer is rarely dangerous. Stackless adds a few limitations as to what C extensions can do. If those restrictions are followed, it won't crash. > I'd be very nervous about using Stackless until > it stops doing that. Why is that? Those crashes can only happen if you use the stackless modules (and only if you use them with a stackless-unsafe extension). If you don't import stackless, no stack is copied. > Seems to me it could be fixed by just copying the > C stack as a whole, instead of piecemeal. Then it won't be stackless - one application is that the recursion limit is only constrained by the heap size, not by the stack size. Also, task switching becomes very expensive when copying the entire thread. Finally, you *still* can get it to break: some extension module might preserve the address of a local variable in global state, but then the entire stack is copied away. Regards, Martin From dag at animagicnet.no Wed Sep 4 10:48:50 2002 From: dag at animagicnet.no (Dag) Date: 4 Sep 2002 14:48:50 GMT Subject: Matching a string up to a word References: <3d75ffaa$1@news.sentex.net> Message-ID: In article <3d75ffaa$1 at news.sentex.net>, Peter Hansen wrote: > > Can you instead guarantee the format of the date that follows the > filename? Will it always consist of the day of the week, the month, > the date, and the year? That would turn this into a relatively > simple problem. Yes I can guarentee the last four fields be in that date format. Actually I think that solved it. I'll split on whitespaces into an array, and remove the first and last four fields, and then join whatever's left. That should do it. I was stuck thinking how to parse it left to right. Thanks for making look at the problem slightly differently. Dag From LogiplexSoftware at earthlink.net Mon Sep 16 17:27:42 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 16 Sep 2002 14:27:42 -0700 Subject: Source code In-Reply-To: References: Message-ID: <1032211662.17056.278.camel@software1.logiplex.internal> On Mon, 2002-09-16 at 13:17, BT wrote: > > |If your code is that valuable, run it on your server remote from end > > |users as a trade secret, or force them to agree to a license and protect > > |it w/ copyright. > > > > I would reformulate the issue slightly: If you BELIEVE your code is > > that valuable, seek psychiatric help. > > > > I really don't understand posts like these. > You think I'm fool to protect my work? No, only a bit uninformed if you think you can get "security through obscurity". Obscuring the code will dissuade only the most casual or incompetent from decompiling/disassembling your code. Sort of like hiding a spare key to your house under the "Welcome" mat. > Ok, let's say I make a software in two years and I market it on internet. > The software is good and sell some copy. > You find the software, like it, change the name, add some feature and resell > it. > My time: 2 years, yours: 1 month. And that would be illegal, hence the suggestion to *copyright* your work. > > I think you need a psychiatric help. > Only Id shared some source code, after years... > Noooooooo!!! IDDDDD!!! Foolish people!!! You want to sell it???!!! You want > to live with that???!!! They shared it because it was no longer relevant. Sort of like opening the source for MS-DOS 2.0 (which hasn't happened, but you should see my point). > Go working in a mine, and write games for fun!!! > I can give you the phone of my clinic, but stop it NOW, join the ideal > world. You mean the "real" world. In the "ideal" world, most software would be free, and people wouldn't pirate software that wasn't. Incidentally, do you believe you are the first person to think of this? This question ("how can I obscure Python byte-code?") comes up at least once a month on this list. It's fairly clear that any scheme you come up with will take longer to implement than it will to break by a competent hacker. Anyway, good luck! If your software is any better than your protection scheme I'll download it from http://www.warez.com when you release it ;) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From h.goebel at crazy-compilers.com Tue Sep 17 14:51:15 2002 From: h.goebel at crazy-compilers.com (Hartmut Goebel) Date: Tue, 17 Sep 2002 20:51:15 +0200 Subject: Earing money with Python software (was: More on Protecting Source Code) References: Message-ID: <4jt7ma.fse.ln@lenashee.goebel-consult.de> Martin v. Loewis wrote: > For software, I think the economical risk is that somebody uses your > software without giving you the money you want - not that somebody > sits down and studies your code for days, to write a program that he > could have written himself from scratch in the same time. Which brings me to another (related) topic): How to earn money distributing Python software? I'm currently trying to make up my mind about exactly this problem area: How can I get some reward back when writing software like decompyle and bridgekeeper? I would be very gald if someone could share his/her experiances on this topic! - Sell it via micro-payment? - Declare it "Shareware" and hope somebody pays for it? - Offer commercial support? - Develop two different versions, a "free" one which is missing some features and a commercial/registered/supported one offering more sophisticated functionallity? (Any other comments are welcome, too.) Regards +++hartmut -- | Hartmut Goebel | h.goebel at crazy-compilers.com | | crazy-compilers.com | compilers which you thought are impossible | From wlfraed at ix.netcom.com Tue Sep 3 11:15:52 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 03 Sep 2002 08:15:52 -0700 Subject: code doesn't work: question References: Message-ID: <8nj2la.cr3.ln@ix.netcom.com> Ruslan Spivak fed this fish to the penguins on Tuesday 03 September 2002 03:03 am: > if (tmp = var) == 5: # this is the error line Unless things have changed since I last read a Python book, assignment is not an operator, it is a statement. tmp = var if tmp == 5: -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From aleax at aleax.it Wed Sep 25 05:11:14 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 09:11:14 GMT Subject: problem with dictionaries within lists References: Message-ID: Grant Hallam wrote: ... > However, the list seems to get populated with the same dictionary ... > webdatabaselist.append(dict) Of course -- you ARE appending the same dict over ands over (AFAICT -- you're probably using tabs for indentation, making your code hard to comprehend for those who read news with KDE's KNode [or MS's OE] as tabs don't show there... use spaces, NOT tabs...). Anyway, you probably need something like: webdatabaselist.append(dict.copy()) dict = {} either might suffice, but generally you'll need to copy the current dict AND make dict empty for the next leg of the loop, if I get the general drift. If you do rebind name dict to {} for the next leg, then you don't need the call to the copy method. Alex From dutoitc at hotmail.com Thu Sep 19 13:49:04 2002 From: dutoitc at hotmail.com (Cedric Dutoit) Date: Thu, 19 Sep 2002 19:49:04 +0200 Subject: wxPython i18n, help wanted Message-ID: Hi, I'm trying to translate an application in Chinese with i18n, but I don't know how to display Chinese characters in wxPython. Can anybody help me ? (Chinese is an example language) thks, C.Dutoit From Padraig at Linux.ie Wed Sep 11 09:20:21 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Wed, 11 Sep 2002 13:20:21 GMT Subject: regular expression for space seperated quoted string References: <%jHf9.3635$cP3.7161@news.iol.ie> Message-ID: Padraig Brady wrote: > Eric Brunel wrote: > >> Padraig Brady wrote: >> >> >>> Hi, I'm trying to split a string that is seperated >>> by spaces and also contains double quoted words which >>> can contain spaces: >> > > [snip] > >> What about: >> >>>>> p = r'[^ \t\n\v\f"]+|"[^"]*"' >>>>> re.findall(p, '1 2 3') >>>> > > FYI, I'm using the following: > > import fileinput, re > for line in fileinput.input(): > #split fields > fields = re.findall('[^ "]+|"[^"]+"', line[:-1]) > #remove quotes > fields = map(lambda field: field.replace('"', ''), listLine) > > thanks again, > P?draig. > Just in case it's useful I might as well make it correct and more efficient: import fileinput, re reFieldSplitter = re.compile('[^ "]+|"[^"]+"') for line in fileinput.input(): #split fields fields = reFieldSplitter.findall(line[:-1]) #remove quotes fields = map(lambda field: field.replace('"', ''), fields) P?draig. From python-list at hendel.net Wed Sep 11 06:58:18 2002 From: python-list at hendel.net (Manuel Hendel) Date: Wed, 11 Sep 2002 12:58:18 +0200 Subject: deleting the first and the last character of a string Message-ID: <20020911105818.GC2054@partagas.as.de.cw.net> I got a file with fields seperated by a "|". The problem is that there is also a "|" at the beginning and at the end of each line although there no fields in front or behind these "|". Now I want to delete these two "|". Is there anything which says delete the first or last character of a string? I checked the string module on the web, but I couldn't find anything. I solved it like this, but I honestly don't like it that way. #!/usr/bin/env python # import sys import string inputfile = open(sys.argv[-1], "r") for line in inputfile.readlines(): fields = string.split(line, "|") lineN = string.join(fields[1:-1], "|") Isn't there any better solution? ;-) Manuel -- The real purpose of books is to trap the mind into doing its own thinking. -Christopher Morley From Oschler at earthlink.net Mon Sep 16 01:30:27 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Mon, 16 Sep 2002 05:30:27 GMT Subject: Are generator functions thread-safe? Message-ID: I know that a call to a generator function actually returns an independent iterator object (mea culpa if I'm wrong on this), but are there any hidden gotchas that would cause the use of the same generator function from multiple threads, to result in a sharing (especially local storage) or memory collision issue? thx From awinston at scn.org Tue Sep 10 13:48:48 2002 From: awinston at scn.org (Alan Winston) Date: Tue, 10 Sep 2002 10:48:48 -0700 Subject: PySol: "global name 'win32_gethomedir' is not defined" References: Message-ID: "Syver Enstad" wrote in message news:un0qp6aex.fsf at online.no... > "Alan Winston" writes: > > > I've been trying to run the PySol 4.81 pyc files under Python 2.2.1 > > and > > > > WinXP and Win98, with no success. > > > > The Python window closes much faster than I can read the error message > > (is > > > > there any way to force the window to stay open?), > > Can't help with the cause, but can't you just start the program from > the command prompt instead of via explorer? Thank you. That makes the error messages much easier to see: Traceback (most recent call last): File "pysol.py", line 19883, in ? File "pysol.py", line 19881, in main File "pysol.py", line 19838, in pysol_main File "pysol.py", line 18833, in __init__ File "pysol.py", line 260, in gethomedir NameError: global name 'win32_gethomedir' is not defined -- Alan Winston Seattle From christophe.delord at free.fr Thu Sep 19 00:45:29 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Thu, 19 Sep 2002 06:45:29 +0200 Subject: PyLog, not require SWI-Prolog right? References: Message-ID: <20020919064529.2a2ae37f.christophe.delord@free.fr> On Thu, 19 Sep 2002 00:07:00 GMT "Robert Oschler" wrote: > PyLog is inpendent of any Prolog interpreter right? There's PyLog and > PyProlog, the latter I believe is a wrapper and therefore requires > SWI-Prolog (just like bevedere requires GNU-Prolog), but PyLog doesn't, > is that correct? Just looking for confirmation. PyLog only requires Python and TPG. TPG is a parser generator and is used to parse Prolog. PyLog is there : http://christophe.delord.free.fr/en/pylog/ TPG is there : http://christophe.delord.free.fr/en/tpg/ Prolog is translated into Python (a predicate is an object) and then interpreted by Python. So PyLog is independant of any Prolog interpreter but also slower. > > Also, PyLog supports backracking right? PyLog supports backtracking but is limited by the size of the Python stack. This may be not a problem with Stackless Python, I have to try it some day. > > thx > > > -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From 2002 at weholt.org Mon Sep 23 05:15:38 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Mon, 23 Sep 2002 09:15:38 GMT Subject: WSDL for XML-RPC ?? Message-ID: <_YAj9.21316$0p1.377838@news2.ulv.nextra.no> SOAP has WSDL to describe a webservice. Doeas XML-RPC have something similar? Is WDDX the right way to go or have I totally missed the point? Ref : http://www.wddx.org http://www.openwddx.org/ Best regards, Thomas From wlfraed at ix.netcom.com Tue Sep 24 21:55:02 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 24 Sep 2002 18:55:02 -0700 Subject: List/Tuple bug or feature? References: Message-ID: sismex01 at hebmex.com fed this fish to the penguins on Tuesday 24 September 2002 03:12 pm: > It's one of python's features :-) > > For when you wanna write a long string, SQL for example: > > Query = "SELECT what, when, where, why " > "FROM t1, t2, t2 " > "WHERE t1.id = t2.id_t1 and t3.id_t2 = t2.id and t1.id_t2 = > t3.id " "AND t1.answer = 'OK'" > What's wrong with... query = """select what, when, where, why from t1, t2, t3 where t1.id = t2.id_t1 and t3_id2 = t2.id ...etc """ -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From tjreedy at udel.edu Thu Sep 19 11:06:44 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Sep 2002 15:06:44 GMT Subject: surface of pygame References: Message-ID: <8Kli9.36954$216.1447920@bin4.nnrp.aus1.giganews.com> "black" wrote in message news:mailman.1032440854.11721.python-list at python.org... > I touched something about pygame today and confused with surface type. I didnt >remember surface data type when learning python, Because surface type is added by to PyGame and not part of standard Python. > and it displays strange to me, for example, I create a new surface by loading a picture >as follows: > > pygame.image.load("myPic.bmp") > > it works fine but I coulnt see any surface appears on the screen. > any ideas ? Read the Pygame docs on how to display image after loading. These are two separate operations. I believe there is a mailing list for PyGame discussion. See site. TJR From imbosol at vt.edu Fri Sep 6 18:58:12 2002 From: imbosol at vt.edu (Carl Banks) Date: Fri, 6 Sep 2002 18:58:12 -0400 Subject: Larry Wall's comment on python... References: Message-ID: mmaddox at hcsmail.com wrote: > > I would argue that the "older" block-structured languages were considered > a breakaway from the column-based languages - RPG2 and Fortran, for > instance. Although I grant the Python structure and the column-based > structures are not completely analogous, they BOTH burden the programmer > with arbitrary rules to govern the physical layout of the code. Python's forced indentation certainly doesn't burden me at all. I don't know about you, but I indent whether I have a block delimiters or not. Python doesn't force me to do anything I wouldn't do anyways. What *is* burdensome is having to use block delimiters, AND to make sure they are properly sychronized to the indentation. > Although > this layout may be considered more elegant from a readability standpoint, > it's the enforcement of the layout that is irritating to the more > Libertarian of us. It's a mindset difference similar to that between > Pascal and C++. Well, if you're complaining about your lack of freedom, then you're complaining about your freedom to write unreadable and misleading code. It's a freedom I don't care for (usually). > Having read Wall's comments on Slashdot, I think he is really just mildly > complaining about ridiculously long page-widths in his editor, not really > slashing Python seriously. He's just giving some props to his own baby at > the expense of another. (He had to say something, right?) You must agree > that Python can lead you to horizontal scrolling in your editor - the bane > of user interface design. No, not any more than C would. Do you not indent in C? If your C code runs against the margin, is your solution to simply stop indenting, and run all the blocks together? (If it is, then you have worse problems than being forced to indent.) And, as a matter of fact, I never exceed 79 columns in any of my Python code. And I use eight-space tab stops. And my editor doesn't have horizontal scrolling; it wraps. -- CARL BANKS http://www.aerojockey.com From tjenkins at devis.com Fri Sep 6 10:41:56 2002 From: tjenkins at devis.com (Tom Jenkins) Date: 06 Sep 2002 10:41:56 -0400 Subject: [DB-SIG] Re: What database should I use In-Reply-To: References: Message-ID: <1031323316.6785.9.camel@asimov> On Fri, 2002-09-06 at 10:29, Leif Jensen wrote: > > PostgreSQL, no doubt, if you use Linux, WinNT or possible WinXP ! > > Leif > I disagree. Don't get me wrong, we use PostgreSQL EXTENSIVELY. But for 2-3k records? These "requirements" don't require anything that powerful. I'd look at Access, pySQLite (which intrigues me), Gadfly. > > > On Thu, 5 Sep 2002, A wrote: > > > Hello, > > I am going to program a small application (in Python and wxPython) which consists about > > 2000 - 3000 records . Can you please recommend which database is the best for that. I > > use Windows. > > Maybe MS Access or FoxPro or MySQL or better? > > I want to keep the program as small as possible. > > Thanks > > Ladislav > > > > > > _______________________________________________ > > wx-users mailing list > > wx-users at lists.wxwindows.org > > http://lists.wxwindows.org/mailman/listinfo/wx-users > > > > > _______________________________________________ > DB-SIG maillist - DB-SIG at python.org > http://mail.python.org/mailman/listinfo/db-sig -- Tom Jenkins Development InfoStructure http://www.devis.com From emile at fenx.com Thu Sep 19 09:56:11 2002 From: emile at fenx.com (Emile van Sebille) Date: Thu, 19 Sep 2002 06:56:11 -0700 Subject: monetary applications (et al) References: Message-ID: Alex Martelli: > Doesn't seem to have done any damage to Python's standing in the > field of scientific computation -- on the contrary, decoupling the Out of curiousity, does python have any standing in the field of business accounting? Perhaps those with experience can chime in as to how this has been handled effectively. We learned long ago to keep all amounts in whole pennies. In python, we need to keep everything as longs and be careful not to slip up and allow normal ints. Not a problem, and one that int/long unification will resolve when it gets here. -- Emile van Sebille emile at fenx.com --------- From loewis at informatik.hu-berlin.de Mon Sep 2 12:31:26 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 02 Sep 2002 18:31:26 +0200 Subject: compiling extensions on linux References: <3D738D4E.35B6C712@mill.co.uk> Message-ID: Joe Connellan writes: > I'm trying to port an extension of mine from windows to linux and am not > sure how to include the myExtension.def file in the compile You shouldn't have a .def file in the first place - I recommend that you use distutils instead. > eg if I use > > g++ -shared -o myextension.so > > it compiles fine but I get the following error when importing it into > python > > >>> import myextension > Traceback (most recent call last): > File "", line 1, in ? > ImportError: dynamic module does not define init function > (initmyextension) Nothing to this respect is needed on Linux. Are you sure your module does define a initmyextension function? It might be that it defines initmyextension__Fv instead, since you compile your extension as a C++ program. You should compile it as a C program, unless it really is a C++ program, in which case you need to define the init function as extern "C". HTH, Martin From walterm at parque.homelinux.net Mon Sep 9 19:19:51 2002 From: walterm at parque.homelinux.net (Walter Moreira) Date: Mon, 9 Sep 2002 20:19:51 -0300 Subject: RPy / Win2k In-Reply-To: References: Message-ID: <20020909231951.GA21801@parque.homelinux.net> On Sat, Sep 07, 2002 at 01:19:13AM +0100, Duncan Smith wrote: > Hello, > Is there anyone out there who has successfully used RPy under > Win2k? I get the impression (from Brian Ripley) that it should be possible > to embed R under Win2k, but that it probably isn't straightforward. Can > anyone help? Cheers. Well, actually it is possible thanks to a patch from Rene Hogendoorn. I have been busy but I will release a Windows version soon. The changes in the source are not straightforward, indeed. I'll try to do it before end of september. Regards: Walter From cliechti at gmx.net Sun Sep 1 19:52:14 2002 From: cliechti at gmx.net (Chris Liechti) Date: 2 Sep 2002 01:52:14 +0200 Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: holger krekel wrote in news:mailman.1030921281.8891.python-list at python.org: > Chris Liechti wrote: >> "Robert Oschler" wrote in >> news:wmvc9.21757$FJ1.3181934 at e3500-atl1.usenetserver.com: >> > Some interesting tidbits I >> > found while trying out your suggestions, as you will see in the >> > two ".py" files that follow, I discovered that to create a method >> > you can dynamically add to a class _instance_, you need to omit the >> > 'self' parameter in the method declaration. For a method you add >> > dynamically to a class definition itself, then you must include the >> > 'self' parameter in the method declaration. If not, you will get >> > an argument count mismatch complaint from the interpreter. >> > Fascinating stuff. >> >> that's just the differece between a "function" and a "method". a >> method works on an object and that is passed explicit as first >> argument. "explicit is better than implicit" (you can read this and >> some other design ideas by typing ">>> import this" ;-) >> >> > I'm running 2.1.1, anybody know if 2.2.2 is going "disable" either >> > of these abilities? (class or class instance dynamic method >> > addition). I saw a note about such activities requiring a >> > "dynamic" keyword, which is fine. I'd really miss either of these >> > abilities. >> >> nah. "classic classes" stay the way they are and are available until >> 3.0 new style classes, those that inherit from "object" or "type", >> will need the marking as "dynamic". > > Can you give a pointer for further explanation? Can't believe it :-) robert already posted a link where its mentioned. i think i saw it too in that thread. i might have choosen the wrong words... - it was it _was_ discussed, and as it looks, it was in the 2.2a release. here is an older "Unifying types and classes in Python 2.2", which still mentiones __dynamic__, newer versions of it don't: http://216.239.37.100/search?q=cache:Nld8Sg3osq0C:www.etsimo.uniovi.es/pyth on/2.2/descrintro.html+__dynamic__&hl=en&ie=UTF-8 chris -- Chris From naveed_iq at hotmail.com Wed Sep 25 13:33:21 2002 From: naveed_iq at hotmail.com (Naveed Iqbal) Date: 25 Sep 2002 10:33:21 -0700 Subject: Whats the Difference between Windows XP and Windows 98.... Message-ID: <3fda493d.0209250933.1a99079f@posting.google.com> Whats the Difference between Windows XP and Windows 98....when it comes to the win32 extensions to python? I used the win32ui and win32com.client modules to print to a printer from windows. the output from the XP machine comes out fine, but the output from the 98 machine looses its formating. I am using a Smart Label Printer 200. this label printer has drivers for all windows family OS's. does anybody have an idea as to what is going on? thanks Naveed From lu_gio at hotmail.com Tue Sep 24 02:57:16 2002 From: lu_gio at hotmail.com (Max) Date: Tue, 24 Sep 2002 08:57:16 +0200 Subject: PyGame + PyOpenGl + ZBuffer? References: <3D8EDCEF.70F827F6@hotmail.com> Message-ID: <3D900CCC.13321011@hotmail.com> I've inserted the set_attribute, then verify it was set. pygame.display.gl_set_attribute(GL_DEPTH_SIZE, 16) pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF ) print "ZBUFFER:",pygame.display.gl_get_attribute(GL_DEPTH_SIZE) print pygame.display.get_driver() The display.get_driver() displays "directx"... DIRECTX????!!!!! WHY??? Is it normal? Inside the draw loop, I test if the depth test is still working... print "Enabled: ",glIsEnabled(GL_DEPTH_TEST) It's a simple scene with four GL_QUADS overlapping; two with z=0 and two with z=0.5 glTranslate(100,100,0.5) glTranslate(100,100,0.0) with a depth range from 0 to 1 glDepthRange(0.0,1.0) BUT... the zbuffer isn't still working... also I get a very low framerate. HELLLP!! Pete Shinners wrote: > Max wrote: > > I found my code is not working well in all computers: with a SiS 300/200 > > graphic card, the Z buffer seems disabled. > > > > The OpenGL initialization code is: > > > > pygame.init() > > pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF|HWSURFACE,32 ) > > glEnable(GL_DEPTH_TEST) > > glDepthFunc(GL_LESS) > > glDepthRange(0,1) > > > > How can I force Opengl to utilize ZBuffer? > > pygame has a function to control extra setting for opengl. it must be > called before display.set_mode(). you'd probably want to pass something > like "pygame.display.gl_set_attribute(GL_DEPTH_SIZE, 16)". perhaps try > different sized depths? > > http://pygame.org/docs/ref/pygame_display.html#gl_set_attribute > > you might also try testing with GLUT, which usually builds with pyopengl. From amk at amk.ca Sat Sep 7 08:43:51 2002 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 07 Sep 2002 12:43:51 -0000 Subject: Daemonize? References: Message-ID: In article , Richard Jones wrote: > Note you can also just assign an object with a write() method that does > nothing to sys.std(out|err) and a similar object to sys.stdin. Why the second > fork, btw? No, reassigning sys.stdin and stdout isn't sufficient; you really, truly have to close those file descriptors. This is complicated slightly by the fact that Python's .close() method for stdin/stdout/stderr doesn't actually do anything. The second fork ensures that the parent PID of your daemon process is 1. I think it also ensures that the daemon is in a process group of its own. Here's the daemonize function I use; I think Greg Ward originally gave it to me. def daemonize (self): # Fork once if os.fork() != 0: os._exit(0) os.setsid() # Create new session if os.fork() != 0: os._exit(0) os.chdir("/") os.umask(0) os.close(sys.__stdin__.fileno()) os.close(sys.__stdout__.fileno()) os.close(sys.__stderr__.fileno()) --amk From hwlgw at hotmail.com Sun Sep 1 17:08:51 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 1 Sep 2002 14:08:51 -0700 Subject: Python IPC options References: <1030829572.943495@irys.nyx.net> <3D715160.2020109@itamarst.org_NOSPAM> Message-ID: Itamar Shtull-Trauring wrote: > Twisted (http://www.twistedmatrix.com) has ... Um, I admire the Twisted project and I hope it will mature someday. The Twisted people do not miss much occasions to mention Twisted. Which is understandable but I think they should not do that until the Twisted documentation is better. You really need more tutorials, step-by-step stuff. And also for Windows users, otherwise at least mention it is aimed at *n*x people until then. >From the link you provided: % mktap ... % twistd -f ... They do not work and I just downloaded Twisted (.exe and .zip for docs). I am using Windows yes, like most people. No idea how to do ``mktap'' using Windows so what do you think people do next? They remove Twisted. And they think 'Wasted some more time with open source stuff'. And that is a shame and that is not what you want. Please stop coding and working on functionality until you have good docs. You have a doc explaining the difference between a framework and a library, that is good. More of that! About daemons, servers, internet protocols, tutorials, whatever. I think your project is great and I hope it will not die from the open-source-amateur-be-cool-read-the-source-virus. Open source is great but weak without good docs. :: It's not the mail volume that bothers me -- I can ignore 100s of messages a day very quickly. It's the time it takes to respond to all of them. -- Guido van Rossum, 20 Jan 2000 From hancock at anansispaceworks.com Thu Sep 26 15:08:28 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 26 Sep 2002 12:08:28 -0700 Subject: How to convert unicode References: <20020928160041.13325.57342.Mailman@mail.python.org> Message-ID: <3D935B2C.3E2E08E1@anansispaceworks.com> Hi Ladislav, I think you're going to have to be a little more specific about what exactly you want before people can help... Ladislav: > I have a script that downloads a webpage with characters that are not plain ascii.From the > web page header I can find out that there is UTF-8 coding( Unicode). I can display the page > properly in a web browser if I send from my script > "Content-Type: text/html; charset=UTF-8 " Right, you're telling your browser what kind of data its receiving, and it knows how to display it. > But I need to save the page( the text of the page) to a file and some time later import the text > to a database (MS Access or similar). > How can I download the file or write to a file so that the characters will be properly display in > the file and in the database as well? > Thanks for help This is actually sort of meaningless, since databases and files don't "display" data, they just "store" it. In general they don't care whether that data is 7,8 or 16 bits wide, as long as it's provided as a nice stream of bytes. (There are exceptions -- I think some databases might trim off the high bit, disallow "control characters", or nulls (0x00) for "text" fields, but even those usually provide a "binary" data type that won't mangle your data -- I can't address what MS Access does because I've never used it). The question therefore is what do you want to use to *view* the data in the file or database, and you need to specify that. If you want to view it with "basically everything", then you'll need to sacrifice portability and capability by converting to some localized encoding (the most common being ASCII, but that may not be the most appropriate for where you are). If that's okay, then this is a character-translation problem, and the result will *lose data*, which you need to be sure is okay. (This is because many applications still only support ASCII-style 8-bit encoding, despite much progress. If nothing else, lots of people are still using older software). I'm guessing you want to preserve all the data though, in which case, you're not talking about translating the data in the file or database at all. You instead need to be asking what software you can use (or how to configure your existing software if it can already do it) to correctly display UTF8 encoded unicode. You sacrifice some flexibility on the display side, but there are a lot of unicode-aware software out there already. If for some reason the software supports one of the other unicode encodings, but not UTF8, then you'll need to do a unicode-to-unicode translation, which won't lose data, but only change its representation. UTF8 is widely supported, though, so I think this isn't that likely. As you can see, we'd have to start making a lot of guesses to be more helpful than that (and I'd probably guess wrong!), so I'll stop and give you a chance to respond with what you want/need to use for display. :-D Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From peter at engcorp.com Tue Sep 24 20:18:17 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 24 Sep 2002 20:18:17 -0400 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 24) References: Message-ID: <3d9100c1$1@news.sentex.net> Dean Goodmanson wrote: > QOTW: "When something "is *EVERYWHERE*", how can it be "clearly VISIBLE" > at the same time?" - Alex Martelli > http://mail.python.org/pipermail/python-list/2002-September/123526.html > > "... [A]necdotally speaking I find Python development goes faster more as > a result of its very high readability than as a result of low loc/FP." > Peter Hansen For the record, this was from http://mail.python.org/pipermail/python-list/2002-February/089848.html although I have to say I have no idea what it means... if it ever meant anything. (Hansen's a real blowhard, you know.) (I also don't know why a posting from February made it in the September QOTW except as an accident. But didn't someone say there's no such thing as bad publicity? ;-) ) -Peter From tjreedy at udel.edu Fri Sep 20 00:42:43 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 20 Sep 2002 04:42:43 GMT Subject: e vs exp()? References: <3a838998.0209191933.1f22e977@posting.google.com> Message-ID: <7Hxi9.56777$216.2039933@bin4.nnrp.aus1.giganews.com> "Buckshot" wrote in message news:3a838998.0209191933.1f22e977 at posting.google.com... > Can anyone here explain why I'm getting different results from > e**2 and exp(2)? Which is more accurate? > > Python 2.2 (#1, Mar 27 2002, 14:56:58) > [GCC 2.95.3 20010315 (release)] on sunos5 > Type "help", "copyright", "credits" or "license" for more information. > >>> from math import * > >>> e**2 > 7.3890560989306522 > >>> exp(2) > 7.3890560989306504 ActivePython 2.2.1 Build 222 (ActiveState Corp.) based on Python 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from math import * >>> e**2 7.3890560989306495 # same as below to within roundoff, but not quite same... >>> exp(2) 7.3890560989306504 # matched your result exactly The last decimal digit reported for floats is almost always flakey. Both round to 7.3......650, so I suspect this is correct and e**2 on your machine is not. On the hypothesis that x**y is calculated as exp(y*log(x)), I tried >>> exp(2*log(e)) 7.3890560989306504 I expected this to end in ..495 so I am puzzled a bit also. How is e**x being calculated to give a different result? Answer in the Python source maybe, or in C library source. In some other situations, hypothesis seems correct >>> pi 3.1415926535897931 >>> sq = sqrt(2) >>> sq 1.4142135623730951 >>> pi**sq 5.0474972673709111 >>> exp(sq*log(pi)) 5.0474972673709111 but not in all >>> sq**pi 2.9706864235520198 >>> exp(pi*log(sq)) 2.9706864235520194 Using 2.0 gives same result as 2: >>> e**2.0 7.3890560989306495 >>> exp(2.0) 7.3890560989306504 >>> log(e) 1.0 Perhaps your system does not have e quite as correct: >>> e 2.7182818284590451 Terry J. Reedy From jdavis at empires.org Tue Sep 24 16:37:04 2002 From: jdavis at empires.org (Jeff Davis) Date: Tue, 24 Sep 2002 20:37:04 GMT Subject: cgi post problem References: <9aWj9.39314$V7.10439005@twister.socal.rr.com> Message-ID: These two files worked for me (see below). Let me know if you have any more problems. Regards, Jeff -------------py2.cgi-------------------------- #!/usr/bin/python2.2 import cgi def main(): try: form = cgi.FieldStorage() input = form.keys() print "Content-type: text/html" print print(""" test """) print "

",input,"

" print "" except: pass if __name__ == "__main__": main() ---------------py2.html------------------------------------------
jano wrote: > There was an error in my prior post. See ^^^^ > > > "jano" wrote in message > news:amq8av$2cum$1 at agate.berkeley.edu... >> >> >> "Jeff Davis" wrote in message >> news:9aWj9.39314$V7.10439005 at twister.socal.rr.com... >> > Hi, >> > >> > It looks as though you have a lot of code. It might be helpful to try >> > to narrow the problem further by removing a lot of the code unrelated >> > to > your >> > problem, which appears to be that "keys" does not contain any items. > After >> > you work that out, then put the other code back in. >> > >> > My first impression is that you have some "weird" form element names >> > because they contain the "/" character. That might be perfectly legal, > but >> > perhaps the cgi.FieldStorage class does not properly handle such >> > element names, or perhaps it considers such names erroneous. >> > >> > Next, it seems that the line "keys = form.keys()" might be out of >> alignment >> > with the rest of the code in it's block. Perhaps it's just the way it >> > looks after you copied your code into the post. >> > >> > Regards, >> > Jeff >> > >> > >> >> >> >> Yes, the problem is that keys does not contain any items. The 'weird' > names >> are not the problem, because i tried it also with regular 1-word names >> (no >> slashes), with the same results. Also, the keys=form.keys() line is >> properly indented in the code -- it was just a copy/paste problem. Here > is >> the code again, with the extraneous stuff stripped out: >> >> #!/usr/local/bin/python >> >> import cgitb; cgitb.enable() >> import sys, traceback, cgi >> >> def main(): >> try: >> form = cgi.FieldStorage() >> input = form.keys() >> >> print "Content-type: text/html\n\n" >> print(""" >> > 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'> >> >> >> test >> >> """) >> print "

",keys,"

" > > # ^^^^ should be 'input' not 'keys', as it > # is > in my script. > >> print "" >> except: >> pass >> >> if __name__ == "__main__": >> main() >> >> And the form is: >> >>
>> >> >> >> >> >> >>
>> >> >> The script, again, is currently just supposed to return the keys, which >> I > am >> expecting to be Name, PartNumber, etc., but it returns only an empty >> list. Any ideas. >> >> thanks, >> >> jano >> >> >> From dance_code at hotmail.com Mon Sep 30 11:12:38 2002 From: dance_code at hotmail.com (lee lion) Date: Mon, 30 Sep 2002 15:12:38 +0000 Subject: What's wrong with it? Message-ID: Hi, What's wrong with it? class Borg(object): _shared_state = {} def __new__(cls): return cls._shared_state class Singleton(Borg): def __new__(cls, arg): self = Borg.__new__(cls) self['val'] = arg return self def main(): x = Singleton('sausage') [snip] When running: >>> Traceback (most recent call last): File "D:\Programming\Python22\my_Python_programs\MyBorgSingleton.py", line 27, in ? main() File "D:\Programming\Python22\my_Python_programs\MyBorgSingleton.py", line 16, in main x = Singleton('sausage') ValueError: dictionary update sequence element #0 has length 1; 2 is required Could anyone tell me why it broke with that strange runtime error? Thank in advance, Lion "The best way of living is to earn a little more than you cost and to cost just as you need to." Li Hang _________________________________________________________________ ?????????????? MSN Messenger: http://messenger.microsoft.com/cn/ From aglyportREMOvethispart at nospam.yahoo.com Tue Sep 3 23:11:45 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Tue, 03 Sep 2002 20:11:45 -0700 Subject: Coredumps (Python 1.4) Message-ID: <3D7579F1.1090500@nospam.yahoo.com> PyObject * getfeed(char *feedfilename) { int p[2]; // create a pipe dolayout would generate output into if( pipe(p) < 0 ) { raise("piping failed"); } char cmd[256]; sprintf(cmd, "%s %s %d >/tmp/spt.dolayout 2>&1", sptbindir("dolayout"), feedfilename, p[1]); // dolayout is killed on SIGPIPE delivery caused by sptdumptags // termination FILE *fp = popen(cmd, "w"); close(p[1]); if(!fp) { raise("can't run dolayout"); } PyObject *layout[2]; layout[1] = PyFile_FromFile(fp, feedfilename, "w", fclose); // line buffering if(setvbuf(fp, 0, _IOLBF, 0)) { raise("can't make out_feed linebuffered"); } errno = 0; fprintf(fp, "lblheight\n"); fp = fdopen( p[0], "r" ); char s[128]=""; if(!fgets(s, sizeof(s), fp)) { // l_fatal? l_warn("there is nothing in the pipe"); }else{ if(verbose) fprintf(stderr, "lblheight is %s", s); } layout[0] = PyFile_FromFile(fp, feedfilename, "r", fclose); PyObject *tuple = PyTuple_New(2); PyTuple_SET_ITEM(tuple, 0, layout[0]); PyTuple_SET_ITEM(tuple, 1, layout[1]); ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ I coredump on this line ever since I linked with Electric Fence memory debugging lib. Any ideas why? This is with Python 1.4 on SCO. Any know issues with memory allocation there? I'm building 2.2 now, but it will take a while. This code seem to work fine on Linux. return tuple; } From martin at v.loewis.de Thu Sep 5 19:39:49 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 06 Sep 2002 01:39:49 +0200 Subject: Python Source Code Documentation References: <9FQd9.324581$Aw4.13464627@bin2.nnrp.aus1.giganews.com> Message-ID: "Terry Reedy" writes: > When I looked a few years ago, I mentally divided the source files > into four groups: > compilation phase (a few files) > interpretation phase (1 file, the main loop -- ceval.c?) > builtin datatypes (one for each -- int, long, tuple, etc -- each > with similar structure) > other There is the obvious division Parser, Python, Modules. Python can be further subdivided as you indicate. Regards, Martin From syver-en+usenet at online.no Mon Sep 9 17:35:02 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Mon, 09 Sep 2002 21:35:02 GMT Subject: Undocumented file behaviour (mode='r+') Message-ID: It would be nice for those of us who are not familiar with all the in's and out's of file processing to include in the documentation for file objects the behaviour of the write and read methods when opening a file for updating ('r+' or 'rb+'). I finally understood what was happening when I looked up the MSDN C-runtime library documentation for fopen. Before that I was pretty amazed that my calls to write failed to have an impact on the file that it was called on. Pretty that both write and read fails without notice methinks, but when that is the behaviour of the underlying library I understand it might be difficult to fix. Here's the behaviour I am talking about: class FileBugTestForWin2k(unittest.TestCase): """ Demonstrates that you have to do a flush after writing, if you are gonna read and a seek after reading if you are gonna write. It seems that the MS documentation is faulty, the unix man page documents the same behaviour as we're seeing here """ def setUp(self): f1 = open('aTestingFile.bin', 'wb') f1.write('lots of shit') f1.close() def tearDown(self): import os os.unlink('aTestingFile.bin') def testFailureWithoutSeek(self): f2 = open('aTestingFile.bin', 'rb+') assert f2.read(2) == 'lo' f2.write('s') # here is the bug, nothing is written to the file f2.seek(0) # should have been 'loss of shit' but write fails silently self.assertEquals('lots of shit', f2.read()) def testFailureWithFlush(self): """ This should be successful according to the docs """ f2 = open('aTestingFile.bin', 'rb+') assert f2.read(2) == 'lo' f2.flush() # MS C-runtime docs say we have to flush or # seek when switching from read to write self.assertRaises(IOError, f2.write, 's') # write fails here with # errno 0 def testSuccessfulWithSeek(self): f2 = open('aTestingFile.bin', 'rb+') f2.read(2) f2.seek(2) # ATTENTION, I didn't know that you had to seek when # switching between read and write operations on the file. f2.write('s') f2.seek(0) self.assertEquals('loss of shit', f2.read()) def testWriteToReadFailure(self): f2 = open('aTestingFile.bin', 'rb+') f2.write('s') assert len(f2.read()) > 300 # reads a load of crap def testWriteToReadFailure(self): f2 = open('aTestingFile.bin', 'rb+') f2.write('s') # advancing file pointer 1 step into the file f2.flush() self.assertEquals('ots of shit', f2.read()) # reading from seek(1) -- Vennlig hilsen Syver Enstad From jubafre at brturbo.com Mon Sep 23 20:52:07 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Mon, 23 Sep 2002 21:52:07 -0300 (GMT-03:00) Subject: file = open(path,'wb')????? Message-ID: <611064730.1032828727023.JavaMail.nobody@webmail2.brturbo.com> i open the a file for writing in a binary mode, but doesnt work final3=['0020 0000x9', '0030 0000xa', '00B4 0000x8', '0030 0000xb', '00F0', '0001', '0003', '0005'] destino=raw_input("Digite o nome do arquivo .mem: ") f = open(destino,'wb') f.write('\x03AHM ') for i in final3: f.write(i+' ') f.close() i open the file in the notepad and my file appears like a text file and not as a binary file, i dont know why?? >>file.mem AHM 0020 0000x7 0030 0000x8 0010 0000x9 00F0 0003 0002 0000 >>i want the file like this, how?? AHM € 0 ?  ƒ ? Juliano Freitas www.gebrasil.hpg.com.br From aleax at aleax.it Wed Sep 25 06:26:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 10:26:53 GMT Subject: comparing all values of a list to regex References: Message-ID: Manuel Hendel wrote: > I have to compare all values of a list to a regex. If the regex > matches all list items the list should be added to a new list. If the > regex matches just one list item, the list should be added to another > new list. And last but not least, if the regex doesn't mutch at all, > the list should be added again to another new list. > > Can someone help me with this? This is driving me crazy. E.g.: num_matches = [ there.match(item) is not None for item in alist ].count(1) if num_matches == 0: againanothernewlist.append(alist) elif num_matches == 1: anothetnewlist.append(alist) elif num_matches == len(alist): anewlist.append(alist) Note that there's some ambiguity on what to do if alist is empty -- literally this is BOTH "matches all list items" AND "doesn't match at all". Here I've chosen the second interpretation, but depending on your specs you can choose to test num_matches in different ways. Alex From skip at pobox.com Mon Sep 9 21:26:33 2002 From: skip at pobox.com (Skip Montanaro) Date: Mon, 9 Sep 2002 20:26:33 -0500 Subject: how to build wxPython w/ Sun's C++ compiler? In-Reply-To: References: Message-ID: <15741.19017.938561.815463@12-248-11-90.client.attbi.com> >> How do I convince it to use CC for files with .cpp extensions. Martin> Currently, you cannot: distutils does not support usage of Martin> separate tools for C and C++; feel free to contribute patches. I received a little frontend script due to Robin Dunn which did the trick for me. It examines the args on the command line. If any end in ".c" it assumes C, otherwise C++. I realize that's a hack. As for patches, it seems to me that distutils needs a generic way to override such settings (CC, CFLAGS, LDFLAGS, etc) via command line arguments, environment variables or ConfigParser files. It's not clear which way would be most Pythonic. I'd lean toward environment variables, but that's just because the setup.py command line is cluttered enough as it is and I'm a Unix-centered geek. Skip From campbells4 at ozemail.com.au Fri Sep 20 12:31:08 2002 From: campbells4 at ozemail.com.au (Alistair Campbell) Date: Sat, 21 Sep 2002 02:31:08 +1000 Subject: general thoughts References: Message-ID: Hi, I am a bit in the same position ben. I am a psychologist by profession but I have always been interested in programming. But, there is no way I would do it as a job. I think doing it for other people would be too full on for me. I get my inspiration for things to program from my other interests. So, I am in the middle of producing a computerised assessment of executive brain function. Next I want to write a program that enables me to develop and administer questionnaires, surveys, and semi-structured interviews on a PC (even TCP/IP!) and link it back to a central clinical information database. Then I would like to write a small statitistics program that enables users to compute clinical significance of change pre and post treatment. I would also like to expand this to more of a suite of obscure statitics tools in the social sciences. I also have a project in mind to write a program that does a thing called repertory grids. All in all these are areas of psychology that I have an interest in anyway and the idea of programming aspects of them simply comes because I have the programming as a tool. If I were you I'd stick to programming in your other domain of knowledge first so that you're not having to learn the language and the knowledge at the same time. If you have the knowledge it is then technical thing about how to automate the process as efficiently and as elegantly as possible. All the best. Alistair From maxm at mxm.dk Thu Sep 26 14:05:16 2002 From: maxm at mxm.dk (Max M) Date: Thu, 26 Sep 2002 20:05:16 +0200 Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> Message-ID: <3D934C5C.4000603@mxm.dk> Pat Notz wrote: > @ = "at" > ! = "bang" > . = "dot" > * = "star" > > Is there a short (one or two syllable) pronounciation for "__" (double > underscore). "Underscore underscore" and "double underscore" are kind > of long. Somthing like "splat"? Anyone? _ = 'under' __ = 'under-under' regards Max M The reason I don't reach any higher is that I stand on the shoulders of midgets. From imbosol at vt.edu Mon Sep 23 23:38:44 2002 From: imbosol at vt.edu (Carl Banks) Date: Mon, 23 Sep 2002 23:38:44 -0400 Subject: Three dumb questions (ordered by dumbness descending) References: Message-ID: Steven Feil wrote: > On Mon, 23 Sep 2002 16:03:21 -0500, Thorsten Kampe wrote: > >> Okay, here they are: > > Ok, I'll take a stab at the first two questions. I do think that a > little more clarity on your part could make it a bit easer. > > The first thing to remember is that Python is a dynamically typed > language. It is typed and each object has a type, It would be a little > easer if you would disclose the type for each object you are referring > to. > > >> 1. Why is 'zip(zip(x)) != x' (should be the same because it's the >> transposed) > [snip] > > I will need to know more about where you got zip from. It's a builtin, since Python 2.0. Very handy for when you want to loop over two sequences side-by-side. For example: for x,i in zip(seq,range(len(seq)): print "Item %d of seq is %s" % (i,x) >> 2. Peter Norvig mentions in "Python for Lisp Programmers" some >> "don'ts": "[x] + y" and "x[1:]". Are there more things to avoid > > humm, "[x] + y", again it comes down to type. [snip] In this case, the types of x and y are obvious to someone familiar with functional programming. Yet I wonder what the point of these "don'ts" is. I imagine he means that adding and slicing lists is Python is not as efficient as it is in LISP? I wonder, then, what the recommended way do functional stuff like that. -- CARL BANKS http://www.aerojockey.com From tdelaney at avaya.com Thu Sep 12 19:09:14 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Fri, 13 Sep 2002 09:09:14 +1000 Subject: "str.contains(part)" or alternatives? Message-ID: > From: Stefan Schwarzer [mailto:sschwarzer at sschwarzer.net] > > Thank you (and all others) for their answers. I didn't expect > to get so many. > Btw, Greg, the .count approach is much nicer than ".find != -1". The .count approach can also be considerably slower - it must scan the entire string, rather than being able to stop when it first finds a match. Tim Delaney From maxm at mxm.dk Tue Sep 3 03:58:54 2002 From: maxm at mxm.dk (Max M) Date: Tue, 03 Sep 2002 09:58:54 +0200 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <1030962064.628232@ampungk.ozonline.com.au> Message-ID: <3D746BBE.4030008@mxm.dk> Carl Banks wrote: >>What would the equivalent of r"(.)(.)(.)\3\2\1" >>This means a "palindrome of 6 characters" >>But it is unlikely that the human readable processor would understand >>that (isn't it??) Why not just write the parts of the regex as named strings? like:: name = '[a-zA-Z0-9_.]+' at = '@' dot = '\.' topDomain = 'com|org|dk' email = name + at + name + dot + topDomain instead of:: email = '[a-zA-Z0-9_.]+@[a-zA-Z0-9_.]+\.com|org|dk' Well my syntax is most likely wrong as I suck at regex, but the meaning should be clear enough. From TuxTrax at fortress.tuxnet.net Sun Sep 22 04:13:49 2002 From: TuxTrax at fortress.tuxnet.net (TuxTrax) Date: Sun, 22 Sep 2002 08:13:49 -0000 Subject: cursor positioning and color Message-ID: Being new to python, I would like to know how one goes about such tasks as precise cursor positioning and output to screen in color. For instance, If I want to print a character or line, at line 10, column 18, in bright white on red, how would I accomplish this? Is there a python library specifically for setting up a text screen to look and function the way you want it to, without having to use a GUI? The SLRN screen is a good example. Obviously, text positioning and coloring commands are being utilized here, as well as such things as clearing the screen and controlled scrolling. How would these things be done in python, and what reference material is available on line? I couldn't find anything in the Python manual, so any URL's would be appreciated Cheers, Mathew -- TuxTrax (n.) An invincible, all terrain, Linux driven armored assault vehicle that can take as much fire as it gives ;-) Yes, I am a Penguin cult high priest. Flipper readings upon request. ROT13 this email address to mail me: bar jbeq abg guerr, uvtu qrfreg zna, ng lnubb qbg pbz From creyes at ea.com Thu Sep 12 21:33:53 2002 From: creyes at ea.com (Christian Reyes) Date: Thu, 12 Sep 2002 18:33:53 -0700 Subject: Problem with HTTPS request Message-ID: I got the following response when trying to make an HTTPS request.

SSL required to access this page

Then I read in the documentation the following Note: HTTPS support is only available if the socket module was compiled with SSL support. Does anyone know where i can get my hands on a socket module that was compiles with SSL support? TIA, Christian From cliechti at gmx.net Mon Sep 23 22:48:32 2002 From: cliechti at gmx.net (Chris Liechti) Date: 24 Sep 2002 04:48:32 +0200 Subject: Python and cgi and problem! References: Message-ID: Jon Ribbens wrote in news:slrnaov5q3.nrp.jon+usenet at snowy.squish.net: > In article , Chris Liechti > wrote: >> print '%s' % (filename, filename) > > I hope none of your filenames have '"', ">" or "&" in. yeah i avoid characters that are special to the shell in my filenames - i even don't use " " very often. sure there are improvements, but its a start. chris -- Chris From mcherm at destiny.com Wed Sep 18 12:38:09 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 18 Sep 2002 12:38:09 -0400 Subject: Python-style license? References: Message-ID: Michael Str?der wrote: > HI! > > In some Python modules there's only a note about a "Python-style > license". Now I wonder what that means. Any clues? > > Ciao, Michael. > http://www.python.org/2.2/license.html From manuel.klimek at web.de Fri Sep 20 14:27:11 2002 From: manuel.klimek at web.de (Manuel Klimek) Date: Fri, 20 Sep 2002 20:27:11 +0200 Subject: Embedding Python in C++ and get rid of it again Message-ID: Hi folks, I've got a problem: I'm coding on xpermud, a scriptable mud client. This one features multiple scripting languages (perl and python at the very moment). The big problem is, that we want the user to be able to choose his scripting language at runtime (saved, for example, in a bookmark). It was quite hard to get perl to do this part, but unloading the library and reloading it made this possible. At first this seamed to work with python, too. In fact, it does, as long as you don't start any modules that depend on .so files. They just don't find the symbols python exports. So I did lot's of research and found out that setting the LTDL_GLOBAL flag helps with this one. But then the python .so has it's symbols globally and can't be unloaded any more. Even worse, perl.so can't be started afterwards (probably) because of a symbol name clash. So why does python want to have "hard"-exported symbols in .so libraries? Only so that python module developers can be more "dirty" in their programming ways? I think from a software design point of view, that this can't be a good solution (and this was the _only_ thing where perl seemed to be designed better, big compliment to the python developer crew :-) Now, our current solution is to disable loading of other interpreters once python is loaded. I'm not really glad with this one. Does anybody know enough of python internals to hint me some other solution? We tried so far: - unloading the .so (doesn't work if there are global symbols) - just letting the .so stay in (makes perl crash when called) - forbidding the user to switch languages after going to python (which he probably'll do anyways ;-), but this is still annoying...) - not using LTDL_GLOBAL, but this disables the use of .so modules (for example time) Special question: Is there a different way to get the python modules find the symbols they need, some magic internal undocumented python function we could call on the C++ side...? thanks in advance for any hint, Manuel From awinston at scn.org Tue Sep 10 14:10:56 2002 From: awinston at scn.org (Alan Winston) Date: Tue, 10 Sep 2002 11:10:56 -0700 Subject: Pysol Solitaire for Windows wanted References: <2MPe9.47925$Jo.5395@rwcrnsc53> Message-ID: > There are bugs in the Windows code for the latest version > (4.80). IIRC, it also depended on a version of Tk which isn't the > standard. None of the problems were impossible to solve, but they were > a mild pain, and the result is *not* the same as the original, as the > supplied .pyc file is somehow built as a single file from multiple > source files. Ah. > The author is also effectively uncontactable, which makes getting > fixes included in the source pretty much impossible. > > It's a real pain, as PySol is a really good program. If anyone could > package it up again, I'm sure the result would be of value to a lot of > people... The update list included with the file encourages us to wait for version 5. I think I will go on waiting, using the available ( "Try going to http://www.gamehippo.com and search for pysol." ) PySol 4.60 in the meantime. Thanks, Alan From quiteblack at yahoo.com Mon Sep 23 04:00:57 2002 From: quiteblack at yahoo.com (black) Date: Mon, 23 Sep 2002 01:00:57 -0700 (PDT) Subject: os module and sys module~ Message-ID: <20020923080057.955.qmail@web21310.mail.yahoo.com> Hi, all~ I couldnt tell the difference between them immediately, and some same method confused me much, for example they both have "path" attribute but what's the difference ? --------------------------------- Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! -------------- next part -------------- An HTML attachment was scrubbed... URL: From max at alcyone.com Fri Sep 27 15:30:42 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 27 Sep 2002 12:30:42 -0700 Subject: file open verification References: <9eabe547.0209270710.17ca112d@posting.google.com> Message-ID: <3D94B1E2.77541C55@alcyone.com> John Howard wrote: > Situation - I have several files on an apache server that are being > accessed by > python programs that are receiving data from html forms. > > q1: How can the status of a file be checked? If two forms have been > submitted > and the data is being added to a common file, how do I know that data > from both forms are being written correctly to the common file? > > q2: Related to above - really more of a cgi question - does the apache > server keep all these file accesses separate some way? No, it's your job to keep them all separate. Not keeping them separate will cause disaster. Use lockfiles. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ An ounce of hypocrisy is worth a pound of ambition. \__/ Michael Korda Crank Dot Net / http://www.crank.net/ Cranks, crackpots, kooks, & loons on the Net. From jdavis at empires.org Tue Sep 24 05:23:17 2002 From: jdavis at empires.org (Jeff Davis) Date: Tue, 24 Sep 2002 09:23:17 GMT Subject: cgi post problem References: Message-ID: <9aWj9.39314$V7.10439005@twister.socal.rr.com> Hi, It looks as though you have a lot of code. It might be helpful to try to narrow the problem further by removing a lot of the code unrelated to your problem, which appears to be that "keys" does not contain any items. After you work that out, then put the other code back in. My first impression is that you have some "weird" form element names because they contain the "/" character. That might be perfectly legal, but perhaps the cgi.FieldStorage class does not properly handle such element names, or perhaps it considers such names erroneous. Next, it seems that the line "keys = form.keys()" might be out of alignment with the rest of the code in it's block. Perhaps it's just the way it looks after you copied your code into the post. Regards, Jeff jano wrote: > Hi, > > I am trying to post a form to a cgi script. The form is as follows: > >
> > > > > > >
> > At the other end, the updatexml.py file currently just echoes back the > form data, as follows (with some wrapper code): > > #!/usr/local/bin/python > > import sys, traceback, cgi > > excText = "" > > > def main(): > global excText > try: > form = cgi.FieldStorage() > keys = form.keys() > > print "Content-type: text/html\n\n" > print(""" > 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'> > > > CGI exception > /> > > > > """) > print "

** ",keys," **

" > print "" > > > except: > print "Content-type: text/html\n\n" > import time > errtime = '--- '+ time.ctime(time.time()) +' ---\n' > errlog = open('cgi_errlog', 'a') > errlog.write(errtime) > traceback.print_exc(None, errlog) > errlog.close() > print(""" > 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'> > > > CGI exception > /> > > >
> """) > print "

Sorry, a problem was encountered running > the > cgi script:


\n" > if excText != "": > print "

", excText, "

" > print "
" > > > if __name__ == "__main__": > main() > > ================== > > The output of the script is always an empty []. Does anybody know what > the > problem might be? In a previous thread, the problem was that the user > had instead of using name ="", but that is not the case > here. > > Thanks for any help. I have checked usenet and the python faq and used > google, to no avail. > > jano From propadovic.nenad at debitel.net Wed Sep 18 19:54:13 2002 From: propadovic.nenad at debitel.net (Nenad Propadovic) Date: Thu, 19 Sep 2002 01:54:13 +0200 Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> <20020918.191423.706043324.1365@x1-6-00-d0-09-7e-c7-3e.wido3.on.cogeco.ca> Message-ID: <3d89108d@news.ivm.net> Such a fast answer. Amazing! Thank you, Mark. It's my first news-posting, you see :) > > Zope would be a good choice. Personally, though, I would stick to a > combination of Apache and Python/PHP/Perl/etc for a project like this. > Your project will be fairly small (although the GUI and chart generation > may be somewhat complex). It can't be too huge if you plan to get it done > by November in your spare time! :) I'll have to make it simple :) > I think Python (with Apache) would be > a good choice. Is Apache ...simple... to work with? I know it's standard :) > One thing, you didn't mention was what languages you have used (you > mentioned what you wrote, but not what you wrote it in). If you mentioned > what languages you have worked with in the past could, that could help > people give you better suggestions. Ahm, yes that's a point. I've been doing a lot of C, a bit of C++ (don't know it well), VBA, Ingress/Open Road... But I realy want to do the stuff in Python. > It really depends. You may want to generate them as images. Or maybee > PDF's? Would PDF be a viable option for you? ReportLAB > (www.reportlab.com) has a very good PDF generating library for Python. > I've > worked with the library and it is amazing. That sounds great! Thanks a lot. Nenad From zopestoller at thomas-guettler.de Tue Sep 10 05:04:17 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 10 Sep 2002 11:04:17 +0200 Subject: run-mailcap in python? Message-ID: Hi! On Unix there is a script called run-mailcap, which opens the corresponding programm with the given file: run-mailcap foo.html --> Default browser starts On windows you can use a double-click with the explorer or use cygstart from cygwin. Is there a portable function in python which does this? E.g. run("foo.html") --> Browser starts run("foo.doc") --> Word starts thomas From vvenka1 at hotmail.com Tue Sep 3 03:26:13 2002 From: vvenka1 at hotmail.com (Venkat Venkataraju) Date: 3 Sep 2002 00:26:13 -0700 Subject: getch in python Message-ID: <75ca4e69.0209022326.4cde72e8@posting.google.com> Hi All Is there any function that behaves like getch() function in C? Venkat From thoa0025 at mail.usyd.edu.au Sun Sep 15 21:50:19 2002 From: thoa0025 at mail.usyd.edu.au (:B nerdy) Date: Mon, 16 Sep 2002 01:50:19 GMT Subject: [xml] convert funny chars to char entites? Message-ID: ive got a string "Il Est N?" and i want to put it into a xml document is there a quick and easy way to conver the funny characters to char entities so i can store them? or is there existing libraries? cheers From kmp at NO2SPAMatrium.fsnet.co.uk Sun Sep 22 08:13:48 2002 From: kmp at NO2SPAMatrium.fsnet.co.uk (Ken Payne) Date: Sun, 22 Sep 2002 13:13:48 +0100 Subject: Tk Getting a directory name Message-ID: HI everyone - I'm writing a Tk interface to an app and in it I want the user to choose a directory. There's an easy way to ask the user to pick a file - fileWanted=askopenfilename() but is there a similar way to ask for a directory? - Ken From praveen.patil at silver-software.com Thu Sep 19 09:43:11 2002 From: praveen.patil at silver-software.com (Praveen Patil) Date: Thu, 19 Sep 2002 14:43:11 +0100 Subject: How pass array from C to python function In-Reply-To: Message-ID: Hi , I have problem in passing array to python function. Please help me passing array to python function. Here is my 'C' program ----------------------- void RECEIVE_IL_STATE_S( int Instance , int vital_data[5]) { PyObject*arglist; PyObject* ret; PyObject* mylist; int count; mylist = PyList_New(5); for (count=0; count< 5; count++) { myint = PyInt_FromLong(vital_data[count]); PyList_Append(mylist,myint); } arglist = Py_BuildValue("O", mylist); ret = PyEval_CallObject(my_callback , arglist); Py_DECREF(arglist); Py_DECREF(ret); } Here is my Python program ------------------------- G_Logfile = None def TestFunction(a): G_Logfile = open('Pytestfile.txt', 'w') G_Logfile.write("%d \n"% a[0]) G_Logfile.write("%d \n"% a[1]) G_Logfile.close Cheers, Praveen. [ The information contained in this e-mail is confidential and is intended for the named recipient only. If you are not the named recipient, please notify us by telephone on +44 (0)1249 442 430 immediately, destroy the message and delete it from your computer. Silver Software has taken every reasonable precaution to ensure that any attachment to this e-mail has been checked for viruses. However, we cannot accept liability for any damage sustained as a result of any such software viruses and advise you to carry out your own virus check before opening any attachment. Furthermore, we do not accept responsibility for any change made to this message after it was sent by the sender.] From tim.one at comcast.net Sun Sep 29 13:52:04 2002 From: tim.one at comcast.net (Tim Peters) Date: Sun, 29 Sep 2002 13:52:04 -0400 Subject: ANN: Tim Peters' FixedPoint on SourceForge In-Reply-To: Message-ID: [dougfort] > This project makes Tim Peters' FixedPoint math class available > to the community as a SourceForge project. > > Check out http://fixedpoint.sourceforge.net [Aahz] > Should I change the link on my web site to point at this? According to me, yes -- I've only been able to make enough time to skim & ignore the email I've gotten on this, but from the parts I didn't ignore I think Doug has this very well in hand. Heck, he might even change it to do the kind of rounding some people think they expect but are unable to articulate . From theller at python.net Thu Sep 19 03:01:21 2002 From: theller at python.net (Thomas Heller) Date: Thu, 19 Sep 2002 09:01:21 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: Martin v. Loewis wrote: > Greg Ewing writes: > > >>So, the only way to find out whether a particular >>extension is safe to use in Stackless is to try >>it. > > > That is not true. It is more reliable to inspect the source code. > > In general, it is very easy to do so: if there are no callbacks to > Python, the module is stackless-safe. So win32all probably wxPython are incompatible with stackless? -- Thomas From javajohn at cox.net Thu Sep 12 10:25:11 2002 From: javajohn at cox.net (John Waycott) Date: Thu, 12 Sep 2002 14:25:11 GMT Subject: Coding Style: Quotes Message-ID: I'm curious if others have adopted any standards for choice of single vs. double quotation marks to delimit strings. A look through the standard library reveals the choice of one over the other is rather arbitrary. I suspect it really makes no difference, but the question has come up during a code review. -- John Waycott From fb at frank-buss.de Sat Sep 14 06:58:33 2002 From: fb at frank-buss.de (Frank Buss) Date: Sat, 14 Sep 2002 10:58:33 +0000 (UTC) Subject: question about dictionary type.. References: Message-ID: eugene kim wrote: > i'd like to have a dictionary which looks like > table = { category1 : { category2 : { category3 : 'garbage value' } } } > > category1 has many category2 > category2 has many category3 > > i expected > table[ 'computer' ][ 'language' ][ 'python' ] = 0 > to create {computer : { language : { python :0 }}} > table[ 'computer' ][ 'language' ][ 'java' ] = 0 > to becomes { 'computer' : { 'language' : { 'python' :0 , 'java' :0 }}} If you don't insist on your syntax, a little function is all you need: def add(tree, path, value): start=tree for key in path[:-1]: if start.has_key(key): start = start[key] else: start[key] = start = {} start[path[-1]] = value You can use it like this, with tuples and lists: >>> tree={} >>> add(tree, ('computer', 'language', 'python'), 'cool!') >>> add(tree, ['computer', 'language', 'java'], 'cumbersome') >>> tree {'computer': {'language': {'python': 'cool!', 'java': 'cumbersome'}}} Interesting is the line "start[key] = start = {}", because first "start[key] = {}" is evaluated, then "start = {}" (with "{}" being the same object as in the first assignment). You can check this with "dis", as I've read in another posting in this newsgroup: >>> def f(): a=b=c ... >>> import dis >>> dis.dis(f) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_GLOBAL 0 (c) 9 DUP_TOP 10 STORE_FAST 0 (a) 13 STORE_FAST 1 (b) 16 LOAD_CONST 0 (None) 19 RETURN_VALUE -- Frank Bu?, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From wolfson at midway.uchicago.edu Sun Sep 22 16:25:44 2002 From: wolfson at midway.uchicago.edu (Ben Wolfson) Date: Sun, 22 Sep 2002 20:25:44 GMT Subject: sys.ps2 assignment has no effect References: <3d8e0aae@news.sentex.net> Message-ID: On Sun, 22 Sep 2002 12:12:56 -0700, "Lance" wrote: >print '...' works correctly, showing ... Well? Don't keep us in suspense, what does it show? -- BTR You're going to set me up as a kind of slovenly attached pig that Jack Kornfeld can slice down in his violent zen compassion? -- Larry Block From skip at pobox.com Wed Sep 11 09:22:08 2002 From: skip at pobox.com (Skip Montanaro) Date: Wed, 11 Sep 2002 08:22:08 -0500 Subject: Large file support and stat vs stat64 in extension modules In-Reply-To: References: Message-ID: <15743.17280.884457.36169@12-248-11-90.client.attbi.com> If I simply use the stat() system call, I get an EOVERFLOW error (OSError: [Errno 75] Value too large for defined data type). It seems that I should be using the newer stat64() call, but: Did you #include ? Ben> 1. posixmodule.c appears just to use plain old stat(). I cannot Ben> figure out why I get errors and it works fine. Quite a Ben> mystery. In /usr/include/sys/stat.h on my Mandrake 8.1 system (very similar to your RH 7.2 I believe), stat is #defined as stat64 if __USE_FILE_OFFSET64 is defined, which it probably is if your system supports POSIX large files. Ben> 2. I don't know what #if defined's to put in to choose between Ben> stat and stat64 correctly. Shouldn't need anything. Ben> Does anyone know how to correctly stat a file within an extension Ben> module? Why does: Ben> struct stat st; Ben> res = stat("bigfile", &st) Ben> not work for me, but in posixmodule.c the same thing (apparently) Ben> is done and works fine? Note that in posixmodule.c references are made to a HAVE_LARGEFILE_SUPPORT macro. When #defined, it causes the output struct to be interpreted differently (the sizes of some fields change). You might scan through your configure.in file. If "long long" support is present and sizeof(off_t) is greater than sizeof(long) and sizeof(long long) is greater than or equal to sizeof(off_t), large file support is assumed. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From nospam at bigfoot.com Wed Sep 11 08:13:33 2002 From: nospam at bigfoot.com (Gillou) Date: Wed, 11 Sep 2002 14:13:33 +0200 Subject: Save session in python interactive console References: Message-ID: You ca have a look at the standalone ZODB (search from google) if you want to play with (almost transparent) persistant objects. --Gilles "newgene" a ?crit dans le message de news: a50631f6.0209091334.7d59476c at posting.google.com... > Hi, group, > After I was working at python interactive console(activepython > v2.2 at Win2000 platform), I am wondering if possible to save the > current session, so that I can load it again and continue the work > next time. Just like R or Matlab, etc. Although python is a > programming language, one of the best features I like is its > interactive console. By writting my own module, I can make it as my > personal working console. If saving session is possible, it will be > much more convinient. > The pickle module provided by python can save any object,but how > can I save all objects in current session? > > Thanks in advance > > > CW From fredrik at pythonware.com Wed Sep 18 14:23:56 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Sep 2002 18:23:56 GMT Subject: Tkinter:select directory dialog? References: <20020918105332.00910.00007029@mb-ch.aol.com> Message-ID: <0x3i9.13118$HY3.2916659@newsc.telia.net> Martin Franklin wrote: > > A nice graphical "choose a directory" Dialog would help. > > Does such a thing exist? > > > from tkCommonDialog import Dialog > class Chooser(Dialog): > command = "tk_chooseDirectory" > def _fixresult(self, widget, result): > if result: > self.options["initialdir"] = result > self.directory = result # compatibility > return result > > def askdirectory(**options): > return apply(Chooser, (), options).show() (hmm. I think I've seen that code before...) the askdirectory function and a Directory class (same as the Chooser above) was added to the tkFileDialog module in Python 2.2: from tkFileDialog import askdirectory directory = askdirectory( title="select directory", mustexist=1 ) if not directory: print "cancelled" else: print "selected", directory From marklists at mceahern.com Sat Sep 14 15:34:22 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 14 Sep 2002 14:34:22 -0500 Subject: Converting a string to time - simple task but don't know how to do it! In-Reply-To: <7A6D2E53461F2BF2.AC83A3D5E1A01468.48CC780BD6530537@lp.airnews.net> Message-ID: Try: import time s = "<>" t = time.strptime(s) I think strptime is only supported on Unix? So if you get an AttributeError when you try that, your best best is to use the mx.DateTime package (a google search should find that). mx.DateTime works like this: import mx.DateTime d = mx.DateTime.DateTimeFrom(your_time_string) d2 = mx.DateTime.now() diff = d2 - d1 print diff // m - From aglyportREMOvethispart at nospam.yahoo.com Thu Sep 5 21:12:39 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Thu, 05 Sep 2002 18:12:39 -0700 Subject: Memory fault - core dumped while compiling python 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> <3D765A05.6030004@nospam.yahoo.com> <3D768753.8030302@nospam.yahoo.com> <3D76A139.1030304@nospam.yahoo.com> Message-ID: <3D780107.9090907@nospam.yahoo.com> J. L. Schilling wrote: > bokr at oz.net (Bengt Richter) wrote in message > >>>[...] >> >>How about >> cc -v >>? > > > Just for the record, cc -V is the option on the SCO compiler > to report its version. It should show something like this > on an OSR 5.0.5 system: > > 217$ /bin/cc -V > SCO UNIX Development System Release 5.1.1A 27Jul98 ^^^^^^^^^^^^^^^^^^ 5.1.1A is what I have also. From robin at jessikat.fsnet.co.uk Sat Sep 21 04:50:10 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Sat, 21 Sep 2002 09:50:10 +0100 Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> <7xn0qcfafp.fsf@ruckus.brouhaha.com> <7xwupf52jx.fsf@ruckus.brouhaha.com> Message-ID: In article <7xwupf52jx.fsf at ruckus.brouhaha.com>, Paul Rubin writes >Christopher Browne writes: >> REALITY CHECK for a moment. >> >> What do you think A Real Live bank uses to compute interest? > >If I had to guess, I'd guess they use floating point. > >I do know that financial modelling software I worked on that was sold >to banks used floating point. Also, spreadsheets use floating point. > >But it's possible (likely even) that some bookkeeping applications use >BCD. One that I worked on actually used exact, multi-precision >rational arithmetic, but I think that's unusual. > >Note that the x86/x87 still supports BCD arithmetic in microcode. In >reality, though, programs that use BCD to keep track of money don't do >all that much arithmetic, so software emulation is plenty fast enough. Well I also worked in finance/research and I agree with Paul and Christopher. Most trading/research software uses FP, most transactions are computed using BCD. The thing about most real financial instruments is that they use fairly complicated sets of rules to calculate the actual interest and since the rules evolved before modern computers are mostly computable using fingers and counting. In particular almost all the calculations have to be with pre-specified precision and rounding rules. EG a bond pays fixed amounts of money at pre-specified intervals, no calculations are involved at all. Of course when I want to compute the yield or npv I need to do some arithmetic and FP is usually easiest and faster as well. Anyhow it seems to me that BCD is pretty good only for additive type calculations. I can't see that BCD is any better than FP at representing 1/3 unless we go fully rational, but that's another story. -- Robin Becker From gerhard.haering at gmx.de Fri Sep 20 01:50:09 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Fri, 20 Sep 2002 07:50:09 +0200 Subject: newbie seeks advise. In-Reply-To: <77c84db2.0209192137.51167ebb@posting.google.com> References: <77c84db2.0209192137.51167ebb@posting.google.com> Message-ID: <20020920055009.GA2163@lilith.ghaering.test> * akirasugiura [2002-09-19 22:37 -0700]: > Hi, > > I've been learning python for about a month. I had no prior knowledge > of programming. > > My question is, I have a tuple which is, data = (69, 40, 74, 41, 56, > 57, 38, 58, 26, 55). How I can make a function that picks up a largest > number from this "data" tuple. If "data" was a 'List' I would be able > to use "sort" but since sort doesn't work with tuple. I am stuck > here. max(data) Now that was too simple, wasn't it? If you want to program a max() function yourself, you can convert the tuple to a list using list(data), then sorting it, then finding the largest element yourself. -- Gerhard From syver-en+usenet at online.no Tue Sep 17 06:37:52 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 17 Sep 2002 10:37:52 GMT Subject: Book for win32? References: <3D868FA2.4040503@nospam.free.fr> Message-ID: laotseu writes: > I'd just add one advice : if you're not familiar with the w32 API, go > and get yourself a good reference of it ! (I think you can get the > win32 API ref on borland's site, with the free version of bcc55). > Yes, that is good advice. But isn't it just as well to use microsoft's own version at http://msdn.microsoft.com. -- Vennlig hilsen Syver Enstad From gerhard.haering at gmx.de Fri Sep 20 14:56:13 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 20 Sep 2002 18:56:13 GMT Subject: Newbie questions: write permission, interpreter minimizing References: Message-ID: pcarey at lexmark.com wrote in comp.lang.python: > I use PythonCardPrototype to make UI's. > When launching these apps (double-clicking), > the interpreter launches (as it should) and remains in the > background (as it should)... but is there any way to automatically > minimize the interpreter? You can give your script a .pyw instead of a .py extension, which will result in the script being launched with pythonw.exe intead of python.exe. This way, you have a normal Windows GUI app, without any console window. OTOH it's harder to track exceptions, but AFAIK wxPython (and thus maybe PythonCard, too) has a way to show exceptions in a GUI window. -- Gerhard From christophe.delord at free.fr Mon Sep 9 16:56:54 2002 From: christophe.delord at free.fr (Christophe Delord) Date: Mon, 9 Sep 2002 22:56:54 +0200 Subject: a re question References: Message-ID: <20020909225654.44e16058.christophe.delord@free.fr> match applies the regular expression at the beginning of the string. Try 'search' instead: >>> s='001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23' >>> p = re.compile(r'(\d{9,} {3,}\d)') >>> print p.match(s) None >>> print p.search(s) <_sre.SRE_Match object at 0x400aed20> >>> print p.search(s).groups() ('123456789 7',) You can also use a different expression: >>> p = re.compile(r'.*(\d{9,} {3,}\d)') >>> print p.match(s) <_sre.SRE_Match object at 0x400aed20> >>> print p.match(s).groups() ('123456789 7',) Christophe. On Mon, 09 Sep 2002 16:10:39 -0400 Rajarshi Guha wrote: > Hi, > I have a file with lines of the format: > > 001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23 > 001 Xya FGh 143557789 7 100 09/05/2002 20:23:23 > > I am trying to extract the 9 digit field and the single digit field > immediatley after that. > > When I use Visual Regexp to try out the regexp > > (\d{9,} {3,}\d) > > it highlights the 2 fields exactly. > > But when I use the following Python code I get None: > > >> s='001 Abc D Efg 123456789 7 100 09/05/2002 20:23:23' > >> p = re.compile(r'(\d{9,} {3,}\d)') > >> print p.match(s) > >> None > > Could anybody point out where I'm going wrong? > > Thanks, -- (o_ Christophe Delord _o) //\ http://christophe.delord.free.fr/ /\\ V_/_ mailto:christophe.delord at free.fr _\_V From loewis at informatik.hu-berlin.de Wed Sep 4 14:38:30 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 04 Sep 2002 20:38:30 +0200 Subject: Why read-only nested scopes? References: Message-ID: Gon?alo Rodrigues writes: > >Gon?alo Rodrigues writes: > > > >> So why hasn't this been extended when nested scopes were introduced, > >> e.g. by reusing the global directive or some other one? > > > >I think the main reason is that nobody could propose an acceptable > >syntax. Reusing the global directive does not work. > > Can you explain why it does not work? Consider x = 1 def foo(): x = 2 def bar(): x = 3 def baz(): global x x = 4 If you invoke baz(), which of the variables is changed? How do you denote that you want to change the others? Regards, Martin From wlfraed at ix.netcom.com Tue Sep 24 22:04:03 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 24 Sep 2002 19:04:03 -0700 Subject: Pythonwin (win32all build 148) on Python 2.2.1 on Win2K, bogus syntax e References: Message-ID: A. Dimsdale Fetus A. Moser fed this fish to the penguins on Tuesday 24 September 2002 05:04 pm: > I am running Pythonwin (win32all build 148) on Windows 2000 > Professional with Python 2.2.1. When I attempt to run a Python script > in it, it halts the running of the script on supposed syntax errors, > which are completely bogus. Examples: > First line of our (Aaron L. Dimsdale and Alex S. Moser) first > semi-significant Python script, called fight: > """fight.py 5.0 -- crappy primitive fighting game by alex s. moser & > aaron l. dimsdale""" > ^^^ (note: no linebreak in that line) > """if one of the players does not say "atk" or "rest" when asked, they > will \ forfeit their turn""" > > Pythonwin barfed on the quote marks marked by carets, returning: > "Failed to run script - syntax error - invalid syntax". > I removed those quote marks and the quote marks at the beginning of > the second documentation line, and left those two lines as one string. Is that supposed to be "doc-string"? (since it isn't assigned to anything?)... Try: """ fight.py 5.0 -- crappy primitive fighting game by alex s. moser & ... if one of the players does not say "atk" or "rest" when asked, they will forfeit their turn """ Triple quotes work to delimit multiple line strings. > Then, several lines later: > > p1char = str(raw_input("Player 1, choose your character class: ")) I'd almost suspect a misplaced quote mark somewhere, but I presume Pythonwin is color-coding properly... -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From akakakhel at attbi.com Mon Sep 9 20:54:52 2002 From: akakakhel at attbi.com (Ali K) Date: Tue, 10 Sep 2002 00:54:52 GMT Subject: IDLE Message-ID: Why won't my IDLE work? From brueckd at tbye.com Sun Sep 15 23:06:40 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Sun, 15 Sep 2002 20:06:40 -0700 (PDT) Subject: can wxpython do this? In-Reply-To: Message-ID: On Mon, 16 Sep 2002, Erick wrote: > Thank you very much Lothar. > > > > There is no problem to setup an installer easily that takes > > Python,WXPysthon and whatever you need. It simply blowes up the > > installer package size. > > Isn't this the way to distribute wxpython apps? Yeah, it is. He meant "blows up" as in "bloats" rather than "explodes/breaks". -Dave From nanotech at europa.com Fri Sep 13 12:29:10 2002 From: nanotech at europa.com (czrpb) Date: Fri, 13 Sep 2002 09:29:10 -0700 (PDT) Subject: Help with regular expression using findall and .*? In-Reply-To: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220D18@hendrix.empolisuk.com> Message-ID: Harvey: Great thanks!! And thanks for sticking to my question's requirements. Ok, this is what we thought around here. But what I do not understand is why any backtracking data is being kept? The '?' in '.*?' means it is non-greedy right? When would backtracking ever occur using '.*?'? What am I missing? < czrpb wrote > > > > Could anyone help out with rewriting (still using regular expressions) > > the following so that it does not cause an exception: > > > > import re > > > > s1=('macro\n'+'a'*200+'\norcam\n')*10 > > s2=('macro\n'+'a'*20000+'\norcam\n')*10 > > > > p=re.compile(r'macro.*?orcam',re.DOTALL) > > > > for x in re.findall(p,s1): > > print x > > > > for x in re.findall(p,s2): > > print x > > > > thanks!! Quentin Crain > > > > You need to be very careful about using .*? as the engine "only" allows 10,000 backtracks > > Try this > > p = re.compile('macro(?:[^o]+|o(?!rcam))*orcam') > for x in p.findall(s2): > print x > > HTH > > Harvey > From gerhard.haering at opus-gmbh.net Wed Sep 4 10:55:05 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 4 Sep 2002 14:55:05 GMT Subject: How to force built-in commands over imported. References: <3D761C39.4020802@akst.tn.tudelft.nl> Message-ID: Maurice van de Rijzen wrote: > Dear all. > I'm a newbie on the field of python, therefore the answer to my question > may be simple. > There is a built-in commans called open(fileName). There is also a > open() command in the os-module open which needs more than the fileName. > Originally I didn't import the os-module and everything worked fine. > However, when I imported the os-module I received an error that open > needed more arguments. How can I force to take the built-in open() > instead of the open() in the os-module. The technical answer is to use __builtins__["open"]. A good advice is to avoid the use of "from ... import *" in most cases. Just "import os", then use the desired function by prefixing it with the module name, like "os.open". -- Gerhard From strat_addict at yahoo.com Sat Sep 21 21:51:24 2002 From: strat_addict at yahoo.com (strat_addict) Date: 21 Sep 2002 18:51:24 -0700 Subject: COM, Word problem Message-ID: hello all, I'm getting a strange error when calling Word with Dispatch. I just noticed it, since I haven't played around with Word in quite some time. Anyway, here is what is getting spit back: >>> from win32com.client.dynamic import Dispatch >>> word = Dispatch("Word.Application") Traceback (most recent call last): File "", line 1, in ? File "C:\PYTHON21\win32com\client\dynamic.py", line 84, in Dispatch IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch,userName,clsctx) File "C:\PYTHON21\win32com\client\dynamic.py", line 81, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\PYTHON21\win32com\client\dynamic.py", line 72, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147417846, 'The message filter indicated that the application is busy.', None, None) I've seen some book code that doesn't use dynamic in the import statement and tried this to no avail. All other applications work (Excel, Access, even Vim) I've looked at some bug reports on the board that are similar, but I can't even create an instance. Has anyone had a similar problem? Just trying to get a sense of what I should try next. All help is appreciated, strat addict From aleax at aleax.it Fri Sep 27 03:34:40 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 27 Sep 2002 07:34:40 GMT Subject: Silly question about ungzipping a file References: <7396d2b2.0209261311.1fdd2d3a@posting.google.com> Message-ID: Lemniscate wrote: ... >>>> import gzip >>>> myFile = gzip.open('LL_tmpl.gz') >>>> file('output.txt', 'w').write(myFile.read()) >>>> > > Now, is there any way to do this so that less memory is used? I mean, import shutil shutil.copyfileobj(myFile, open('output.txt', 'w')) > 129MB. I'm sure I'm just missing something simple, but why is that? I think the reason you're missing this simple something is that you are not entirely familiar with Python's rich standard library -- a defect common to us all (I don't recall _every_ useful module either:-). A partial help is /F's "Python Standard Library" (O'Reilly) -- it won't magically infuse you with knowledge of every such module, but by giving at least one example script for each module in the library (all in a remarkably concise 280 pages!) it makes it quite a bit more likely that more modules will stay in your subconscious memory. Python's online reference, Beazley's New Riders book, my Nutshell when it comes (the delay ain't my fault THIS time - the complete, technically-revised draft is currently in the editor's hands!-), each give a different perspective on Python's standard library, and enhance the likelihood that you'll know where to find excellent code ripe for reuse. Probably the best single piece of advice is the one in the Python online docs -- "sleep with the Library Reference under your pillow" (and use a thin pillow, so that the knowledge has an easier time filtering up into your brain:-). Alex From vtail at yandex.ru Mon Sep 30 12:56:23 2002 From: vtail at yandex.ru (vtail) Date: 30 Sep 2002 09:56:23 -0700 Subject: McMillian installer + win32com.client.constants - how to use them together? Message-ID: <9ff6b66.0209300856.5fcdf961@posting.google.com> Greetings, can anybody please explain me the Right Way to use McMillian installer with application that uses constants from MSWord library? I've generate them with win32com/client/makepy.py and use them in my code via ====> import win32com.client ... a = win32com.client.constants.wdBlack # application crashed here ... <=== When I build .exe from my applications it is crashed on marked line with AttributeError exception. I've tried to study this subject myself, but now I'm totally confused with all this gencache.EnsureModule(), prog_id, CLSID etc. I can't find any clear documentation on the subject. I'll greatly appreciated any help on this, even RTFM links ;). Victor. From debl2nonosabsolutelynospam at bellatlantic.net Mon Sep 9 21:48:51 2002 From: debl2nonosabsolutelynospam at bellatlantic.net (David Lees) Date: Tue, 10 Sep 2002 01:48:51 GMT Subject: IDLE References: Message-ID: <3D7D4F84.318CDB0F@bellatlantic.net> This is a really great group, with lots of helpful folks, but few of them are mind readers :) Why don't you describe your hardware, OS, Python distribution, a description of how you installed and exactly what you mean when you say IDLE does not work. david lees Ali K wrote: > > Why won't my IDLE work? From tim.one at comcast.net Thu Sep 19 00:00:58 2002 From: tim.one at comcast.net (Tim Peters) Date: Thu, 19 Sep 2002 00:00:58 -0400 Subject: Remarks to Python 2.3 In-Reply-To: <20020918222421.328088eb.use-net@schabi.de> Message-ID: [Markus Schaber, on 2.3 features] > ... > - Mutable sets support some in-place operations - should those, just as > the in place operations on lists, like sort(), return None instead of > the new list to make clear that they are in place operations and for the > sake of consistency? Yes, and that's already been done. The docs may be lagging here: be a prince and submit a doc patch! From jhndnn at yahoo.com Thu Sep 26 19:46:14 2002 From: jhndnn at yahoo.com (John Dunn) Date: 26 Sep 2002 16:46:14 -0700 Subject: Changing global variables in embedding Python Message-ID: <2cc96dc7.0209261546.22f71021@posting.google.com> Hello- I have embedding Python in a C++ application. All is well, except I cannot figure out how to modify globals via Python script. After I load in my script files, I do this- module = PyImport_AddModule(""); dict = PyModule_GetDict(module); PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins()); PyObject* args = PyTuple_New(1); ... fill out arguments to function here.... PyObject* func = PyDict_GetItemString( dict, func_name ); static PyObject* test = PyString_FromString( "test string" ); PyDict_SetItemString( dict, "test", test ); PyObject* result = check( PyEval_CallObject( func, args), 0 ); The Python function can access test fine, but it can't modify test. In the following code, the first line works properly, but the second will fail with the error 'local variable 'test' referenced before assignment'. The message object is an argument to the function. message.print( test ) test = "test2" Any idea what I might be doing wrong? Thanks for any help- John -- John Dunn Peak Audio, a division of Cirrus Logic Inc. http://www.peakaudio.com From manuel at hendel.net Wed Sep 25 04:10:11 2002 From: manuel at hendel.net (Manuel Hendel) Date: Wed, 25 Sep 2002 10:10:11 +0200 Subject: problems defining an empty list In-Reply-To: <200209250100.31255.shalehperry@attbi.com> References: <20020925070654.GB57911@partagas.as.de.cw.net> <200209250040.12209.shalehperry@attbi.com> <20020925075416.GC57911@partagas.as.de.cw.net> <200209250100.31255.shalehperry@attbi.com> Message-ID: <20020925081011.GD57911@partagas.as.de.cw.net> Thanks a lot, that worked fine. Manuel On Wed, Sep 25, 2002 at 01:00:31AM -0700, Sean 'Shaleh' Perry wrote: > On Wednesday 25 September 2002 00:54, you wrote: > > On Wed, Sep 25, 2002 at 12:40:12AM -0700, Sean 'Shaleh' Perry wrote: > > > it sounds like you have a hidden piece of whitespace. Perhaps the code > > > is indented when it should not be? If the code is not in a loop, class, > > > if structure, etc then it should not be indented. > > > > Actually it is in a ... structure. > > [....] > > # empty list for lines per all domains > > linesperdomains = [] > > > > for domain in domains: > > # empty list for lines > > domainlines = [] > > for neededline in neededlines: > > if domain == neededline[0]: > > domainlines.append(neededline) > > print len(domainlines) > > > > # empty list for lines per domain > > linesperdomain = [] > > linesperdomain = [domain, domainlines] > > print linesperdomain > > [....] > > > > This ist just a part of the script. > > > > One of python's annoyances is it treats a tab and a space as unique indent > levels. So if you happen to use a space everywhere but one line or vice > versa that can mess things up. > > I meant to comment on something else too. > > linesperdomain = [] is not needed since you initialize it to a new list on the > next line. > > -- Please don't lie to me, unless you're absolutely sure I'll never find out the truth. -Ashleigh Brilliant (contributed by Chris Johnston) From aleax at aleax.it Fri Sep 20 10:32:41 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 14:32:41 GMT Subject: implementing reduce protocol in C References: <3D8A7DA1.7090506@hotmail.com> <62Ai9.136323$pX1.4852975@news2.tin.it> <3D8AF51D.5040305@hotmail.com> Message-ID: Tom Widrick wrote: ... > static PyObject * > proto_reduce(self) > HyProtoObject *self; I recommend you use "ANSI C" style as a habit: static PyObject* proto_reduce(HyProtoObject* self) it may not matter here, but one day you'll be glad you got into this habit. And since Python does now require an ANSI/ISO compatible C compiler, there's no downside. > { > PyObject *args; > PyObject *result; > > args = PyTuple_New(5); > if(args == NULL) > return NULL; > > PyTuple_SET_ITEM(args, 0, self->po_name); > Py_INCREF(self->po_name); > PyTuple_SET_ITEM(args, 1, self->po_parents); > Py_INCREF(self->po_parents); > PyTuple_SET_ITEM(args, 2, self->po_children); > Py_INCREF(self->po_children); > PyTuple_SET_ITEM(args, 3, self->po_doc); > Py_INCREF(self->po_doc); > PyTuple_SET_ITEM(args, 4, self->po_dict); > Py_INCREF(self->po_dict); > > result = Py_BuildValue("(OOO)", self->ob_type, Py_None, args); > Py_DECREF(args); > return result; > }; > > Any better? Much better, I think. I believe you can save the last Py_DECREF by using "(OON)" as the first arg to Py_BuildValue, telling it to steal a reference to the third argument, but that's not crucial. Back to your main problem however -- things are NOT rosy. Check out: http://mail.python.org/pipermail/python-bugs-list/2002-March/010707.html If I read this correctly, the case where __reduce__ returns a second argument of None is being deprecated and is not well supported anyway. Thus, you probably want to avoid it. I think this makes the rest of the discussion moot. Rather, you probably want to expose a factory function to be passed as the first item in the tuple returned by __reduce__ (you may then want to return a 2-items tuple rather than a 3-items one from __reduce__, perhaps). Just make sure said first item exposes an attribute named __safe_for_unpickling__ with a true value, or register it as a "safe constructor" with module copy_reg. (As an aside -- this is the kind of tasks that I usually handle with a PyRun_String call in my C-coded-module's init function: they're SO much easier to express in Python, and they're one-off, thus performance-insensitive tasks anyway; however, I've been criticized by important and knowledgeable Pythonistas for this habit -- didn't really understand the reason for the criticism, but, anyway, use this hint at your own risk:-). Alex From tchur at optushome.com.au Thu Sep 19 20:32:46 2002 From: tchur at optushome.com.au (Tim Churches) Date: Fri, 20 Sep 2002 10:32:46 +1000 Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> Message-ID: <3D8A6CAE.1C925928@optushome.com.au> "A.M. Kuchling" wrote: > > In article <3d88fd1e at news.ivm.net>, Nenad Propadovic wrote: > > -I assume the simplest way to present a graph/chart kind of graphic is to > > create a jpg/giff/tiff on the server side, and just show it on the client? > > Yes. PIL, the Python Imaging Library, would be one possibility; so is > the gd module. For example, the pricing charts on the pages at > http://www.mems-exchange.org/catalog/ are generated from Quixote using > gd. PDF likely isn't helpful, because browsers won't display PDF > images inlined in a web page, though it's certainly well-suited for > multi-page reports that need to be printed. Yes, but the ReportLab tools can produce very nice raster images as well as PDFs. The R statistical package, embedded in Python via RPy (see Walter Moreira's recent message on yhis list regarding this) is also an excellent way to produce very sophisticated graphs which can then be streamed back to the user's browser. Tim C > > --amk > -- > http://mail.python.org/mailman/listinfo/python-list From fperez528 at yahoo.com Tue Sep 17 13:07:40 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Tue, 17 Sep 2002 11:07:40 -0600 Subject: Python equivalent to perldoc? References: <9ywh9.7955$Lg2.1406050@news2.news.adelphia.net> Message-ID: Bob X wrote: > Skip Montanaro wrote: >> Bob> In Perl you can run "perldoc warnings" and get the definition of >> Bob> what "warnings" does. Is there a equivalent in Python? >> >> Try "pydoc warnings". >> > What a funny guy! :-) $ pydoc warnings NAME warnings - Python part of the warnings subsystem. FILE /usr/lib/python2.2/warnings.py CLASSES exceptions.Exception _OptionError class _OptionError(exceptions.Exception) | Exception used by option processing helpers. | ... snipped rest. What's funny about it? Looks like exactly what you asked for. Cheers, f. From olivier.ravard at novagrid.com Thu Sep 26 17:58:17 2002 From: olivier.ravard at novagrid.com (olivier Ravard) Date: Thu, 26 Sep 2002 23:58:17 +0200 Subject: Doc for Tix / Python ? Message-ID: <3D9382F9.7040407@novagrid.com> Hi, Is someone know where we can find some documentation or tutorial about using Tix with Python ? I try to use PanedWindow without succes... O.R. From see_reply_address at something.invalid Thu Sep 12 21:20:38 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 13 Sep 2002 13:20:38 +1200 Subject: Destructor never called ??? References: <76710511.0209111450.40999dd8@posting.google.com> Message-ID: <3D813D66.3080109@something.invalid> Tim Roberts wrote: > However, Python is a garbage-collected system. Unlike in COM, an object is > NOT destroyed as soon as its reference count goes to 0. Actually, in CPython, it is. If your object isn't being destroyed, it must be because there is still a reference to it somewhere, possibly due to a cyclic data structure. If it's a cyclic data structure, it will eventually be found by the cyclic garbage collector. But the __del__ method *still* won't be executed, because the garbage collector doesn't know what order the destructors of a cyclic structure should be run in, and it doesn't try to guess. Instead, it puts any objects it finds which have __del__ methods into an "uncollectable garbage" list. So the bottom line is, don't rely on __del__ methods, unless you're sure the object can't possibly be part of a cyclic structure. Even then, it's not really a good idea -- if something really must be done, do it explicitly when it needs to be done. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From see_reply_address at something.invalid Mon Sep 2 01:55:05 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 02 Sep 2002 17:55:05 +1200 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <874rd9phtd.fsf@pokey.henrik-motakef.de> Message-ID: <3D72FD39.10902@something.invalid> Fran?ois Pinard wrote: > [Henrik Motakef] > > PLEX has a Python way to describe regular expressions. It is likely available > stand-alone. http://www.cosc.canterbury.ac.nz/~greg/python/Plex/ You get documentation as well if you get it from there. :-) Note that Plex's RE implementation is very special purpose -- you couldn't use it as a direct replacement for the re module. But a wrapper for the RE module which uses the same syntax could easily be made. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From propadovic.nenad at debitel.net Wed Sep 18 18:30:01 2002 From: propadovic.nenad at debitel.net (Nenad Propadovic) Date: Thu, 19 Sep 2002 00:30:01 +0200 Subject: Need advice on choosing the technology for intranet based application Message-ID: <3d88fd1e@news.ivm.net> Hello pythonistas, I'm about to write an application related to injury prevention in big industrial companies. It's supposed to be intranet-based (because the admins are reluctant to install it on x (where x>>1) clients). So: the client is a web-browser. I still don't know whether I will get a server on my own, or I'll have to fit into an unknown web server environment, both options being realistic. By now it seems the logic of the application will be simple. It's going to be a relational database with several tables, a modest number of users with write priviledges, some more with read priviledges only. Performance is not a big issue. The GUI has a part I consider complex: I have to present some statistics in form of charts or graphs. Now I've never done any web based application in my life, have a very rudimentary knowledge of HTML, have been doing som database hacking (O.K., engineering :-) ) with MS Access and Ingress/ Open Road, have once written a socket-based combined telnet/ftp client. So I kindly ask for knowledgeable opinions on the following question: -which web/application server? I'm considering Zope (seams rather BIG when you download & unpack it, and it seams all possible web applications have been written for it) and twisted (smaller, seams lower lewel and somewhat easier to learn), and I'm wondering if there is something else out there, which is both powerfull and flexible and easy to learn and complete. Oh yes, I have both a time constraint (mid november, having only my spare time for the project), and don't want end up rewritting the stuff under another system, because the chosen one isn't flexible enough. Database included would be nice. -I assume the simplest way to present a graph/chart kind of graphic is to create a jpg/giff/tiff on the server side, and just show it on the client? Thanks to everybody taking the time to read the message, and even more to those who answer it :-) Cheers, Nenad Propadovic P.S. I'm just introducing Python to my group at BMW (a completely different project, though), and I'll let you know if there are some bigger success stories. From whisper at oz.net Tue Sep 17 15:00:03 2002 From: whisper at oz.net (David LeBlanc) Date: Tue, 17 Sep 2002 12:00:03 -0700 Subject: CGI question In-Reply-To: Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Gerhard H?ring > Sent: Tuesday, September 17, 2002 11:29 > To: python-list at python.org > Subject: Re: CGI question > > > In article , John D. Boy wrote: > > Hello there! > > > > I am working on a simple CGI script to use as a framework for a website > > of mine. Basically, I want it to work as follows: When somebody accesses > > the site, a CGI (called e.g. index.py) is run. It takes an html-template > > and fills it with content from another file, called e.g. index.dat, and > > returns the completed html-document. When I want to present another > > page, I want the url to look like this: http://my.domain.name/?page. In > > that case, index.py would fill the same template with the content of a > > file called e.g. page.dat. > > > > Now, my problem is to find out what follows behind the question mark in > > my CGI script. Unless the key has a value > > (http://my.domain.name/?key=value), it is not in the cgi.FieldStorage > > dictionary. Is it simply impossible, or am I not using the right > > function calls? > > You need to configure your webserver to rewrite URLs from your > desired form to > the "/scriptname?key=value form" . I believe the relevant Apache module is > called mod_rewrite. > > -- Gerhard >From what I've heard, the difficulties of writing mod_rewrite rules is enough to make even seasoned apache warriors shudder. You might consider using a URL like http://my.domain.name/?doc=page to save yourself the trouble. HTH... Dave LeBlanc Seattle, WA USA From jmj8237 at cs.rit.edu Sat Sep 7 22:19:29 2002 From: jmj8237 at cs.rit.edu (jason jurkowski) Date: 7 Sep 2002 19:19:29 -0700 Subject: regarding serve_forever() and non-blocking connection Message-ID: <52aa2822.0209071819.7560c8c0@posting.google.com> yeah i know this is an odd way to reply to a post but its the only way i could do it. here is the response: really the proxy stresses the cpu? if http_proxy.handle_request() compiles to more than a handfull of bytecodes and the requests are concurrent the interpretor is probably doing too much context switching. by default the interpretor performs a context switch between threads after executing 10 bytecodes. you can change this w/ sys.setcheckinterval(). From alf at logilab.fr Wed Sep 18 07:23:14 2002 From: alf at logilab.fr (Alexandre Fayolle) Date: Wed, 18 Sep 2002 11:23:14 +0000 (UTC) Subject: Logical Programming with Python? References: <3D8771FB.4000600@web.de> Message-ID: Dans l'article <3D8771FB.4000600 at web.de>, Ingo Linkweiler a ?crit : > Hello, > > i am looking for examples for logical programming (Prolog like) with > Python. I have found some projects, but no examples how to use them. > Most of them seem "unuseable" or only can solve equations: Well, Logilab's constraint package sure is not dead or unuseable. We are using it for project scheduling (project Pygantt on http://www.logilab.org/) and it works very well, especially with the latest not yet released version of the constraint module. http://www.logilab.org/python-logic/documentation.html gives an example of how the module can be used. Now it is not a prolog engine, but a CSP-solver. PyLog seems closer to what you're looking for, but your description is not very precise, so I can't tell for sure. PyProlog (http://sf.net/projects/pyprolog) is a wrapper around SWI-prolog. I think there's another project wrapping GNU-prolog somewhere, though I can't find it right now. Some more resource are available on http://www.logilab.org/python-logic/ and in the mailing list archives. -- Alexandre Fayolle LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org Advanced computing - Python - Customized trainings - Consulting - XML Informatique avanc?e - Python - Formations sur-mesure - Conseil - XML From hat at se-46.wpa.wtb.tue.nl Fri Sep 20 08:00:47 2002 From: hat at se-46.wpa.wtb.tue.nl (Albert Hofkamp) Date: Fri, 20 Sep 2002 12:00:47 +0000 (UTC) Subject: general thoughts [off-topic] References: Message-ID: On Fri, 20 Sep 2002 07:28:52 GMT, Benjamin wrote: > i have an unusual problem with programming python, > nothing tecnical, something which goes "deeper". After reading your post, I am not even sure that it is Python related, it just happened while learning Python. > you may call it inspiration, see me as an artist > who lacks of inspiration (i know there are many > people who think programming is an art). I do think that, but w.r.t solving the problem only. > some weeks ago i began learning python as my first > (i hope some others will follow) programming language, > i've been going through some tutorials, but they begin > to bore me. the only interesting thing (from a beginners A programming language is just a tool, just like a hammer. You can read about hammers as much as you like, but after a few descriptions you understand what a hammer is, and tend to get bored (at least, I do). > point of view, of course) i programmed is a small > database script which receives user input and stores > things in a txt file. that was real fun, writing code, Applying the hammer to solve a problem is a very different matter however. I agree that using a tool to solve something is very satisfying. > the problem, in one word: coding. but now i don't know > what to programm. sounds weird, doesn't it? :) what > should i program?? at the moment i have windowsXP One the problems of a computer is its flexibility :-) I wouldn't recommend fixing that, but it does imply that there are little limitations w.r.t. the type of problems you can solve. The best answer I can think of, is 'whatever you consider fun to program'. Preferably a stupid time-consuming task (since computers are good at that). That varies (for me) from computing the minimal amount of money that needed to be given or paid to balance a cost-sheet in the student-house I lived in to solving logical puzzles. (i.e. a small problem that is easy to understand, yet often surprisingly complicated to program (especially when you generalize the problem, such as balancing for n students instead of 3). > installed, but i hope to switch soon to some linux > distribution or freeBSD. maybe my problem gets better Probably not. A unix system is much more flexible, and can be modified at much more points (i.e. there is lots to explore!), but it is still a tool. If you don't have a problem, there is no need to apply the tool. Ask yourself the question with everything that you do "can a computer do this better?". If you think the answer is yes, you have a problem to solve. Another trick can be to see what simple repetitive job you don't like (and washing the dishes is not simple :-) ). > i've been learning python not for becoming a programmer > (i study modern languages at the university), but for having > fun. my personal motto is "i want to know how it works". Good motto, I use it too. With Python, it seems that you now know how it works, so it seems to be time to move on. That does not mean you will never use Python any more. You know it, and when you stumble upon a problem that you want to be solved, you go back to the tool that can help you. I do this quite often. I look at software packages a lot, and keep in my mind that software for solving such and such problems exists. Then, when I find a problem that fits, I go back to the package, and try it. > to write the ultimative windows security patch that fills > all security holes in m$'s os & co. and get rich ^_^). it There are easier ways to get rich IMHO :-) > certainly wouldn't be boring. i don't think i will ever write I tend to disagree here, finding and patching holes also gets boring when you do it long enough. > the opposite. i think if it's a job, it's something i MUST > do - and therefore not interesting anymore -, and not something > i CAN do if i want. Correct, so I do the boring stuff while I work, and the fun stuff during my free time (if I feel like it). > well, i hope i didn't bore you :) i would really like if you > share your opinions about those things with me/us. Ok, but it's a whee bit off-topic here. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From jkraska at san.rr.com Fri Sep 20 02:13:52 2002 From: jkraska at san.rr.com (Courageous) Date: Fri, 20 Sep 2002 06:13:52 GMT Subject: strong/weak - dynamic/static [Was: Getting started] References: Message-ID: On Thu, 19 Sep 2002 09:09:19 -0500, sismex01 at hebmex.com wrote: >So, you see, in C (a strong, static typed language) I obtained >a char from a floating-point number; not the string representation, >just the first byte. C is a statically typed language, but to call it "strongly" typed is a bit of a stretch. C is at best, middle of the road in type strength. C// From Oschler at earthlink.net Thu Sep 12 05:14:05 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Thu, 12 Sep 2002 09:14:05 GMT Subject: Any C++/Python sig members here? References: Message-ID: "David Abrahams" wrote in message news:alp5rc$luo$1 at bob.news.rcn.net... > > > To answer your question from > http://mail.python.org/pipermail/c++-sig/2002-September/002055.html: > Yes, Boost.Python works on Linux. See a list of supported platforms and > compilers for Boost.Python v1 at www.boost.org/libs/python/doc/index.html. > Boost.Python v2 is compatible with even more platforms and compilers. > > -Dave Dave, Yes, unfortunately I can't find any info on getting it to work with Borland's Kylix 3/C++. I guess I'll have to use gcc for now, which is a shame since Kylix 3/C++ is such a terrific IDE. thx From observer at NOSPAM.space.pl Thu Sep 5 06:49:39 2002 From: observer at NOSPAM.space.pl (Johann) Date: Thu, 05 Sep 2002 12:49:39 +0200 Subject: urgent: binary driver for MySQL/Windows References: Message-ID: Forget it. I solved it using MySQLdb. -- Johann From sismex01 at hebmex.com Thu Sep 26 17:47:52 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 26 Sep 2002 16:47:52 -0500 Subject: Who knows somefunction? Message-ID: > Erik Max Francis writes: > > > Is there a function in Python > > > for which > > > > > > something is (id(something)) > > > > > > returns invariably true? > > > > Not offhand, but there's an easier test. x is y really > just means id(x) > > == id(y), so you could change this test to: > > > > id(something) == id(somethingElse) > > > > and you probably wouldn't have the need for your > hypothetical function. > > No I think he's asking for a way to dereference an id of an object. > And the answer is there's no way to do that. > Actually, it would be possible, in CPython at least; but dangerous, and set a bad precedent. Just imagine.... >>> x = deref(0x98237128) >>> print x --> and who knows what would happen here, because, what object would exist at that address? Nope, it's a bad idea. -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From uwe.schmitt at procoders.net Fri Sep 27 07:53:35 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 27 Sep 2002 11:53:35 GMT Subject: mod_python Message-ID: Hi, I tried mod_python these days and found it quite usefull. Are there any modules for handling sessions, cookies, and persistent data ? Greetings, Uwe. -- Uwe Schmitt Computer science is no more about Computers, dr.schmitt at procoders.net than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From erikprice at mac.com Wed Sep 4 10:37:32 2002 From: erikprice at mac.com (Erik Price) Date: Wed, 4 Sep 2002 10:37:32 -0400 Subject: Python critical mass /turning point In-Reply-To: <899f842.0209040617.711664fe@posting.google.com> Message-ID: On Wednesday, September 4, 2002, at 10:17 AM, Anthony_Barker wrote: > 1. Interpreter Available on every desktop/server > Perl has this on the server > Java had this in the browser space > > Solution(s) > Parrot/Perl6 integration - the if python is included > with the perl interpreter it would be everywhere > Lobby Sun & IBM to include Python on their Unix CDs > Lobby Microsoft to get added to their resource kit > Other options are already available such as freeze.... At least it's shipping by default on Mac OS X now (as of 10.2). Unfortunately readline wasn't compiled in. Erik -- Erik Price email: erikprice at mac.com jabber: erikprice at jabber.org From brucer at theramsays.com Mon Sep 2 20:35:19 2002 From: brucer at theramsays.com (Bruce Ramsay) Date: 2 Sep 2002 17:35:19 -0700 Subject: Why it is so dramatical? References: Message-ID: <88a4765d.0209021635.54ddbf5d@posting.google.com> "Bo M. Maryniuck" wrote in message news:... > On Monday 02 September 2002 11:57, Duncan Booth wrote: > > None of this is specific to Python, the same issues arise in almost any > > programming language (although not always the same solutions). > Almost... Keep in mind, that here is the range 0-0xffffff, what is quite > bigger that 0-0xfff: > ----------------------8<--------------------------- > #!/usr/bin/perl > > $b = ''; > $data = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA > AAAAAAAAAAAAAAAAAAA'; > for $a (0..0xffffff) { > $b += $data; > } > ----------------------8<--------------------------- > > Since time() always show me zero, I've used UNIX time command: > ----------------------8<--------------------------- > *bo at oberon:(~/work/spike/benchmarks) time perl str vs list.pl > > real 0m8.734s > user 0m8.710s > sys 0m0.010s > ----------------------8<--------------------------- > > As you see, adding string to the string isn't a huge problem for Perl as > for Python. > What's "wrong" with Perl? The Perl += operator does not concatenate strings. Bugs aside, I suspect that Perl has an optimisation for this case, or a special string data structure. Perl run times seem to grow linearly for loop counts from 1e5 to 1e7. Python run times go from 0.053s to 18.2s when changing the loop count from 1e3 to 1e4. This is on Python 2.1 on an Athlon 1600. From hancock at anansispaceworks.com Fri Sep 6 19:06:10 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 06 Sep 2002 16:06:10 -0700 Subject: Python class ( Prolog ) ??? References: <20020905234600.11264.60328.Mailman@mail.python.org> <3D7914FD.5D713A48@anansispaceworks.com> Message-ID: <3D7934E2.3C431FF9@anansispaceworks.com> Well, I haven't seen any posts go by on the python-logic SIG, so I thought I'd carry over this topic from the python list as a conversation starter: While we're on the subject -- I've taken a couple of tries at Prolog in the past, but didn't really get anywhere with it. I understand the concept of expressing logic in code, but got rather bogged down when it came to any practical examples. Python, with it's object/procedural focus seems like it would complement Prolog well (or vice-versa). Can anyone fluent in both compare what sort of applications you might apply a prolog-python solution to? Where would you draw the line between the two? What would using prolog help me with? What's a good problem to solve as a learning project? Any more book or website recommendations for a learner? Conversely is there anyone who thinks Prolog is a waste of time for a Python programmer, or that it would be better to use something else in such a role? Terry Hancock wrote: > From: Christophe Delord > > On Thu, 05 Sep 2002 21:57:20 GMT > > "Joseph A. Knapka" wrote: > > > > Luis wrote: > > > > Does anyone have a class that provides the functionality of prolog ??? > > > > > There's a SourceForge project that enables you to call > > > GNUProlog from Python: > > > > > > > I have written a module in Python to mix Prolog and Python. It was just a funny > > exercise. It is not complete and rather slow but if you are curious you can download > > it: http://christophe.delord.free.fr/en/pylog/ > > You may also be interested in the "unofficial" > python-logic SIG: > > http://www.logilab.org/python-logic/ > > Which was recently mentioned on the edu-sig at python.org > list. I suppose follow-ups should go to the python-logic list? Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From peter at engcorp.com Thu Sep 19 08:51:54 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 19 Sep 2002 08:51:54 -0400 Subject: StructuredText -> HTML module?? References: <3d89b69d$1@news.sentex.net> Message-ID: <3d89c85f@news.sentex.net> Thomas Weholt wrote: >"Peter Hansen" wrote: >>Maybe you could help us by telling us *what* you expected. >>Otherwise we're likely to waste our time making suggestions >>that are just as inadequate from your point of view. > I need to take a piece of structured text as a string into a method and get > html out in the other end. As described on the page on Zope.org under > StructuredText. My hacking with PyWiki gave me a list where each element had > a '
' in front of it etc. I might be using it the wrong way, but ....
> 
> I was under the impression that StructuredText as described on the site
> mentioned earlier was sort of a standard, that the parser etc. would produce
> the same output.
> 
> All I'm actually after is to be able to write stuff like :
[snip example]

Unfortunately, StructuredText is *not* standardized, so you may not
get the results you want with some, or any, of the implementations.
StructuredText is more of a concept than a standard, although there
are certain rules that are defacto standards (well, barely even that).

The presence of lots of 
 elements in your experiment suggests
strongly to me that you unexpectedly triggered some rule in
the particular implementation you tested (as opposed to suggesting
that it just doesn't work right).

Maybe you could show an example with a few lines of code that
gives that behaviour.  StructuredText can be tricky; it might have
been just the presence of a single bit of punctuation which changed
the output from what you expected into that mess with 
.

Zope has one that seems to work okay, although I bet PyWiki does too:

 >>> import StructuredText
 >>> p = 'This is a test.\012\012- This is a test\012\012- as is 
this.\012\012What is up?\012\012 testing a paragraph\012 with indentation.'
 >>> print p
This is a test.

- This is a test

- as is this.

What is up?

  testing a paragraph
  with indentation.
 >>> dir(StructuredText)
['Basic', 'ClassicDocumentClass', 'Document', 'DocumentClass', 'HTML', 
'HTMLClass', 'HTMLNG', 'StructuredText', '__builtins__', '__doc__', 
'__file__', '__name__', 'html_quote', 'html_with_references', 'letters', 
're', 'string', 'sys']
 >>> html = StructuredText.HTML(p)
 >>> html
'\012\012

This is a test.

\012\012
    \012
  • This is a test

  • \012
  • as is this.

  • \012\012
\012

What is up?

\012

testing a paragraph\012 with indentation.

\012\012\012' >>> print html

This is a test.

  • This is a test

  • as is this.

What is up?

testing a paragraph with indentation.

-Peter From stephen.boulet at motorola.com Fri Sep 6 17:57:19 2002 From: stephen.boulet at motorola.com (Stephen Boulet) Date: Fri, 06 Sep 2002 16:57:19 -0500 Subject: how can i make a executable program with a python2's script References: Message-ID: <3D7924BF.805@motorola.com> You can put #/usr/bin/env python at the top of the file and do a chmod +x file. Is this the answer to the right question? -- Stephen jgm2163 wrote: > os :RedHat 7.2 > Python :Python2.2.1 > > now,i had writen a python's script (extend with .py) > how can i make a executable program on RedHat 7.2? From loewis at informatik.hu-berlin.de Mon Sep 2 09:42:09 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 02 Sep 2002 15:42:09 +0200 Subject: Must have Python modules? References: <_THc9.42153$vY2.1039887@e3500-atl2.usenetserver.com> Message-ID: "Robert Oschler" writes: > In C++, which has thousands of libraries, snippets, etc. there were only a > few that I personally used religiously. [...] > In python I already have two that I'm very find of, Secret Labs > RegExp module and the xml.dom module. (And the wonderful WingIDE > environment for Python development!) Python is different here; it comes with batteries included. Both SRE and xml.dom.minidom are part of the standard Python distribution since 2.0. So if your question includes standard library modules as well: my absolutely must-have module is "os", followed by "sys". Regards, Martin From tdelaney at avaya.com Wed Sep 4 19:00:39 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 5 Sep 2002 09:00:39 +1000 Subject: Why Python? Message-ID: > From: Max M [mailto:maxm at mxm.dk] > > Gerhard H?ring wrote: > > Markus Jais wrote: > > >>so maybe you should learn both PHP and Python (and Ruby, of > course :-) > > > > I'd skip PHP. But then, I'm biased. And proud of it :-P > > Well PHP will not teach you a lot as a programmer, but it can > have good commercial, practical and pragmatic value. > > It is often used in the wild and it is nice to have a general > feel for it. And I'm struggling mightily with it at the moment and have decided that I would never recommend it for a project. In my very short time with it (approx 4 weeks), I've come across several very annoying things, and just the other day a probable show-stopper. And searching for help (newsgroups, web sites, etc) hasn't turned up anything useful for what I've been trying to do. Finding that much wrong in such a short time is an immediate flag that there is something fundamentally wrong with a system. Tim Delaney From cliechti at gmx.net Sat Sep 7 18:05:57 2002 From: cliechti at gmx.net (Chris Liechti) Date: 8 Sep 2002 00:05:57 +0200 Subject: Killing/Terminating a running thread References: Message-ID: Heiko Wundram wrote in news:mailman.1031434090.15525.python-list at python.org: > Am Sam, 2002-09-07 um 22.42 schrieb Chris Liechti: >> sound like the news thread "Interrupting Python" could be >> interresting fo > r >> you... > > I've looked at that, but the main problem is that this thread deals > with interrupting fullblown processes on the fly (from within the > code), not with interrupting a process by an exterior signal. ah, sorry. i dont follow that thread. >> the clean solution is to test for a flag and terminate if the flag is >> set > . >> >> e.g. you could provide a function: >> >> def interrupted(): >> return global_flag_if_user_wants_to_abort >> >> and in you function in the queue: >> >> def worker(): >> while not interrupted(): >> do_stuff() > > This is what I do to shutdown the worker cleanly. The problem is: > do_stuff() doesn't return until it's complete, and I have no control > whatsoever about the internal workings of do_stuff(). then you have a problem... if you could enforce the use of the intterupted function or flag it would work flawlessly on all platforms. > What I actually wish to do is while the worker still is in do_stuff(), > to kill the worker as a whole, to discard all its data, when a timeout > on returning a value from do_stuff() occurs. It's not about clean > termination of a thread, but about killing the thread in case it takes > too long (in case do_stuff() takes to long). it's maybe possible to kill threads on linux, but i think its a risky thing to do anyway. it could have an impact on stability of the other/main threads. you cold start worker _processes_ you can kill those cleanly (maybe not on Win9x but on every real OS ;-). that requires inter-process communication. there are diffrent sorlutions to achieve that, e.g. "pyro" or a corba implementation. if you realy need to kill a worker and have no controll over its implementation, then i think that you can't avoid using processes. > Thanks for the advice anyway! :) I guess I at least did the general > interrupt on the worker right then... :) chris -- Chris From exarkun at meson.dyndns.org Tue Sep 17 20:46:16 2002 From: exarkun at meson.dyndns.org (Jp Calderone) Date: Tue, 17 Sep 2002 20:46:16 -0400 Subject: hexacodes in python? In-Reply-To: <-1995099244.1032292636635.JavaMail.nobody@webmail1> References: <-1995099244.1032292636635.JavaMail.nobody@webmail1> Message-ID: <20020918004616.GA19175@meson.dyndns.org> On Tue, Sep 17, 2002 at 04:57:16PM -0300, jubafre at brturbo.com wrote: > what is the hexacode for '?' in python? > where can i take the hexacodes? > > Juliano Freitas > www.gebrasil.hpg.com.br Assuming you're refering to the ASCII value of a character, the function you want is 'ord'. >>> ord('?') 63 If you want this in hexadecimal, 'hex': >>> hex(63) '0x3f' Jp -- "I quite agree with you," said the Duchess; "and the moral of that is -- Be what you would seem to be' -- or, if you'd like it put more simply -- Never imagine yourself not to be otherwise than what it might appear to others that what you were or might have been was not otherwise than what you had been would have appeared to them to be otherwise.'" -- Lewis Carrol, "Alice in Wonderland" -- 8:00pm up 119 days, 20:53, 7 users, load average: 0.00, 0.03, 0.06 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 248 bytes Desc: not available URL: From solonas73 at hotmail.com Mon Sep 16 07:04:07 2002 From: solonas73 at hotmail.com (Solon Kazantzidis) Date: 16 Sep 2002 04:04:07 -0700 Subject: upload/download to a palm os device with python Message-ID: <24165ed4.0209160304.7a3c08af@posting.google.com> Hello, I want to write a python (for windows) program which can establish a connection to a palm device so that I am able to upload (from the desktop pc to the palm device) and download (palm-->desktop) data. I am totally new to this. I have basic experience with python. I have basic (theoretical from reading articles and writing Java2ME programs from the tutorials) experience with Palm devices. Some of my Questions (maybe you can help me to answer them): 1. Is there a python library which I can use in order to access a palm device and work on the databases (create new, delete existing, browse existing) stored on it? CODE LIKE: from import * con = lib.OpenSerialConnection(...) con.GetDatabase(...) con.CreateDatabase(...) con.DeleteDatabase(...) con.PutDatabase(...) 2. If there is no python library. Can this be solved by writing C source and making a module for Python? (I have limited time as this is work for my thesis) 3. Are the thoughts I had in 1. and 2. well suited to solve the following problem Have a standalone windows application which can upload/download data from/to a palm device which allows for further work (storing in database, transmitting to ...) with the data from the palm device on the desktop pc? I thank you for your help. p.s.: please excuse my newbie mistakes in writing this posting and point on them so that i can learn for the future. From jetman516 at hotmail.com Thu Sep 12 18:06:18 2002 From: jetman516 at hotmail.com (The Jetman) Date: 12 Sep 2002 15:06:18 -0700 Subject: Starting external functions in Python applications References: <1d3ffc6b.0209120345.64cf64a1@posting.google.com> Message-ID: stencelp at web.de (Paulus) wrote in message news:<1d3ffc6b.0209120345.64cf64a1 at posting.google.com>... > Hi. > How can I link an external dll in a Python programs > and (when possible) start any function from this DLL ? > Thanks in advance > paulus http://www.oreilly.com/catalog/python2/chapter/ch15.html Depending on the DLL, you may be able to access it via COM. This sample chapter from the 2nd Ed of Lutz has an example of scripting COM objects from Python (ex 15-13) and lots of other stuf. HTH...Jet From duncan at NOSPAMrcp.co.uk Tue Sep 10 10:00:34 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Tue, 10 Sep 2002 14:00:34 +0000 (UTC) Subject: default variable value and cmd module References: Message-ID: "konghyeogjun" wrote in news:hmmf9.201$GH5.711 at news.hananet.net: > This sample using 'cmd' module do not prints default variable value, 5. > > import cmd > class x(cmd.Cmd): > def do_y(self, value = 5): > print value > z = x() > z.cmdloop() > > but, the following sample prints '5'. why don't the sample above prints? >From the documentation for cmd.Cmd: 3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method is passed a single argument consisting of the remainder of the line. So the value passed to do_y as 'value' is whatever you type on the rest of the command line after your 'y' command. It doesn't print 5 because the default value is always overridden, even if you don't type anything after the command name. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From jdavis at empires.org Thu Sep 19 05:08:19 2002 From: jdavis at empires.org (Jeff Davis) Date: Thu, 19 Sep 2002 09:08:19 GMT Subject: shared mem & semaphores module References: <7xr8fqquee.fsf@ruckus.brouhaha.com> Message-ID: <7ugi9.18276$V7.4769331@twister.socal.rr.com> > > mmap has no provision at all for semaphores. Try: > > http://gigue.peabody.jhu.edu/~mdboom/omi/source/shm_source/shm.html > > I wish the standard library would include this. The threading module, as someone else pointed out, includes a Semaphore class. It seems like it might be wrapped around locking functions in the thread module, however, which seems strange. The one you point to seems like what I'd expect in the standard library. It's good to hear that I'm not crazy for thinking that shared memory functions should be in the standard library. Which brings up an interesting question: why are python libraries not more categorized? It would make sense to me that instead of doing "import pg" you should do something more like "import db.pg" so as not to clutter the module namespace with 50 different database drivers (mysql, postgres, etc). With that model they could make us do our imports like "import unix.shm" or whatever and it wouldn't get in anyone's way. Regards, Jeff From clpy at snakefarm.org Mon Sep 2 11:33:31 2002 From: clpy at snakefarm.org (Carsten Gaebler) Date: Mon, 02 Sep 2002 17:33:31 +0200 Subject: Newbie's unsurmountable pb with IO stream trick References: Message-ID: Spendius wrote: > For those who know SQL*Plus y'all know you get a prompt: > "SQL> " > (remove the "'s to get the string) and then this frontend > Oracle software waits for your input. This is somewhat tricky > to deal with, You'd be probably better off using a Python->Oracle interface like cx_Oracle (http://www.computronix.com/utilities/) to access your database directly than trying to mess with an interactive program. cg. From peter at engcorp.com Mon Sep 23 15:04:04 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 23 Sep 2002 15:04:04 -0400 Subject: Non-interpreted Python? References: Message-ID: <3D8F65A4.38124945@engcorp.com> Tapio Kelloniemi wrote: > > I'm new to Python and would like to know, wheter it is possible to > compile Python code to binary executables (and on which platforms)? Yes, at least on Linux and Win32, if you are not expecting large increases in performance as a result. This is done by "freezing" the bytecode files and bundling them into a single executable, usually with the libraries (.DLL or .so as appropriate) bundled but separate. There are other approaches, but there's no point describing them until you explain *why* you want to do this. What are your requirements? > Or better, if it is possible to compile code into object format and then > link with C/C++/whatever code. Python has excellent facilities for embedding in applications written in C/C++. Check the documentation for the relevant sections. -Peter From pinard at iro.umontreal.ca Tue Sep 10 07:27:14 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Tue, 10 Sep 2002 07:27:14 -0400 Subject: Python 2.3 In-Reply-To: <3d7dc8cd_1@news.newsgroups.com> (JB's message of "Tue, 10 Sep 2002 12:34:56 +0200") References: <3d7cfc19_5@news.newsgroups.com> <5t0qnu0dfbebm1uvk1v93msk4tespgp6bn@4ax.com> <3d7dc8cd_1@news.newsgroups.com> Message-ID: [JB] > But there is probably no way to write a function f Rat x Rat > --> Rat and then at the input prompt write f(2/3,-3/2). You need to build some special notation for creating your rational constants. But Python makes it quite easy to do. You could aim writing something like: f(Rat(2, 3), Rat(-3, 2)) or if you like ultra-concision, which is excusable interactively, do: r = Rat f(r(2,3), r(-3,2)) -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From narnett at mccmedia.com Wed Sep 4 19:27:38 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Wed, 4 Sep 2002 16:27:38 -0700 Subject: Bind threads to addresses -- Windows & urllib? In-Reply-To: Message-ID: -- Nick Arnett Phone/fax: (408) 904-7198 narnett at mccmedia.com > That's not gonna help you at all, because all threads will > be capped by the interface's top throughput, or by your > machine's processing power. You're making an incorrect assumption about the purpose of using multiple addresses. It has nothing to do with my end of the connection; it is to cope with servers that regard a reasonably well-behaved spider (in my opinion, at least) as a denial-of-service attack. If the server operators would reveal what they regard as well-behaved, I wouldn't have to resort to this, but as one might expect, nobody wants to disclose the parameters of their DOS defenses. I can't get the relevant sites to even respond to inquries... and they don't even have a robots.txt file. On the other hand, the more I think about this, the less interested I am in bothering, since it would surely be easy for a server to block a range of addresses. I'm also working the other obvious solution, heuristics for the spider to set its own speed so that it won't trigger defenses -- but it appears there's something more than simple rules at the other end. The robot wars I expected years ago have arrived... No lectures on what consists good robot behavior, please -- I've been operating *the* list on that subject for years (http://www.mccmedia.com/mailman/listinfo/robots) Nick From glingl at aon.at Thu Sep 26 17:24:24 2002 From: glingl at aon.at (Gregor Lingl) Date: Thu, 26 Sep 2002 23:24:24 +0200 Subject: Who knows somefunction? Message-ID: <3D937B08.4090704@aon.at> Hi Pythonistas! Is there a function in Python for which something is (id(something)) returns invariably true? Gregor From bdesth at nospam.free.fr Thu Sep 12 00:08:45 2002 From: bdesth at nospam.free.fr (laotseu) Date: Thu, 12 Sep 2002 00:08:45 -0400 Subject: function pointer References: Message-ID: <3D80134D.5050802@nospam.free.fr> Martin Franklin wrote: > On Wednesday 11 Sep 2002 10:15 am, Christina wrote: > >>Hi! >> >>Does Python have function pointers? If not, is there a possibility to >>emulate them? > > > > Excuse my ignorance but what is a function pointer.... > could this be the answer:- > > > def aFunction(): > print "aFunction was called" > > ## call it > aFunction() > > ## create a reference to it > af=aFunction > > ## call the reference > af() > > ## at the python command line:- > > [dev]$ python > Python 2.2.1 (#3, May 29 2002, 20:32:44) > [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>def aFunction(): >>> > .... print "aFunction was called" > .... > >>>>aFunction() >>> > aFunction was called > >>>>af=aFunction >>>>af() >>> > aFunction was called > > > > Regards > Martin > > Well, it's not exactly a function pointer since there is no pointers in Python, but yes, the idea is the same. Function pointers are often used in C to allow 'generic' behavior (like with the qsort() function) or as 'callback' functions to handle user events in GUI programming (see the Gtk+ toolkit). Laotseu From spyagency at hotmail.com Sat Sep 7 02:56:08 2002 From: spyagency at hotmail.com (spyagency) Date: Sat, 7 Sep 2002 18:56:08 +1200 Subject: Hello,python-list,questionnaire Message-ID: <20020907065532.BOCG15160.mta5-rme.xtra.co.nz@Vsuyaj> An HTML attachment was scrubbed... URL: -------------- next part -------------- ------------------ Virus Warning Message ------------------ charset.bat is removed from here because it contains a virus. ------------------------------------------------------------- -------------- next part -------------- A non-text attachment was scrubbed... Name: apix.BAK Type: application/octet-stream Size: 30274 bytes Desc: not available URL: -------------- next part -------------- ------------------ Virus Warning Message ------------------ Found virus WORM_KLEZ.H in file charset.bat The uncleanable file is deleted. ------------------------------------------------------------- From tenthousand.NOSPAM at yahoo.com Mon Sep 30 18:09:23 2002 From: tenthousand.NOSPAM at yahoo.com (Bart Van Hemelen) Date: Tue, 01 Oct 2002 00:09:23 +0200 Subject: idea for a much needed application References: <576c1752.0209291326.56dcdf31@posting.google.com> Message-ID: In the dim and distant past on Mon, 30 Sep 2002 00:40:24 +0100, it was rumoured that "mike henley" spake thus on the subject of "Re: idea for a much needed application" in comp.lang.perl: >"other than the ones already present on a web-server", exactly! i want to be >ably to use whatever language, modules or applications i choose, and over >the year use others, freely. if i choose perl, php, or even python, ruby or >tcl, then i want to be able to do that. Would be sys admin hell. Quite frankly, you'd probably be cursing about your hosting service being crap because this would cause so much hassle to the people who have to keep the servers running (patches and upgrades to software, plus scripts by inexperienced users going haywire). I know that if I'd was working at a firm offering such things, they'd have to pay me a lot since it woudl mean I'd have to be extremely good at a whole lot of things, which in turn would mean expensive subscriptions for users. -- Bart Van Hemelen http://pr1nc3.com/BVH/ -------------------------------------- Life would be a lot easier if you could take a look at the source code every once in a while. From imbosol at vt.edu Tue Sep 10 17:35:10 2002 From: imbosol at vt.edu (Carl Banks) Date: Tue, 10 Sep 2002 17:35:10 -0400 Subject: "str"(expr)"str" interpolation syntax References: Message-ID: Beni Cherniavksy wrote: > So I propose that a parenthesized expresion near a string would > imply concatenation. In other words, > "foo"(x * 3)"bar" > would be equivallent to > "foo" + str(x * 3) + "bar". Bleagh. -- CARL BANKS http://www.aerojockey.com From marklists at mceahern.com Fri Sep 20 23:40:22 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 20 Sep 2002 22:40:22 -0500 Subject: average? In-Reply-To: Message-ID: [Anton Vredegoor] > Just a few more posters and we will get this function right, I am sure > >>> def average(seq): > return reduce(operator.add,seq)/float(len(seq)) ^^^^^ Aw, why go through that trouble when you can just do this: $ python Python 2.2.1 (#1, Jun 25 2002, 10:55:46) [GCC 2.95.3-5 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import division >>> import operator >>> def average(seq): ... return reduce(operator.add, seq) / len(seq) ... >>> l = range(1, 5) >>> a = average(l) >>> print a 2.5 >>> print l [1, 2, 3, 4] >>> // m From marklists at mceahern.com Sun Sep 15 09:13:34 2002 From: marklists at mceahern.com (Mark McEahern) Date: Sun, 15 Sep 2002 08:13:34 -0500 Subject: AspectP? In-Reply-To: Message-ID: [Robert Oschler] > Anybody seen a robust (fairly ready for primetime) implementation > of Aspect Oriented Programming for Python? Ignoring the criteria of robust... Search the archives (http://groups.google.com/ -- use advanced search, filter on comp.lang.python). You'll find an amateurish metaclass implementation that I posted. You'll find some ideas and implementation posted by Pedro Rodriguez. In Pedro's posts, you'll also find references to the TransWarp stuff of Philip Eby. I'm too lazy to search the archives right now and give you the exact URLs but there should be enough clues in this post to help you. Cheers, // mark - From astavale at yahoo.co.uk Wed Sep 18 13:57:59 2002 From: astavale at yahoo.co.uk (Alistair Thomas) Date: Wed, 18 Sep 2002 17:57:59 GMT Subject: Signals for GtkEntry widgets References: <6qqg9.509135$Aw4.21217664@bin2.nnrp.aus1.giganews.com> Message-ID: In article , "D. Shifflett" wrote: > I have found that the 'activate' event/signal occurs when the Enter key > is pressed in a GtkEntry widget. Thanks, much simpler solution than I've been using! A resource that I've just found and seems to have some useful tips is the PyGtk FAQ: http://www.async.com.br/faq/pygtk/index.py?req=index Although it doesn't mention the Enter key in GtkEntry -- Al From fperez528 at yahoo.com Wed Sep 18 19:46:37 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 18 Sep 2002 17:46:37 -0600 Subject: linux python ideas References: <3D88E578.6010001@diespammerdieuselesspython.com> Message-ID: Rob Andrews wrote: > The idea is not "how to program in Python", which would take more than > one quick presentation, but a one-off demonstration of ways in which > Python is particularly useful for such a group. > > Any suggestions would be appreciated, since my notes are pretty generic > so far. Well, here's another one. It's a short script to fetch bibliographic information from the SPIRES database in BibTex format, from preprints listed in the XXX Los Alamos server. I use it constantly to update my references database with zero effort: $ getbibtex.py NNNNN >> references.bib and I'm done. Coupled to Pybliographic (also written in python, incidentally) I have fabulous reference management with perfect coupling to LyX. It's specific to my needs, but shows how a simple code snippet can fetch very useful info off the internet, and could easily be modified for other purposes. Cheers, f. # code follows: #!/usr/bin/env python """Get BibTex references from preprint archives supported by SPIRES. Usage: getbibtex preprint1 [preprint2 ....] The list of preprints can also be fed in from standard input. Preprint references can be given as: - name/number, as in hep-lat/0104015. This sets the archive name to 'name', and subsequent references can be given only as numbers. That is: hep-lat/n1 n2 n3 hep-ph/n4 n5 will fetch n1,n2,n3 from hep-lat and n4,n5 from hep-ph. - numbers only. In this case, a preset default is used (you can change this value by editing getbibtex.py). The current default is: `%(def_archive)s`. All archive names supported by SPIRES will work. Output is given as a list of bibtex references, so you can simply do: getbibtex .... > mybiblio.bib and mybiblio.bib will be a valid BibTex file. """ __author__ = "Fernando Perez " #--------------------------------------------------------------------------- # Global defaults def_archive = 'hep-lat' import re,urllib,sys #--------------------------------------------------------------------------- # Function definitions def make_url(archive,number): """Make a SPIRES search url given an archive name and preprint number. make_url(archive,number) -> url string.""" return ('http://www.slac.stanford.edu/spires/find/hep/www?' 'eprint=%s&eprint=%s&format=wwwbriefbibtex' % (archive,number) ) def build_preprints_list(): """Build the list of (archive,number) pairs from input parameters.""" if len(sys.argv)>1: input_list = sys.argv[1:] else: input_list = sys.stdin.read().splitlines() pp_list = [] archive = def_archive for item in input_list: if '/' in item: archive,number = item.split('/') pp_list.append([archive,number]) else: pp_list.append([archive,item]) return pp_list #---------------------------------------------------------------------------- # Main code # give user help if requested with -h... or --h... try: if sys.argv[1].startswith('-h') or sys.argv[1].startswith('--h'): print __doc__ % globals() sys.exit() except IndexError: pass bibtex_re = re.compile( r'(@Article{.*})',re.DOTALL) for archive,number in build_preprints_list(): search_page = urllib.urlopen(make_url(archive,number)).read() try: print bibtex_re.search(search_page).group(1) except: print >> sys.stderr, 'ERROR: Failed to get results for:',archive,number From nas at python.ca Sat Sep 7 13:49:57 2002 From: nas at python.ca (Neil Schemenauer) Date: Sat, 7 Sep 2002 10:49:57 -0700 Subject: Daemonize? In-Reply-To: <20020907161037.GA70503@hishome.net> References: <20020907161037.GA70503@hishome.net> Message-ID: <20020907174957.GA25058@glacier.arctrix.com> Oren Tirosh wrote: > devnull = os.open('/dev/null', 0) > os.dup2(devnull, 0) > os.dup2(devnull, 1) > os.dup2(devnull, 2) > > This is safer because it prevents these file descriptors from being reused. Better: os.close(sys.__stdin__.fileno()) os.close(sys.__stdout__.fileno()) os.close(sys.__stderr__.fileno()) os.open('/dev/null', 0) os.dup(0) os.dup(0) pedanticly-y'rs Neil From marklists at mceahern.com Mon Sep 30 11:52:08 2002 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 30 Sep 2002 10:52:08 -0500 Subject: Question about __getattribute__/__getattr__ In-Reply-To: Message-ID: > if cached_value == None: This is an aside, but comparison to None should be via identity rather than equality; e.g., if x is None: or: if x is not None: Why? Because you may be comparing an object that barfs when compared to None via its own __eq__ method. It's a subtle point and I don't think I'm explaining it very well. Suffice it to say, if you really are comparing to None, use is/is not. If you want to test whether an object is/is not zero, then use: if x: or: if not x: // m From mak at trisoft.com.pl Mon Sep 16 07:50:26 2002 From: mak at trisoft.com.pl (Grzegorz Makarewicz) Date: Mon, 16 Sep 2002 13:50:26 +0200 Subject: upload/download to a palm os device with python References: <24165ed4.0209160304.7a3c08af@posting.google.com> Message-ID: <3D85C582.50101@trisoft.com.pl> Solon Kazantzidis wrote: > > 1. Is there a python library which I can use in order to access a palm > device and work on the databases (create new, delete existing, browse > existing) stored on it? > sf.net/projects/pilot-link - for Palm palms with http://www.pyrite.org/ for offline database manipulations. wincerapi for Windows CE devices mak From roy at panix.com Mon Sep 16 09:56:34 2002 From: roy at panix.com (Roy Smith) Date: Mon, 16 Sep 2002 09:56:34 -0400 Subject: Converting Python app to C++ completely References: <3D85D9EB.9020102@thinkware.se> Message-ID: Magnus Lycka wrote: > A common approach is to factor out the performance critical > parts (once you have actually measured) and rewrite them in > C or C++. The profiler is a good tool for this measuring. I'm in the process of doing exactly that. I've got an app I wrote in Python which needed speeding up. Profiling showed that 99% of the CPU time was spent in one class, which did a lot of low-level character processing. Mostly what it did was thrash around creating string objects and tearing them down again in a rather un-pythonic way. Seemed like a perfect opportunity to learn C++, so I re-wrote the class in that language. Somewhat surprisingly, I only got about a 2x speedup. I think the reason is because now instead of spending all my time allocating and deallocating Python strings, I'm doing the same with C++ strings :-) I'm going to take a shot at re-writing it again using C-style arrays of characters. It'll be interesting to see how much speedup I get. I figure one of two things will happen; either the C version will be much faster than the C++ version, or it won't. Either way, I figure I will have learned something about C++, and maybe about Python too :-) From jeremy at alum.mit.edu Thu Sep 5 15:30:13 2002 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 5 Sep 2002 12:30:13 -0700 Subject: newbie-question: Nested functions and variable scope References: <7a7157fd.0209041503.7b9a0f44@posting.google.com> Message-ID: leoboiko at linuxbr.com.br (Leonardo Boiko) wrote in message news:<7a7157fd.0209041503.7b9a0f44 at posting.google.com>... > Hi, I'm a Python newbie. I'm writing a program that uses expat. Some > code looks like this: > > def generate_main(filename="main.xml", (...)): > (...) > outfile = open (filename, "w") > in_reply = 0 # true if we are inside "reply" element > > def start_element(name, attrs): > if name == "reply": > in_reply = 1 > elif not in_reply: > outfile.write("<" + name.encode(encoding) + ">") [...] > If I put "in_reply" outside everything and use "global in_reply" > inside each nested function, it works, but that's evil! What would be > a better way of doing it? Do I need to use a class? You'd be better off using a class. You can't rebind a name in a nested scope. So there is no way to make in_reply a local variable in generate_main() and rebind it in start_element(). Jeremy From aicolburn at yahoo.com Thu Sep 12 12:56:50 2002 From: aicolburn at yahoo.com (Alan C.) Date: 12 Sep 2002 09:56:50 -0700 Subject: ANN: Thinking in Tkinter References: Message-ID: <1a3a9ffa.0209120856.1de06f57@posting.google.com> Your comments are well taken, Tom, but I think a little care is needed when using IDLE for learning Tkinter, just because the "root.mainloop()" command will hang IDLE in some circumstances. I enjoyed this tutorial. I had only two other thoughts/suggestions for you Steve. First, perhaps include a brief explanation early on about why you're creating the program within a class structure. As a Tkinter beginner myself, I'm thinking all the widgets could be added within the root frame, i.e., see the Tkinter notes at http://bembry.org/tech/python/index.shtml. [The reasons become a little clearer toward the end of the tutorial; I'm just thinking the overall document might be clearer to readers if some explanation was also included early on.] The other addition that I think newbies would appreciate is in the section of the tutorial where you're talking about events. I think it would be educational to distinguish between, say, "self.button1Click()" and "self.button1Click" I don't know for sure, but I bet there are folks who get confused distinguishing between them. Again, thanks for putting this together. I read it carefully :-) Al From mikemccand at bigfoot.com Wed Sep 25 10:28:39 2002 From: mikemccand at bigfoot.com (Mike McCandless) Date: 25 Sep 2002 07:28:39 -0700 Subject: how to check if a function signature "matches" without calling the function? References: Message-ID: Fantastic -- thank you! Python never ceases to amaze me ... Mike Alex Martelli wrote in message news:... > Mike McCandless wrote: > > > Does Python 2.2.1 make it possible for me to see some details about > > the expected arguments that a function takes, without actually calling > > the function? > > Yes. inspect.getargspec lets you learn all you need: > > import inspect > argnames, has_varargs, has_kdws, default_values = inspect.getargspec(func) > > > > Specifically, if I have a function or method object, and I have a > > tuple + dict of arguments I'd like to apply it on, is there a function > > I can call that would check if the tuple + dict can be properly > > "coerced" to the formal parameters? > > You still have some work to do for your checking, but it doesn't > seem to be much. You need to check you supply each mandatory > argument exactly once, and each optional argument 0 or 1 time; > you can have other positional args only if has_varargs, and > other named args only if has_kwds. E.g. for clarity: > > > class NoWay(Exception): pass > > def times_supplied(argname, argposition, atuple, adict): > return (argname in adict) + (argposition < len(atuple)) > > def check_args(argnames, default_values, atuple, adict): > > number_mandatory = len(argnames) - len(default_values) > > for pos in range(len(argnames)): > name = argnames[pos] > n = times_supplied(name, pos, atuple, adict) > if n<1 and pos raise NoWay, "Mandatory argument %s (%s) missing" % (name, pos) > elif n>1: > raise NoWay, "Argument %s (%s) given twice" % (name, pos) > > def check_funcargs(func, atuple, adict): > import inspect > names, has_varargs, has_kdws, defaults = inspect.getargspec(func) > check_args(names, defaults, atuple, adict) > if not has_varargs and len(atuple)>len(names): > raise NoWay, "Supplied %d positional args, max is %d" % ( > len(atuple), len(names) ) > if not has_kwds: > for name in adict: > if name not in names: > raise NoWay, "Unknown argument %s" % name > > > You can express this more concisely &c, of course, or use other > means than raising a dedicated exception to diagnose problems > (I only diagnose the first problem if any, that can be tweaked > too, of course). > > > Alex From gumuz at looze.net Tue Sep 3 04:14:02 2002 From: gumuz at looze.net (Gumuz) Date: Tue, 3 Sep 2002 10:14:02 +0200 Subject: what about things like __*** ? References: <7153651c.0209021927.16a3efaf@posting.google.com> Message-ID: <3d746df6$0$222$4d4ebb8e@news.nl.uu.net> ah great, I found asking this myself last night, too. isn't this the same for: __methodName(self, parm) which makes it a private method? "Eric Brunel" wrote in message news:al1p8n$12d$1 at wanadoo.fr... > black wrote: > > Hi, all~ > > > > when reading the tutorial I met some trouble.(Maybe trifle to you all > > but really trouble to me) > > > > That is I couldnt figure out what __*** is. Here is the description of > > that article but even confused me: > > > > There is limited support for class-private identifiers. Any identifier > > of the form __spam (at least two leading underscores, at most one > > trailing underscore) is now textually replaced with _classname__spam, > > where classname is the current class name with leading underscore(s) > > stripped. > > > > What's it trying to say please ??? > > As a good practice in object-oriented programming, the structure of a > class, i.e. its actual attributes, are often hidden from the outside world. > It's called "encapsulation". It helps to separate the interface of the > class from the actual implementation of the methods, that shouldn't be > known outside the class itself. > > Languages like C++ or Java have a native support for encapsulation, by > allowing to declare attributes "private" or "protected". A value of a > private or protected attribute can't be read or set by another class than > the owner class (or one of its sub-classes for protected attributes). > > IIRC, before Python 2.0, there were no support at all for encapsulation in > Python. So you could always do: > > class C: > def __init__(self): > self.a = 12 > o = C() > o.a = 13 > print o.a > > The attribute "a" of instances of class C can be read or modified outside > the class, and there's no (simple...) means to prevent that. > > From Python 2.0, there's a (limited) support for encapsulation: if the name > of an attribute begins with a double-underscore, it's just as if it had > been declared private: > > class C: > def __init__(self): > self.__a = 12 > def get_a(self): > return self.__a > o = C() > o.__a = 13 # Does not work > print o.__a # Again, does not work > print o.get_a() # Works > > class CC(C): > def __init__(self): > C.__init__(self) > print self.__a # Does *not* work > > The attribute __a is private: it can be seen only in the class C. It's > impossible to read or set it from outside the class, even in one of its > sub-classes. This sounds like a big restriction, but is actually very often > used in OO programming. > > The actual mechanism involves a "name-mangling", and that's what the > comment tried to explain. But it's not that important: the final result is > just that any attribute beginning with a double-underscore is private. > > HTH > -- > - Eric Brunel - > PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From moc.q-dnan-p at p-nand-q.com Mon Sep 2 01:02:23 2002 From: moc.q-dnan-p at p-nand-q.com (Gerson Kurz) Date: Mon, 02 Sep 2002 05:02:23 GMT Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: <3d72f007.1990343@News.CIS.DFN.DE> On Sun, 01 Sep 2002 21:07:24 -0000, "A.M. Kuchling" wrote: >The problem with a new syntax is that no one else would be using it, so >you'd still need to learn the existing syntax for use with grep, vi, Perl, >&c. (It wouldn't surprise me if Perl 6's revised regexes run into this very >difficulty and don't gain much adoption.) A tounge-in-cheek-answer: I don't use grep, I use python. I don't use vi, I use python. I don't use perl, I use python :) Seriously, my thinking was, the re.compile function is there to compile an expression to a binary representation for optimized searching. So maybe, a "clean syntax" -> "ugly re syntax" compiler would be good? Besides, you could use the output ("ugly re syntax") in grep, vi, perl if you really so intended. From DennisR at dair.com Tue Sep 17 17:26:21 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Tue, 17 Sep 2002 21:26:21 GMT Subject: Python comment stripper Message-ID: <16Nh9.248$Wc6.17087796@newssvr13.news.prodigy.com> Does anyone have a Python source comment stripper or can anyone recommend a parser that could be adapted for same? Why? ... well there is a better than 2:1 byte size reduction in both raw and compressed .py files if comments are stripped. Results of analyzing dospath.py in : raw Kb compressed Kb ---------- -------------------- original 10.44 2.98 4 spaces -> 1 space 8.85 2.86 + strip comments 4.65 1.34 -- Dennis Reinhardt http://www.dair.com From loewis at informatik.hu-berlin.de Mon Sep 9 05:17:13 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 09 Sep 2002 11:17:13 +0200 Subject: Computing directory sizes problem References: Message-ID: nmichael at yahoo.com (Neophytos Michael) writes: > Dear Python experts, > I wrote the following function to compute the size of a directory > (being new to python there maybe better ways to do this - if so please > advice). It works quite well except when the directory in question > contains files whose names that are not made up of ascii (english) > characters (this typically happens on my machine for my non-english > mp3 files). What Python version are you using? What localized Windows version? What are the file names in question? If the file names are non-ASCII, it should still work - provided the file names are supported in the system locale (i.e. ANSI code page). It might be easiest to adjust your system locale. Regards, Martin From cmay4 at yahoo.com Fri Sep 20 16:30:18 2002 From: cmay4 at yahoo.com (Chuck May) Date: Fri, 20 Sep 2002 20:30:18 GMT Subject: Python Sybase slow compared to Perl? Message-ID: I have always written my database scripts in Perl. I am very interested in Python, and would like to start using it for all my scripting. I am not trying to start a flame war, I'd just like to understand why a particular script I wrote runs so much faster under Perl. The script in question takes roughly 3 times as long to run under Python. It is very possible that there is a faster way to do this under Python. I cut out most of the script, leaving only the part of the scrit that does all the work. I am basically selecting all the fields from a table, looping over the results, and outputting the results in a fixed-width text file. Seems simple enough. Here is the Perl code snippet: # output the actual data $sth = $dbh->prepare( "SELECT $select FROM $table->[0]" ); $sth->execute(); $num_recs = 0; $tempfile = "$dumpfile.tmp.gz"; unlink $tempfile; open( DUMP_FILE, "| gzip -c > $tempfile" ) while ( @data = $sth->fetchrow_array() ) { $line = ""; for ( $i = 0; $i < scalar @lengths; $i++ ) { $line .= pack( "A$lengths[$i]", $data[$i] ); } print DUMP_FILE "$line\n"; $num_recs++; } close DUMP_FILE; $sth->finish(); and here is the Python code snippet: # output the actual data c = db.cursor() c.execute( "SELECT %s FROM %s" % ( select, table ) ) num_recs = 0 if os.path.isfile( "%s.gz" % dumpfile ): os.remove( "%s.gz" % dumpfile ) file = os.popen( "gzip -c > %s.gz" % dumpfile, "w" ) while 1: row = c.fetchone() if not row : break line = [] for i in range( len( row ) ): line.append( "%-*s" % ( lengths[i], row[i] ) ) print >> file, "".join( line ) num_recs += 1 file.close() c.close() No matter what table how many records there are, the Python script always takes longer to run (usually by a facter of 3 or more). I am still a Python newbie, so I may be doing something wrong. Has anyone else experienced similar results? Is this due to a poorly optimized Sybase module? I really want to use Python, and I don't mind giving up a little speed, but this is more than I can accept. I ran the Python script using the profiler and the output is below. Any help would be much appreciated. Thanks. Chuck May IMS, Inc. ------------- profile output: Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 1230.540 1230.540 :1(?) 4 0.000 0.000 0.000 0.000 Sybase.py:114(_get_diag) 2 0.000 0.000 0.000 0.000 Sybase.py:141(_ct_errors) 3 0.000 0.000 0.000 0.000 Sybase.py:148(_row_bind) 900345 96.240 0.000 96.240 0.000 Sybase.py:166(_extract_row) 900348 177.670 0.000 273.910 0.000 Sybase.py:180(_fetch_rows) 3 0.000 0.000 0.010 0.003 Sybase.py:229(__init__) 3 0.000 0.000 0.000 0.000 Sybase.py:246(__del__) 900361 83.230 0.000 267.090 0.000 Sybase.py:258(_lock) 900361 86.720 0.000 269.000 0.000 Sybase.py:262(_unlock) 3 0.000 0.000 0.010 0.003 Sybase.py:312(close) 3 0.000 0.000 0.000 0.000 Sybase.py:328(execute) 900348 178.280 0.000 988.260 0.001 Sybase.py:365(fetchone) 1 0.000 0.000 0.000 0.000 Sybase.py:408(fetchall) 3 0.000 0.000 0.000 0.000 Sybase.py:451(_fetch_rowcount) 3 0.000 0.000 0.000 0.000 Sybase.py:466(_start_results) 2 0.000 0.000 0.010 0.005 Sybase.py:494(__init__) 2 0.000 0.000 0.000 0.000 Sybase.py:522(_raise_error) 2 0.010 0.005 0.010 0.005 Sybase.py:527(connect) 2 0.000 0.000 0.000 0.000 Sybase.py:564(__del__) 4 0.000 0.000 0.000 0.000 Sybase.py:570(close) 3 0.000 0.000 0.010 0.003 Sybase.py:613(cursor) 2 0.000 0.000 0.000 0.000 Sybase.py:618(execute) 2 0.000 0.000 0.000 0.000 Sybase.py:640(_fetch_results) 2 0.000 0.000 0.010 0.005 Sybase.py:667(connect) 1 0.000 0.000 1230.540 1230.540 bsi_dump.py:176(main) 3 0.000 0.000 0.000 0.000 bsi_dump.py:238(outputMessage) 1 242.210 242.210 1230.520 1230.520 bsi_dump.py:39(dumptable) 1 0.030 0.030 0.030 0.030 commands.py:50 (getstatusoutput) 1 0.000 0.000 0.000 0.000 getopt.py:121(do_shorts) 1 0.000 0.000 0.000 0.000 getopt.py:136(short_has_arg) 1 0.000 0.000 0.000 0.000 getopt.py:35(getopt) 1 0.010 0.010 0.010 0.010 getpass.py:18(unix_getpass) 1 0.000 0.000 0.000 0.000 getpass.py:71(_raw_input) 2 0.000 0.000 0.000 0.000 posixpath.py:194(isfile) 1 0.080 0.080 1230.620 1230.620 profile:0(main()) 0 0.000 0.000 profile:0(profiler) 2 0.000 0.000 0.000 0.000 stat.py:29(S_IFMT) 2 0.000 0.000 0.000 0.000 stat.py:54(S_ISREG) 2 0.000 0.000 0.000 0.000 string.py:121(join) 2 0.000 0.000 0.000 0.000 threading.py:39(__init__) 1800738 60.630 0.000 60.630 0.000 threading.py:44(_note) 1800738 60.440 0.000 60.440 0.000 threading.py:581 (currentThread) 2 0.000 0.000 0.000 0.000 threading.py:64(RLock) 2 0.000 0.000 0.000 0.000 threading.py:69(__init__) 900369 123.010 0.000 183.860 0.000 threading.py:81(acquire) 900369 122.060 0.000 182.280 0.000 threading.py:99(release) From max at alcyone.com Fri Sep 13 15:12:08 2002 From: max at alcyone.com (Erik Max Francis) Date: Fri, 13 Sep 2002 12:12:08 -0700 Subject: transform list of int in a list of string?? References: Message-ID: <3D823888.AF9C6B6F@alcyone.com> jubafre at brturbo.com wrote: > How can i transform a list of integer numbers in a list of string > numbers, like that: > > x=[1,2,3,4] to y=['1', '2'...]???????? map(str, L) Or if you prefer list comprehensions, [str(x) for x in L] -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ To be a man means to be a fellow man. \__/ Leo Baeck PyUID / http://www.alcyone.com/pyos/uid/ A module for generating "unique" IDs in Python. From mikael.lexen at spam.no.volvo.com Thu Sep 26 10:08:50 2002 From: mikael.lexen at spam.no.volvo.com (Mikael =?iso-8859-1?Q?Lex=E9n?=) Date: Thu, 26 Sep 2002 16:08:50 +0200 Subject: unicode woes References: <3d92d120$0$76313$e4fe514c@dreader4.news.xs4all.nl> Message-ID: <3D9314F2.1C30196A@spam.no.volvo.com> You can find information about Python 2.3 in this document http://www.python.org/dev/doc/devel/whatsnew/section-encodings.html /Mikael Ulli Stein wrote: > Radovan Garabik wrote: > > > Ulli Stein wrote: > > : But nevertheless you would have to use everywhere the Python unicode() > > : function. > > > > : Or how would you do this (nonsense string): > > : str = str + "bla?" + str[:5] + "?? > > > > : Would you write then: > > : str = str + unicode("bla?") + str[:5] + unicode("??)? > > > > I ran into the same problem and find out that python2.3 > > handles this. > > Just add the line > > # -*- coding: UTF-8 -*- > > as the second line of your python script and then > > you can use all your strings in UTF-8 encoding > > (or any other, whatever fits you) > > > > From where do you have this information? Is there some official changelog > for python2.3? > > Thanks. From edgebruce at yahoo.com Mon Sep 30 18:51:40 2002 From: edgebruce at yahoo.com (Bruce Edge) Date: Mon, 30 Sep 2002 15:51:40 -0700 Subject: Id, or stinky primo? Message-ID: <7A4m9.25416$V64.5149538@newsfeed.slurp.net> Is the Id it really worth the $$$$? I've been looking at a kona stinky primo, and it seems like a comparable bike for less dough. What's the general opinion out there? Why is the Id better? -Bruce. From wolfson at midway.uchicago.edu Thu Sep 5 02:56:24 2002 From: wolfson at midway.uchicago.edu (Ben Wolfson) Date: Thu, 05 Sep 2002 06:56:24 GMT Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <4pid9.5883$e5.1033514@newsb.telia.net> Message-ID: <8vvdnucccqp2och24gigcmmc91njbjkhhk@4ax.com> On Thu, 05 Sep 2002 06:41:14 GMT, "Fredrik Lundh" wrote: >Bengt Richter wrote: > >> >you can ask SRE to dump the internal parse tree >> >to stdout: >> > >> >>>> sre.compile("[a-z]\d*", sre.DEBUG) >> >in >> > range (97, 122) >> >max_repeat 0 65535 >> > in >> > category category_digit >> > >> >turning this into 'English' is left as an exercise etc. >> >> Interesting, thanks. Does the above mean that sre can't fully match >> 'a'+'9'*65537 >> ? > >in this context, 65535 represents any number: Doesn't that cause problems for something like this? >>> m=re.compile(r'\d{0,65535}a').match(('9'*1000000)+'a') >>> len(m.group(0)) 1000001 -- BTR You're going to set me up as a kind of slovenly attached pig that Jack Kornfeld can slice down in his violent zen compassion? -- Larry Block From martin at v.loewis.de Sat Sep 14 16:50:04 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 14 Sep 2002 22:50:04 +0200 Subject: Python11 References: Message-ID: "Jeff Sasmor" writes: > Is there any definitive information on the next Python conference, > Python 11? I've read the conferences-discuss archive on > Python.org (http://mail.python.org/pipermail/conferences-discuss/) > and the discussion seems to be tapering off. IIRC, by last year > at this time there was already a call for papers. Python11 will be colocated with the O'Reilly Open Source Convention (OSCON), which will take place July 7-11, 2003 in Portland, USA. I believe O'Reilly will organize the specific schedule, including setting dates for the call for papers, submission deadlines, etc. Given that this is still ten months away, I don't see any urgency. HTH, Martin From GavinT at ResMed.com.au Tue Sep 17 23:48:58 2002 From: GavinT at ResMed.com.au (Gavin Tomlins) Date: Wed, 18 Sep 2002 13:48:58 +1000 Subject: PythonScript Message-ID: <362133AB12B2CE4EA3C01E12CD6CCC6E0254E08B@osprey.corp.resmed.org> Greetings, Firstly apologies if this is slightly out of the scope of the mailing list but after searching the web, archives I've been unable to find references of PythonScript with its use with the activescript engine. I own March Hammond & Andy Robinson's Python Win32 Programming and have gone over there chapter of active scripting though there examples focus more on python and activescripting via the command shell. The problem I seem to be hitting is utilising python in applications that embed an ActiveScript Engine. To date I am unable to get one python script to execute. Other languages vbscript, jscript,perl etc, work in the same environment so I'm left wondering if its a configuration problem or something that I might be overlooking. If anyone could give me pointers, url's, snippets etc. it would be interested. The product I specifically having problems is FinalBuilder (http://www.atozedsoftware.com) though have seen this problem in other applications as well. I've tried both ActiveState and Python distribution 2.2.1 with Win32 1.48all. Regards Gavin Warning: Copyright ResMed. Where the contents of this email and/or attachment includes materials prepared by ResMed, the use of those materials is subject exclusively to the conditions of engagement between ResMed and the intended recipient. This communication is confidential and may contain legally privileged information. By the use of email over the Internet or other communication systems, ResMed is not waiving either confidentiality of, or legal privilege in,the content of the email and of any attachments. If the recipient of this message is not the intended addressee, please call ResMed immediately on +61 2 9886 5000 Sydney, Australia. From tjreedy at udel.edu Wed Sep 25 10:56:15 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Sep 2002 14:56:15 GMT Subject: What function called this function ?? References: <98jk9.22340$0p1.391334@news2.ulv.nextra.no> Message-ID: "Thomas Weholt" <2002 at weholt.org> wrote in message news:98jk9.22340$0p1.391334 at news2.ulv.nextra.no... > Is it possible, by hacking the traceback/stack/etc, to get information about > the function, that functions class and in what module that function and > class are defined, from inside a function located elsewhere? Something like > a way of answering the question of "who called me?" without sending the > answer along as a parameter. Yes. Traceback hack has been posted previously. If not in the FAQ, you might find posts thru groups.google.com. TJR From andrea.baglioni at redturtle.net Fri Sep 6 04:25:14 2002 From: andrea.baglioni at redturtle.net (andrea.baglioni at redturtle.net) Date: Fri, 6 Sep 2002 10:25:14 +0200 Subject: .py to .pyc Message-ID: Hi everybody, I'm a python newbie and i've a problem. I want to compile a python file called File.py and i want to produce a file called File.pyc, so i do python File.py I always find the following error: Traceback (most recent call last): File "File.py", line 18, in ? import Globals, StructuredText, string, utils, re ImportError: No module named Globals Can anybody help me to find the problem? I think it's a problem of $PYTHONPATH and $PYTHONHOME but i'm not sure. Please...help! Thanx in advance Andrew From martin at v.loewis.de Mon Sep 9 01:39:28 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 09 Sep 2002 07:39:28 +0200 Subject: Unicode -> String problem References: <20010708204337.MJGP11827.femail4.rdc1.on.home.com@jparlar> <3B48D1DB.C3F726C9@ActiveState.com> Message-ID: pinard at iro.umontreal.ca (Fran?ois Pinard) writes: > For now, I would presume that `codecs.ascii_encode(UNICODE_STRING)' does the > same as `UNICODE_STRING.encode("ascii")' and consequently, we do not need to > know about `ascii_encode'. Is that right? In the context of the OP's question, you'd use UNICODE_STRING.encode("ascii", "replace"), or, perhaps, codecs.getencoder("ascii")(UNICODE_STRING, "replace"). Regards, Martin From rjones at ekit-inc.com Tue Sep 24 18:01:17 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Wed, 25 Sep 2002 08:01:17 +1000 Subject: Difference between MOD_PYTHON and the CGI module In-Reply-To: <3d904321$0$234$4d4ebb8e@news.nl.uu.net> References: <3d904321$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: <200209250801.17174.rjones@ekit-inc.com> On Tue, 24 Sep 2002 8:55 pm, Gumuz wrote: > Suppose I'd like to use python as a 'replacement' for PHP, what do I use? Visit http://www.python.org/cgi-bin/moinmoin/WebProgramming and browse the offerings, then choose whatever solution feels best to you. Richard From david at fielden.com.au Fri Sep 13 00:05:36 2002 From: david at fielden.com.au (DG) Date: Fri, 13 Sep 2002 14:05:36 +1000 Subject: problems with getpass.getpass() under Linux In-Reply-To: <40197710-C6C9-11D6-B141-00039351FE6A@mac.com> Message-ID: <008601c25ada$d1a5f580$3101a8c0@borg.fielden.com.au> Greetings, I have Slackware Linux 8.0 with the (as distributed) Python 2.0.1 installed. When I import getpass and try to getpass.getpass() I get the following error and the password is echoed: "Warning: Problem with getpass. Passwords may be echoed." Looking into getpass.py it does this: try: import termios, TERMIOS If that fails, it goes on to try to import Windows and then Mac-specific modules, with a fallback to just calling raw_input (effectively). I have TERMIOS.py in /usr/lib/python2.0/plat-linux2 but I do not have termios.py anywhere. I have the Python 2.2.1 tarball (not (yet) installed), it contains TERMIOS.py and but not termios.py (altho it does have a termios.c). I notice that the 2.2.1 getpass.py only tries to import termios. What do I need to do to have getpass.getpass() work correctly? tia Rowdy From jacob at boris.cd.chalmers.se.cd.chalmers.se Wed Sep 25 10:00:43 2002 From: jacob at boris.cd.chalmers.se.cd.chalmers.se (Jacob Hallen) Date: 25 Sep 2002 14:00:43 GMT Subject: Larry Wall's comment on python... References: <3D7958DB.50903@nospam.free.fr> <3D87402E.6020700@thinkware.se> Message-ID: In article <3D87402E.6020700 at thinkware.se>, Magnus Lyck? wrote: ... >My personal experience from many years of coding C++ etc >with curlies and Python without, is that I tend to get >lost a lot more in my C++ code than in my Python code. >Not to mention the code of others... I've certainly had >a number of debugging sessions where I had to help some >mediocre C++ coder who couldn't match his own braces... >The problem is usually that the blocks get to big... The >fact that you can get away with incorrect indentation in >the brace-languages makes it worse. > >Most modern editors have tools like indentation guides and >folding that can make it easier to see block structures. > >Was it one of Beethoven's symphonies that ended so abruptly >that the audience didn't understand when to applaud? It was >considered a big failure at it's time, and it's considered >one of the best works of a genious today... I think there is a good explanation for why code with explicit delimiters is harder to read and follow than normal Python code. There is an absolutely outstanding series of books by Edward Tufte about how to create charts, tables and other information presentation graphics. In his books he introduces a measurable unit called "Chart junk". This is the percentage of the ink used in the chart that does not convey information. Ink does not convey information if it can be erased, or if by changing the position of other ink in the diagram, you can leave the ink out. Tufte then goes on to practically show that the unit is a relevant one to ease of understanding. The books are beautiful and should be required reading for anyone who ever designs a user interface. In any case, I think that there exists something we can call source-junk, which is the programming language equivalent of chart-junk. It is all the "ink" in the source code that does not add to your understanding of what the code does. Block starts and ends can be represented by white areas. Redundant parenthesis can be thrown away. Declarations are seldom needed by the programmer in order to understand the program. The most important parts of your program, for understanding how it works is the names of your objects (variables, classes, methods, functions, modules). Second to that is the operations you do on your objects - how you combine them. That's about it. Please note that I didn't say anything about block delimiters or parentheses in this. I think they were put into programming languages to make it easy to write fast compilers. I also think that one of the factors making C so popular was that the BEGIN/END of Pascal and ADA were even more intrusive than {}, so people considered C to be much more readable than the competitors. The lack of source junk is certainly the biggest thing that attracts me to Python. The rest of the benefits are fairly pedestrian. This one is the really big win. Jacob Hall?n A -- From gumuz at looze.net Tue Sep 3 11:15:42 2002 From: gumuz at looze.net (Gumuz) Date: Tue, 3 Sep 2002 17:15:42 +0200 Subject: Design question.... parent/child class References: <3d74b021$0$234$4d4ebb8e@news.nl.uu.net> <3d74b283$1@news.sentex.net> Message-ID: <3d74d0c9$0$225$4d4ebb8e@news.nl.uu.net> I'm sorry, I don't think I understand it correctly. Do you mean i should create a third Interface class just to communicate to the other class? Isn't that then just the same but with an extra class? "Peter Hansen" wrote in message news:3d74b283$1 at news.sentex.net... > Gumuz wrote: > > hi all, > > > > i have a SessionManager class, which contains a list of Session > > objects(instantiated from a Session class). I have a design problem. > > > > Each session object has a small 'queue' of messages for the specific > > session. How can a session send a message to another session without having > > some kind of parent-reference to the SessionManager object? > > > > i am a bit puzzled, or is this parent-reference not such a bad idea after > > all? > > Increasing coupling is always bad, but you could do this in a way that > doesn't really increase coupling (at least in Python). The Session > objects don't need to know about SessionManagers specifically, just > about some thing that has a particular interface. In this case, maybe > it's a "post" method. Pass in a reference to the SessionManager, > or even the post method itself (a "bound" method, bound to a specific > SessionManager instance), but don't do an "import sessionmanager" > or anything like that in the session.py module itself. > > Note that passing messages between Sessions could be considered a > function not appropriate for something called merely "SessionManager". > Maybe you want to do this with another mechanism in parallel to this, > or rename that class. Personally, I wouldn't do that unless the > whole design was starting to get complex. > > -Peter > From tdelaney at avaya.com Wed Sep 11 19:37:17 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 12 Sep 2002 09:37:17 +1000 Subject: "str.contains(part)" or alternatives? Message-ID: > From: Stefan Schwarzer [mailto:sschwarzer at sschwarzer.net] > > "if part in s" disturbs the pattern "if item in sequence" > somewhat but that has > already been weakened by "if key in dict" (that I like, nonetheless). In fact, this was the deciding factor in Guido changing his position on 'if s1 in s2'. A string has sequence-like behaviour (e.g. it is iterable, individual characters can be indexed), but also has its own behaviour (e.g. substring containment, all elements are single-character strings). Tim Delaney From wlfraed at ix.netcom.com Sun Sep 1 23:10:44 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 01 Sep 2002 20:10:44 -0700 Subject: curses: AttributeError: initscr References: Message-ID: Cesar fed this fish to the penguins on Sunday 01 September 2002 05:52 pm: > > > I'm running python 1.5/2.2.1 under redhat linux 7.2. > So which is it when you get the error? I could be wrong (I've not kept track of when certain changes took effect) but does 1.5 understand library directories? On this system (Mandrake) curses is a directory with an __init__.py file. What does (from python) dir(curses) return? -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From yaipa at aol.com Wed Sep 18 17:59:24 2002 From: yaipa at aol.com (yaipa) Date: 18 Sep 2002 14:59:24 -0700 Subject: When we say 'One obvious way...', do we mean 'generally obvious' or does that matter? Message-ID: <8d148763.0209181359.68cd789f@posting.google.com> Code from mail thread: http://groups.google.com/groups?dq=&hl=en&lr=&ie=UTF-8&frame=right&th=ef69520e5c dd3170&seekm=mailman.1031971577.27090.python-list%40python.org#link1 I LIKE the below code snippet. While it might be Pythonic, it will only be 'obvious' to a Python programmer with some experience under his/her belt. *** Comments begin again after code snippet **** ------------------------------------------------------------------------- #!/usr/bin/env python import inspect def make_undefined(cls, attr): def undefined(self, *args, **kwargs): msg = "'%s' object has no attribute '%s'" % (cls.__name__, attr) raise AttributeError(msg) return undefined def is_magic(attr): prefix = suffix = '__' return attr.startswith(prefix) and attr.endswith(suffix) class Restricted(type): common = ['__class__', '__defined__', '__dict__', '__doc__', '__getattribute__', '__init__', '__new__'] def __new__(cls, classname, bases, classdict): defined_key = 'defined' defined = classdict.get(defined_key, []) + Restricted.common # If a non-magic attribute from any base class is not in common or # defined, hide it with a method that raises a descriptive # AttributeError (mimicking Python). for base in bases: for k, v in inspect.getmembers(base): if not is_magic(k) and k not in defined: classdict[k] = make_undefined(cls, k) return type.__new__(cls, classname, bases, classdict) class RestrictedDict(dict): __metaclass__ = Restricted defined = ['put', 'get', 'keys', 'items', 'values'] f = RestrictedDict() print f.keys print f.keys() f['a'] = 'b' print f.keys() try: f.clear() except AttributeError: pass print f.keys() ------------------------------------------------------------------------- *** More Comments *** ------------------------------------------------------------------------- The flip side of this would be to build up accessors with a root class that can only 'get' a key or keys and finish with a child class that can get/set/add and destroy key(s) in the dictionary. Then the user of such a library can inherit from the accessor class that which fits his/her needs. While this is practiced in other languages, I don't see it much used in Python. Does the 'one obverse' rule mean the one way that is more 'Generic' or more 'Pythonic'? As a note, here are my accessors and a couple of data dictionary classes ------------------------------------------------------------------------- class StaticFinalDictionaryMethods: #1. class only allows the getting of dictionary names/values. # Private Class level Vars. def __init__ (self): pass def getKeys(self): return self._dictionary.keys() def getNamePairs(self): return self._dictionary.items() def getByKey(self, _key, _index = 'None'): # test to make sure key is valid if self._dictionary.has_key(_key): if _index == 'None' or (_index >= self.min and _index < \ len(self._dictionary[_key])): if _index == 'None': return self._dictionary[_key] else: return self._dictionary[_key][_index] else: return 'None' else: return 'no_such_key' class BasicDictionaryMethods(StaticFinalDictionaryMethods): #1. class allows the getting of dictionary names/values. #2. class allows the setting of dictionary values by hash name. # Private Class level Vars. def __init__(self): # Python requires us to explicity call the super class StaticFinalDictionaryMethods.__init__(self) #Class private Setter for Task startup initilization # Does not support updating single element of a tuple. def setByKey(self, _key, _value, _index = 'None'): # test to make sure key is valid if self._dictionary.has_key(_key): if _index == 'None': # set tuple here self._dictionary[_key] = _value else: print _key, " - ERROR, TaskCore.setByKey().error - no_such_key" class DynamicDictionary(BasicDictionaryMethods): def __init__(self): BasicDictionaryMethods.__init__(self) def addkey(self, _key, _value): self._dictionary.setdefault(_key,[]).append(_value) # end accessors #--------------------------------------------------------------- # class ExitTerms(TaskDataAccess.StaticFinalDictionaryMethods): # Private Class level Vars. def __init__ (self): # explicit call to the super class TaskDataAccess.StaticFinalDictionaryMethods.__init__ (self) # private dictionary, only 'self.' class methods can access. self._dictionary = { 'ttf' : None, 'exitKey' : "unset_exitKey", 'symptom' : "unset_symptom", 'message' : "unset_message", } class DynamicKeys(TaskDataAccess.DynamicDictionary): # Private Class level Vars. def __init__ (self): # explicit call to the super class TaskDataAccess.DynamicDictionary.__init__ (self) self.min = 0 # Build DataStructure and __init__ each '_key' in dictionary. # ------------------------------------------------------------- # private dictionary, only 'self.' class methods can access. self._dictionary = {} From jhorneman at pobox.com Sun Sep 29 16:09:11 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: Sun, 29 Sep 2002 22:09:11 +0200 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <3d9739c7$0$19818$91cee783@newsreader01.highway.telekom.at> Message-ID: <3d975d86$0$24792$91cee783@newsreader01.highway.telekom.at> "Jurie Horneman" wrote in message news:3d9739c7$0$19818$91cee783 at newsreader01.highway.telekom.at... > "Jurie Horneman" wrote in message > news:9ac02e81.0209290839.4f4d6475 at posting.google.com... > > However, I do stand by my criticisms of the Python docs. No - I've changed my mind. Slightly. Although a few functions are undocumented, the documentation of the imp module did contain the information I wanted. Plus there's a rather good example which I should have examined more closely... alright, some egg on my face there. Jurie. From ken at hotmail.com Thu Sep 26 02:19:08 2002 From: ken at hotmail.com (Ken) Date: Thu, 26 Sep 2002 16:19:08 +1000 Subject: How to send Email using Python? Message-ID: Hi all, I like to know how to send a HTML featured Email from Python? I know how to do a text based version using SMTPLib, but not sure how to do it with a HTML featured Email. Can someone help me? Can someone provide me with sample code? Thanks From GavinT at ResMed.com.au Wed Sep 18 19:26:25 2002 From: GavinT at ResMed.com.au (Gavin Tomlins) Date: Thu, 19 Sep 2002 09:26:25 +1000 Subject: PythonScript Message-ID: <362133AB12B2CE4EA3C01E12CD6CCC6E0254E097@osprey.corp.resmed.org> Hi Mark, thanks for the replay and apologies for mispelling your name. The application that I'm trying to get working is FinalBuilder (http://www.atozedsoftware.com/ a build/release tool. Would it be possible to suggest a small thirdparty product support PythonScript and ActiveScripting that would be good for a test harness so as to do comparative testing ? Is there any fundamental difference between the Win32 1.48all and the ActiveState distribution ? I'm assuming that you are right in terms of the application support as the internet explorer test pages appear to work after registering the python activescript script. Regards Gavin You located in Melb/Syd ? -----Original Message----- From: Mark Hammond [mailto:mhammond at skippinet.com.au] Sent: Wednesday, 18 September 2002 10:58 PM To: python-list at python.org Subject: Re: PythonScript Gavin Tomlins wrote: > Greetings, > > Firstly apologies if this is slightly out of the scope of the mailing list > but after searching the web, archives I've been unable to find references of > PythonScript with its use with the activescript engine. I own March Hammond > & Andy Robinson's Python Win32 Programming and have gone over there chapter > of active scripting though there examples focus more on python and > activescripting via the command shell. > > The problem I seem to be hitting is utilising python in applications that > embed an ActiveScript Engine. To date I am unable to get one python script > to execute. Other languages vbscript, jscript,perl etc, work in the same > environment so I'm left wondering if its a configuration problem or > something that I might be overlooking. If anyone could give me pointers, > url's, snippets etc. it would be interested. The product I specifically > having problems is FinalBuilder (http://www.atozedsoftware.com) though have > seen this problem in other applications as well. > It is likely to be some strange interaction between PythonScript and the host. Python works fine in all MS hosts, and quite a number of 3rd party ones. What application is it? Mark. -- http://mail.python.org/mailman/listinfo/python-list Warning: Copyright ResMed. Where the contents of this email and/or attachment includes materials prepared by ResMed, the use of those materials is subject exclusively to the conditions of engagement between ResMed and the intended recipient. This communication is confidential and may contain legally privileged information. By the use of email over the Internet or other communication systems, ResMed is not waiving either confidentiality of, or legal privilege in,the content of the email and of any attachments. If the recipient of this message is not the intended addressee, please call ResMed immediately on +61 2 9886 5000 Sydney, Australia. From aleax at aleax.it Tue Sep 24 08:12:50 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 12:12:50 GMT Subject: how to build up a guest book with python ? References: Message-ID: <6FYj9.157588$pX1.5677010@news2.tin.it> black wrote: > I'm learning python for almost 1 month and decide to build up a guest > book with it, but I really know nothing about web programming, any > tutorials for me please ? Steve Holden's "Python Web Programming" (New Riders) should be perfect for your needs -- it touches on all the technologies you need to be acquainted with for the purpose, and gives a good tutorial grounding in each of them. (I'm biased: Steve is a friend and I was a tech editor for the book -- but I have some counter-bias to compensate, as I could be recommending my own books instead of his, so it probably balances out:-). Alex From wyojustin at hotmail.com Tue Sep 24 23:07:15 2002 From: wyojustin at hotmail.com (Justin Shaw) Date: Wed, 25 Sep 2002 03:07:15 GMT Subject: Removing all occurences of a character from a string. References: Message-ID: > How can I remove the single quotes so that "'Hello World'" becomes "Hello World"? Try this one: >>> s = "'Hello World'" >>> print s.replace("'", "") Hello World >>> Justin > I have a string, say "'Hello World'", where Hello World is in single > quotes(i.e., 'Hello World'). How can I remove the single quotes so that > "'Hello World'" becomes "Hello World"? > Thanks > Sean Ross > > From leader730 at hotmail.com Sat Sep 7 16:03:57 2002 From: leader730 at hotmail.com (Leader) Date: Sat, 7 Sep 2002 16:03:57 -0400 Subject: getting clients ip address Message-ID: Hello, I am using Python for my website, more specifically Spyce+mod_python, what I want to do is print out the clients ip address on the site so it can say something like "your ip is:xxx.xxx.xxx.xxx" basicly the python version of I'm sure I saw something a while ago while browsing through the module docs but I can't find it anymore. thanks From andremoy1 at terra.com.pe Mon Sep 9 22:36:57 2002 From: andremoy1 at terra.com.pe (andremoy1) Date: Mon, 9 Sep 2002 21:36:57 -0500 (PET) Subject: Cellpadding Message-ID: <20020910023657.3725612DCA6@smtp1.terra.com.pe> An HTML attachment was scrubbed... URL: -------------- next part -------------- -- Antivirus de Terra ha detectado un grave virus en "este mensaje". Con la finalidad de evitar su contagio, hemos procedido a borrar el virus -- border.scr is removed from here because it contains a virus. Si tiene alguna consulta o comentario escr?banos a antivirus at terra.com.pe - Terra Networks Peru S.A. - -------------- next part -------------- A non-text attachment was scrubbed... Name: content14136-0.html Type: application/octet-stream Size: 654 bytes Desc: not available URL: From ahmad at NOSPAMbitbuilder.com Mon Sep 9 16:11:46 2002 From: ahmad at NOSPAMbitbuilder.com (Ahmad Baitalmal) Date: Mon, 09 Sep 2002 20:11:46 GMT Subject: xml.minidom is stripping out my CRLF's in attrib values!! References: <3D7C80C4.9070204@NOSPAMbitbuilder.com> <3D7C8C76.8060700@NOSPAMbitbuilder.com> Message-ID: <3D7D00AE.4080900@NOSPAMbitbuilder.com> That is the solution I went with. Just replaced all "\n" with " " and all "\r" with "&$013;". Works fine now, but, I think I will try the xml:space solution also. Thanks all! Duncan Booth wrote: > Ahmad Baitalmal wrote in > news:3D7C8C76.8060700 at NOSPAMbitbuilder.com: > > >>That's not what my problem is, that I know about ( crlf's between >>nodes),, >> >>Here is the deal: >> >> >> >> >>After the word "spotted" there is a crlf, -inside- the attribute >>value. Sholdn't it be treated as part of the value? >> >>The value now comes stripped of that crlf. > > > The XML specification, para 3.3.3 specifies that attribute values must > be normalised. The normalisation will convert your newline to a space and > may also remove duplicate spaces: > > >>3.3.3 Attribute-Value Normalization >>Before the value of an attribute is passed to the application or >>checked for validity, the XML processor must normalize the attribute >>value by applying the algorithm below, or by using some other method >>such that the value passed to the application is the same as that >>produced by the algorithm. >> >>All line breaks must have been normalized on input to #xA as described >>in 2.11 End-of-Line Handling, so the rest of this algorithm operates >>on text normalized in this way. >> >>Begin with a normalized value consisting of the empty string. >> >>For each character, entity reference, or character reference in the >>unnormalized attribute value, beginning with the first and continuing >>to the last, do the following: >> >>For a character reference, append the referenced character to the >>normalized value. >> >>For an entity reference, recursively apply step 3 of this algorithm to >>the replacement text of the entity. >> >>For a white space character (#x20, #xD, #xA, #x9), append a space >>character (#x20) to the normalized value. >> >>For another character, append the character to the normalized value. >> >>If the attribute type is not CDATA, then the XML processor must >>further process the normalized attribute value by discarding any >>leading and trailing space (#x20) characters, and by replacing >>sequences of space (#x20) characters by a single space (#x20) >>character. >> >>Note that if the unnormalized attribute value contains a character >>reference to a white space character other than space (#x20), the >>normalized value contains the referenced character itself (#xD, #xA or >>#x9). This contrasts with the case where the unnormalized value >>contains a white space character (not a reference), which is replaced >>with a space character (#x20) in the normalized value and also >>contrasts with the case where the unnormalized value contains an >>entity reference whose replacement text contains a white space >>character; being recursively processed, the white space character is >>replaced with a space character (#x20) in the normalized value. >> >>All attributes for which no declaration has been read should be >>treated by a non-validating processor as if declared CDATA. >> > > > So the only way to get a newline into an attribute is to escape it in using > an entity reference. > -- - - -- ---- ----------------------------------------- --- -- - - *Ahmad Baitalmal*** *BitBuilder*** web: http://www.bitbuilder.com - - -- ---- -------------------------------------------------------------- --- -- - - From robin at alldunn.NOSPAM.com Thu Sep 19 23:41:10 2002 From: robin at alldunn.NOSPAM.com (Robin Dunn) Date: Fri, 20 Sep 2002 03:41:10 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <6_Ph9.479711$q53.16315681@twister.austin.rr.com> <3d8868b1$0$28683@echo-01.iinet.net.au> <1Y0i9.508708$UU1.84704@sccrnsc03> Message-ID: bap wrote: > Does wx work with ActiveState Python? I tried to use and as soon as > wxWindows imports, Python (2.2) > bombs and your back out at Windows with no error message. On another group I > was > told that this is a known issue and wxWindows doesn't work with Active State > Python. It has trouble running within the PythonWin GUI, but works just fine with the Python interpreter itself. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From aleax at aleax.it Thu Sep 26 14:43:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 18:43:16 GMT Subject: design question References: <1ha6pukqdqell8f31q1k7rtor2rv5ogjs0@4ax.com> Message-ID: <8zIk9.147208$ub2.3246077@news1.tin.it> Gon?alo Rodrigues wrote: ... > Class1 > | > | > Class2 > > Where the dashed line means a parent-child relationship. Now what I want > is something like > > Wrapper1 > | > | > Wrapper2 > > where Wrapper1 (Wrapper2) wraps Class1(Class2) and the inheritance > reltionships between the several wrappers mirror those of the classes > they wrap -- but as I said, the protocol that the wrappers have can be > substantially different from the classes they wrap. > > Leaving aside the question of the usefulness of doing all this, I would > like to ask how would you proceed? Making Wrapper derive from Class is > stupid since their protocols can differ widely and I would end up with > lots of diamonds in the inheritance graph. On the other hand I could > just do: > > class Wrapper1(object) > def __init__(self, ): > self.__wrap = Class1() > > > But then if I did the same with Wrapper2, it would be at least quirky > since it inherits from Wrapper1 but it wraps Class1 puzzled bewilderment> Don't use __wrap as it interferes with communication between Wrapper1 and Wrapper2; use _wrap, with a single underscore, so that such communication within your own hierarchy of wrappers is unimpeded, whild (by convention) you're still communicating to the outside world that this is an internal implementation detail. Declare all your wrapper's __init__ method with a similarly named optional argument, a tuple that determines what factory callable to call to get the object to be wrapped: class Wrapper1(object): def __init__(self, , _wrap=(Class1,)): self._wrap = _wrap[0](*_wrap[1:]) class Wrapper2(Wrapper1): def __init__(self, , _wrap=(Class2,)): super(Wrapper2, self).__init__(, _wrap=_wrap) Alex From jimb417 at NO* Fri Sep 6 22:40:39 2002 From: jimb417 at NO* (Jim) Date: Fri, 06 Sep 2002 20:40:39 -0600 Subject: PyQT picture display Message-ID: Hello to all, I've a widget with three buttons and a label. I want to display a JPEG picture when either of the first two buttons is clicked. When I run the code below, the widget displays on screen but when either button is clicked, the picture does not appear( the text in the label disappears as it should ). Can anyone tell me what I'm doing wrong here? Thanks, Jim from qt import * import sys class Picts(QWidget): def __init__( self, parent = None, name = None ): QWidget.__init__( self, parent, name ) global Picture1 global Picture2 Picture1 = QPixmap( "!Pict1.jpg" ) Picture2 = QPixmap( "!Pict2.jpg" ) self.label = QLabel( "Click to see a picture!", self ) self.label.setGeometry( 50, 50, 300, 300 ) button1 = QPushButton( "Picture 1",self ) button1.setGeometry( 10, 10, 80, 30 ) button2 = QPushButton( "Picture 2",self ) button2.setGeometry( 100, 10, 80, 30 ) button3 = QPushButton( "Quit", self ) button3.setGeometry( 190, 10, 80, 30 ) self.connect( button1, SIGNAL( "clicked()" ), self.setPicture1 ) self.connect( button2, SIGNAL( "clicked()" ), self.setPicture2 ) self.connect( button3, SIGNAL( "clicked()" ), qApp, SLOT( "quit()" ) ) def setPicture1( self ): self.label.setPixmap( Picture1 ) def setPicture2( self ): self.label.setPixmap( Picture2 ) app = QApplication( sys.argv ) w = Picts() w.setGeometry( 100, 100, 500, 500 ) app.setMainWidget( w ) w.show() app.exec_loop() -- Registered Linux User #269187 http://counter.li.org From tim.one at comcast.net Fri Sep 20 15:33:25 2002 From: tim.one at comcast.net (Tim Peters) Date: Fri, 20 Sep 2002 15:33:25 -0400 Subject: e vs exp()? In-Reply-To: <7Hxi9.56777$216.2039933@bin4.nnrp.aus1.giganews.com> Message-ID: [Terry Reedy] > ... > On the hypothesis that x**y is calculated as exp(y*log(x)), Bad hypothesis. The implementation of a decent x**y function is one of the most difficult tasks in a platform's math library. The "naive" expression you give *can* be used if the library has an efficient way to do the internal computations using extended precision. Else it's a disaster: if all computations are done in the result's precision, log(x) introduces an error of its own, then that error is effectively multipled by y, and then the magnified error in that is used as an exponent! As a rule of thumb, the number of trailing bits in the result that are complete nonsense can be as bad as the number of bits in the internal float exponent field (this is specific to using that specific expression, of course). However, a decent modern libm supplies an x**y with error strictly less than 1 unit in the last bit. I've written such a beast without benefit of an extended hardware precision; I wouldn't want to do it again . WRT exp(y) vs math.e**y, math.e isn't the mathematical e, of course, and whatever representation error math.e suffers for cramming e into 53 bits is magnified by the "**y" part. exp(y) is going to be more accurate, unless the platform libm plain sucks (Ping Tak Peter Tang published a way to compute exp(y) that's very efficient, uses only native precision, and has worst-case error less than 0.53 units in the last place; I had the extreme pleasure of collaborating with him on a math library in a previous life). From steven_shaw at iprimus.com.au Tue Sep 10 12:01:07 2002 From: steven_shaw at iprimus.com.au (Steven Shaw) Date: Wed, 11 Sep 2002 02:01:07 +1000 Subject: dynamism References: <66715c02.0209091923.265fe77e@posting.google.com> Message-ID: <3d7e209a_1@news.iprimus.com.au> "Duncan Booth" wrote in message news:Xns92855D48384F9duncanrcpcouk at 127.0.0.1... > steven_shaw at adc.com (Steven Shaw) wrote in > news:66715c02.0209091923.265fe77e at posting.google.com: > > > > > I thought you could just extend an object's attributes at run-time > > like this: > > > >>>> p = object() > >>>> p.x = 1 > > Traceback (most recent call last): > > File "", line 1, in ? > > AttributeError: 'object' object has no attribute 'x' > > New style classes (which are those with 'object' or other builtin classes > as a base class) do not all allow you to add arbitrary attributes: > > If you have an object which is a builtin type (object, int, dict, ...) then > you cannot add attributes. If you have an object which is a subclass of a > builtin type, then you can add attributes unless the subclass defined a > member __slots__. > > The __slots__ attribute in a class, if defined, lists all of the attribute > names settable in instances of that class. If no __slots__ attribute is > directly defined in a class then you may add arbitrary attributes (this > applies even if __slots__ is set in a base class). > > An object of a builtin type, or with __slots__ defined in the class and > all base classes does not have a __dict__ attribute. Does this mean that the attributes are stored in a more efficient way? Is there a way to implement "record-based" object layout rather than "associative-array based" object layout? Cheers, Steve. From sholden at holdenweb.com Mon Sep 30 21:41:08 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 30 Sep 2002 21:41:08 -0400 Subject: PROBLEM with form in cgi References: Message-ID: "CheapSkate" wrote in message news:anas2k$i2b$1 at lust.ihug.co.nz... > HI, > I'm having problem trying to figure out what is wrong with my cgi script. > > here's the code that's creating the problem in the apple.cgi > The name of your script isn't very relevant. While it's good you tried to remove extraneous code, unfortunately you may have gone too far. You often find that this kind of message is actually due to an earlier error in the source. > print """
""" > ^ > it keeps on saying invalid syntax in the action(as indicated) The caret is pointing at the dot in "delete.html"? > and if I try to change it to this > print """""" > ^ Isn't this exactly the same as the lines above? > it gives the error at action. > I would suggest looking for an unclosed triple-quote (""") above this statement. That's typical of the kind of error that generates this anodyne and not-very-helpful message. Given the causes, it would be difficult to know what error message you *could* use to give the programmer more idea what went wrong. Good luck. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From andymac at bullseye.apana.org.au Fri Sep 13 20:25:31 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 14 Sep 2002 11:25:31 +1100 (edt) Subject: Dynamic loading of c modules,question. In-Reply-To: <1810446.1031909856@dbforums.com> Message-ID: [posted & mailed] On Fri, 13 Sep 2002, hpyhpy wrote: {...} > /****************************/ > example.i > > /* File : example.i */ > %module example > > extern int gcd(int x, int y); > extern double Foo; > /****************************/ > And I do : > #gcc -c example.c > #swig -python example.i > #gcc -c example_wrap.c -I/usr/local/include/python2.2/ > #gcc -G -Wl example.o example_wrap.o -o _examplecmodule.so ^ why the underscore here? {...} > So I wonder where is the "example.py"??? > So I can't "import example" > > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named example There would only be an example.py if you wrote it yourself. SWIG generates the extension module, which you can directly use without a wrapper in Python. if you rename _examplemodule.so to examplemodule.so, it should work. -- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au | Snail: PO Box 370 andymac at pcug.org.au | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From martin at v.loewis.de Thu Sep 19 15:25:21 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Sep 2002 21:25:21 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: Christian Tismer writes: > > Academically, I don't think the results are unpredictable, as > > micro-thread switch occur at predictable points in processing. > > Yes, right now, but this will change pretty soon. You mean, tasklet switches will occur at unpredictable times? This sounds like a bad idea. > I am not saying that the random module is not thread safe (although > I'm not sure if it is). To quote from the docstring: Multi-threading note: the random number generator used here is not thread- safe; it is possible that two calls return the same random value. > The point is: Microthread safety is more than thread safety, since > microthreads don't care about thread locks, since they are still *in > the same thread*. The issues are the same: the values of data may change at points where you don't expect them to change. Thread-safety means to be aware of such changes, and protect against them, by means of synchronization. > I have to do rigid locking of every unknown piece of code, until > somebody explicitly claims some code to be switchable. This, again, sounds terrible. I doubt it will help, and users will complain. Regards, Martin From gumuz at looze.net Wed Sep 4 07:14:15 2002 From: gumuz at looze.net (Gumuz) Date: Wed, 4 Sep 2002 13:14:15 +0200 Subject: encryption (passwords) References: <3d75d115$0$221$4d4ebb8e@news.nl.uu.net> <7xd6ru2gfi.fsf@ruckus.brouhaha.com> Message-ID: <3d75f0f0$0$230$4d4ebb8e@news.nl.uu.net> Actually, I am trying to create a sort of simple instant messenger server+client. although this is just a play-learn-project and security is not really an issue, i'd like to include encryption in it as well to get experience in this, too. "Paul Rubin" wrote in message news:7xd6ru2gfi.fsf at ruckus.brouhaha.com... > "Gumuz" writes: > > My limited understanding of encryption tells me that I need a 'key' to > > decrypt stuff. So I figure that this key will bey written(hard-coded?) > > somewhere in my Python-script and it needs to be known at both sides in > > order to encrypt and decrypt. Somehow, I can't believe this is true. I can't > > get over the idea that if my application becomes open-source anyone could > > see the key and decrypt my messages. > > > > I am fairly certain that it probably doesn't work this way, but I have > > really no idea. Cann someone clarify this for me? > > OK, first of all, that type of question is probably better asked on > sci.crypt rather than the Python group. > > Second, a word of advice: don't try to implement encryption protocols > with your present state of knowledge, and especially don't try to > design protocols yourself. It's extremely easy to make mistakes that > mess up security. Even experts make those mistakes, all the time. > > I'll sketch out answers to your questions but basically I think your > best approach is to use an unencrypted protocol between your Python > scripts, and tunnel it through an encrypting socket layer that someone > else has already debugged. The two most popular choices of encryption > layers are SSL and SSH. SSH has a "port forwarding" feature that lets > you set up local ports on both machines, that communicate through an > encrypted tunnel. Your Python program would just open the local port > and send unencrypted data to it, and the same data would appear at the > other end transparently decrypted. SSL is a fancier protocol that > doesn't incorporate forwarding, but there's a program called stunnel > that implements forwarding over SSL. > > Between the two, I'd say SSH is a easier to set up if you're just > trying to secure a single socket pair between two machines. If you're > trying to have a bunch of machines that talk to each other, and/or > they're not all controlled by the same people (e.g. you're a vendor > that needs to exchange secure traffic with various different > customers), you probably want to use SSL. That type of network is > called an extranet and various books have been written about how to > build and manage them. If you say more specifically what you're > trying to do, I or someone else here might be able to advise you more > usefully. > > Finally, if you're building any kind of secure system that's intended > to protect valuable data, I recommend you read "Security Engineering" > by Ross Anderson all the way through before deploying your system. It > will give you an idea of what you're up against and what kinds of > measures you can take. > > Re your basic questions: > > Yes you're correct that you need a secret decryption key. The key > should be unique for your specific installation, NOT part of the > program that gets distributed. It's like the password that you log > into your computer with. The login program is distributed freely as > source code, but your password is not part of it. You install the > program, THEN set your password for your specific account. > > Then there's the problem of how to store the key, so your program can > use it. There are several approaches, each with good and bad points: > > 1) Include the key, in cleartext form, as part of the program > configuration that gets loaded at program startup. Good points: > convenient. Bad point: anyone with access to the config file > (possibly gotten by breaking into your system) gets the key. > This method is not recommended if the data being protected is valuable. > > 2) Use a passphrase as a key that you enter when you start the > program, so it stays in memory and doesn't get stored on disk. > Good point: better security (key not stored). Bad points: you > have to enter the key every time you start the program. If you > want someone else to start the program for you, you have to tell > them the passphrase. If the program has to start without human > attention at reboot if the system crashes, you're hosed. > > 3) Encapsulate the key in a special hardware device that does the > cryptography. This can range from a $5 smart card or USB dongle, to a > multi-kilobuck sealed module on your PCI or SCSI bus. This is the > preferred method for high security applications (banking, etc.). Good > points: best security of all, key can't be stolen without physical > access to the machine, can implement its own access controls, etc. > Bad points: special hardware required; cheaper devices are slow. From david at no.westcontrol.spam.com Wed Sep 11 11:17:07 2002 From: david at no.westcontrol.spam.com (David Brown) Date: Wed, 11 Sep 2002 17:17:07 +0200 Subject: Multi-threading python References: Message-ID: "Michael Chermside" wrote in message news:mailman.1031751975.3372.python-list at python.org... > David Brown wrote: > > I've just been reading a little about the GIL and threading in python, and I > > have a couple of questions that I hope someone can answer. > > I'm not an expert, but I'll try. > > > Am I right in thinking that threading in Python does not use the underlying > > OS's threads, but effectively implements its own scheduler? Or does it use > > the OS's threads, but uses the GIL to ensure that only one is runable at a > > time? > > It uses the OS's threads, and then uses the GIL to ensure that only one > is executing Python bytecodes at a time. However, other threads may be > runable... they could be blocked waiting on I/O, or executing some C > code from a module that releases the GIL before performing a > long-running computation. > If C code (or other extensions) that take significant time, or block for other reasons, release the GIL then there I suppose there is not going to be much of a problem. The point is to maximize the throughput, and avoid threads blocking each other unnecessarily. > > On a dual-processor system, does this mean that only one thread of a Python > > program can run at a time, even when both CPUs are free, so that two > > seperate python interpreter processes are needed to take advantage of the > > two CPUs? > > Yes. It sounds like that is only true for code that does a lot of work in pure python (rather than with time-consuming, GIL-released C code). > > > What about when a Python thread is blocked for some other reason, such as > > while waiting for a file read - will that block other threads, or will the > > waiting thread definitely release the GIL and allow other threads to run? > > Depends on what it's blocked for. If it's blocked for I/O, then the GIL > is released and the other threads will run. I'm not sure what else it > would block for that might be a problem. But you could certainly CREATE > a problem if you tried... simplest way would be to write C code which > ran for a long time WITHOUT releasing the GIL. > > It would be much more difficult to block things through badly written > Python code, since after each bytecode the interpretor can switch to a > different thread. > > > If the GIL does block all threads in this manner, are there any plans to > > introduce more fine-grained locking to improve scalability, analagous to > > locking in the Linux kernel? > > No. The general consensus is that eliminating the GIL would be quite > difficult and that there's not really all that much to gain. (Most > casual users don't have multi-processor systems; serious users of this > sort probably use Numeric and/or put the tight loops into C anyhow.) > However, if you know someone who's good with this stuff and wants to > volunteer, I'm sure they wouldn't turn down working code (unless it > introduced other problems). > > -- Michael Chermside > Thanks for the information - it was definitely helpful. It looks like the system used by Python will work fine in all but a few situations (SMP system in which a lot of work is being done in Python itself, rather than in extension modules - or in badly written extensions which don't release the GIL before doing heavy work). Such situations can be dealt with by running two python processes - if a program really needs to do hard SMP work in python, then that is a small price to pay since I image the GIL simplifies a lot of things. I had been worried that the Python threading scheme would have caused more inefficiences (such as all threads stopping while a single thread was blocked for I/O). From fredrik at pythonware.com Thu Sep 5 02:41:12 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Sep 2002 06:41:12 GMT Subject: Why read-only nested scopes? References: Message-ID: David Eppstein wrote: > I'm sure there were good reasons for this decision, but it leads to ugly > workarounds like making each nonlocal variable into a list and assigning > to x[0] instead of x... when you find yourself doing that, it's a sure sign that you're no longer using python to write python code... From kkuroda at crl.ucsd.edu Sat Sep 7 01:51:30 2002 From: kkuroda at crl.ucsd.edu (Kow Kuroda) Date: Fri, 6 Sep 2002 22:51:30 -0700 Subject: Larry Wall's comment on python... In-Reply-To: Message-ID: On Friday, September 6, 2002, at 11:25 AM, Rod Stephenson wrote: snipped > "Python is cool to look at small bits of, but I think the "outline" > syntax breaks down with larger chunks of code. I'm with Aristotle on > the structure of discourse--a story should have a beginning, and > middle, and an end. So should blocks" snipped > Any comments? Well, Python code may look awkward --- if not awk-like --- if you don't know how to customize the tab width in your editor of choice. For example, vi and emacs indent by 8 characters by default, which I suspect is too wide for Python. Some code with deep nesting wouldn't look very nice with this default. Kow From fperez528 at yahoo.com Sat Sep 28 21:15:38 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sat, 28 Sep 2002 19:15:38 -0600 Subject: Lambdaizing Python Code References: Message-ID: Terry Hancock wrote: > > Not that I want to sign up for the style police or > anything, but ... > > Would respectfully like to point out that this could > as well be represented: > > def plur(word, number): > if number > 1: > word = word + 's' > return '%d %s' % (number, word) Well, not quite. You need 'if number !=1'. Otherwise this happens: In [36]: plur('cat',0) Out[36]: '0 cat' when you want: In [37]: plur0('cat',0) Out[37]: '0 cats' Anyway, I know that the above is equivalent to my lambda. I just like and often use lambda for quick, simple one-liners. The page originally referred to by the OP is a nightmare, and a funny example of abusing the lambda idea to death. But I don't mind them in simple cases, nor do I find them particularly unreadable. My original: plur=lambda s,n:'%s %s' % (n,s+('','s')[n!=1]) is fine for me. I see exactly what it does in one pass of my eyes. That's why _I_ like lambdas, and where I use them. But this is absolutely a matter of _personal_ preference. I'm a big defender of code clarity and readability over conciseness/cleverness (I'm an ex-perler, for good reason). It's just that in cases like the above, _I_ find the lambda form quicker to visualize mentally and overall simpler to my taste. Feel free to differ. Cheers, f. From james.kew at btinternet.com Tue Sep 3 17:31:33 2002 From: james.kew at btinternet.com (James Kew) Date: Tue, 3 Sep 2002 22:31:33 +0100 Subject: Another stylistic question: passing on arguments Message-ID: I have a class hierarchy in which the __init__ method must always have the same signature: the classes are all validators for various sorts of file, and by having them all expose the same initialisation and checking methods I can happily use them polymorphically. So far so good. However, sometimes in derived classes I need to initialise additional instance data at __init__ time. Up to now, I've happily overriden __init__ in derived classes, done my derived-class-specific stuff, and then delegated down to the base class __init__. Today, though, I wanted to add an extra argument to the __init__ method. The extra argument is only meaningful to the base class. So, I merrily added it to the base class __init__, blissfully forgot to modify the derived classes __init__s, ran it up, and of course it blew up at runtime as now some classes take three parameters on __init__ and some take two. Alex posted this a while ago, which I tucked away in my Inbox and which burrowed itself into my subconscious: http://groups.google.co.uk/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&selm=kNw%258.1 31213%24vm5.4318544%40news2.tin.it particularly his advice that: > In fact: when you wrap a library class, please CONSIDER accepting > arbitrary keyword parameters and passing them up to the superclass's > method that you're overriding-and-delegating-to. Just in case this > sort of thing happens tomorrow. Pretty please. My C/C++ background doesn't get me beyond varargs and default values as far as variable argument lists go, but I'm starting to see now the power of the positional and keyword argument * and ** syntax. I'm thinking that, had I written my derived class __init__s to catch and pass on additional arguments to the base class, my base-class-only change would have been transparent to derived classes. But is that just using a nifty Python tool because it's there? I suspect my "same __init__ signature everywhere" requirement would be better met by defining __init__ only in the base class and having it delegate out to an empty do_init method which derived classes can override. Um: I think I've just argued myself into the second solution. But I'll be playing with the *args, **kwargs syntax to add it to my toolbox; and I wanted to thank Alex for helping this newbie along the Python path. -- James Kew james.kew at btinternet.com From sholden at holdenweb.com Sat Sep 7 11:54:34 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 7 Sep 2002 11:54:34 -0400 Subject: Newbie's unsurmountable pb with IO stream trick References: <3D738EE2.3A8756D@engcorp.com> Message-ID: "Spendius" wrote ... > Peter Hansen wrote in message... > > OK I forgot to say I'm trying to develop my stuff under Windoze. > > > at once here. For one thing, why are you trying to use > > global variables at all when the original code was in > > Java, which doesn't have such things? > Do you mean Java doesn't have global variables or I'm mistaken ?!? > Java maintains a much stricter control over named access to non-local variables than Python does. If you get an "UnboundLocalError" this invaribaly means you are trying to use a variable which has not previously been bound to a value. At the very least this makes your program logic questionable. > > And what does not declaring variables have to do with > > the "global keyword issue" (whatever that is)? > I kept getting the error message > # UnboundLocalError: local variable 'cpt' referenced before assignment > where I really didn't expect to get such an error, and noticed in this > forum a lot of guys who know Python complain and talk themselves about > a "mess" (my 'cpt' var. is a counter incremented every time a method > gets called and I must sometimes re-initialize it to 0 inside an 'if' > statement: merely IMPOSSIBLE). > Not at all. The problem is that, if you are using a global variable, you must either initialize it before first use outside the functions that refer to it, or you must ensure that your first call to any such function will initialize it. This is simply sound programming practice. > > If you have an SQL database to access, why not use one of the > > standard DBAPI modules to get to it? You might be doing a lot > > of extra work when you don't have to. > And why not ? Anyway SQL*Plus contains plenty of built-in commands > that allow you to format your output how you like: I'd like to > keep that functionality. And let's say that I want to do that for > the sole purpose of learning the handling of IO streams in Python ! > Well, that's a bit like saying you want to learn how to handle irregular verbs in Esperanto, since the Java streams concept doesn't transliterate directly into Python. You are simply bringing too much of your mental Java baggage into the Python domain, where it will get in your way rather than helping you to solve problems. As far as inefficiency goes, sure, you may wish to solve your problem by interacting with an external SQL/Plus process even if there are better ways to go (and there are, as Peter mentioned). However, you should not expect Java-style solutions to be appropriate in the Python world, where we have popen() and friends to talk to external processes. > > If you're just learning Python, you've taken on a fairly > > complicated and large task right at the beginning. Why not > I admit it. But I did *exactly* the same with Java (writing > the app I'm trying to port) but never got stuck into problems > that blocking... > Don't try to port the Java, try to re-implement it in Python :-) regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From bokr at oz.net Mon Sep 9 10:50:53 2002 From: bokr at oz.net (Bengt Richter) Date: 9 Sep 2002 14:50:53 GMT Subject: python program to watch a file - example. References: Message-ID: On Sun, 8 Sep 2002 07:52:56 -0400, "Wayne R" wrote: >Sorry for the html, I forgot to turn it off (as I usually turn it off >as soon as I install a new system, forgot this time). > >The platform is Gentoo Linux, I am writing a piece of code for the >Twiggi project to patch in adduser support. > > >|-> > >I am trying to write a python program that will run as a deamon >and >|-> > >watch a file for data to arrive and then wake up and perform >duties >|-> on >|-> > >that data. I found ways to make a python program run as a >deamon >|-> but I >|-> > >am at a loss to find anything related to watching a file for data >so >|-> > >that it can then process the data. I didn't really want to do a >|-> sleep >|-> > >loop or something like, I am sure there is a better way. >|-> > > >|-> > >Any ideas or links to more info? >|-> > > >|-> > Don't annoy people you want help from, for starters. >|-> > What system are you targeting? (Outlook in the headers says you're >on >|-> windows >|-> > generating this abominable mix of actual message and useless >cruft). >|-> > >[Wayne R] > Sorry 'bout that. I don't very often express myself so testily, I hope. Anyway, if you are going to have to read new data periodically, you could just poll by doing it, I suppose. Unless you can control the writer or have access to something like Isaac describes, you might almost as well poll, ugly as that is. E.g., this seems to work, and I made it back off if there's errors due to permissions etc. The question would be if open/seek/tell/seek/read/close could cause an unacceptable error for some writer trying to get exclusive access or such. But it should be more robust than that, probably. If you control the source, it's a different ballgame, of course. Anyway, try this on Linux (mine is slackware 2.2.16 on an old p90 with Python 1.5.2 ;-) --< monf.py >-- #!/usr/bin/python def mon(fname, firstpos, period): import os, time, string last_len = firstpos next_errp = 1 ioerr_ctr = 0 while 1: f = None; data = '' try: f = open(fname) f.seek(0,2) # to EOF told = f.tell() if told < last_len: print 'File shortened from %s to %s. Starting from 0.'%( last_len, told ) last_len = 0 f.seek(last_len) data = f.read() ioerr_ctr = 0 # fresh sequence next_errp = 1 except IOError, e: ioerr_ctr = ioerr_ctr + 1 if ioerr_ctr >= next_errp: next_errp = next_errp*2 print '%s IOErrors: %s' % (ioerr_ctr, e) if f is not None: f.close() if len(data): print '----< %s bytes of new data >----\n%s' % ( len(data), `data` ) last_len = last_len + len(data) # use actually read length print '----< end, now totaling %s bytes >---' % last_len time.sleep(period) if __name__ == '__main__': import sys, string try: fname, firstpos, period = sys.argv[1:4] firstpos = int(firstpos) period = float(period) mon(fname, firstpos, period) except Exception, e: print '%s: %s' % (string.split(str(e.__class__),'.')[-1], e) print 'Usage monf.py filename firstpos(byte offset) period(seconds)' --------------- Running it locally via telnet from windows NT, and messing with the file directly on the Linux local terminal on the desk at my left: bokr at springbok:~/junk$ monf.py junk.txt 0 5 1 IOErrors: [Errno 2] No such file or directory: 'junk.txt' 2 IOErrors: [Errno 2] No such file or directory: 'junk.txt' 4 IOErrors: [Errno 2] No such file or directory: 'junk.txt' ----< 16 bytes of new data >---- 'A line of data.\012' ----< end, now totaling 16 bytes >--- ----< 22 bytes of new data >---- 'Another line of data.\012' ----< end, now totaling 38 bytes >--- File shortened from 38 to 18. Starting from 0. ----< 18 bytes of new data >---- 'Replaced totally.\012' ----< end, now totaling 18 bytes >--- KeyboardInterrupt: Usage monf.py filename firstpos(byte offset) period(seconds) bokr at springbok:~/junk$ Here I'll start monitoring at position 10, and then chmod it -+r from the other computer. bokr at springbok:~/junk$ monf.py junk.txt 10 5 ----< 8 bytes of new data >---- 'otally.\012' ----< end, now totaling 18 bytes >--- ----< 35 bytes of new data >---- 'Will now chmod it -r then +r again\012' ----< end, now totaling 53 bytes >--- 1 IOErrors: [Errno 13] Permission denied: 'junk.txt' 2 IOErrors: [Errno 13] Permission denied: 'junk.txt' 4 IOErrors: [Errno 13] Permission denied: 'junk.txt' ----< 38 bytes of new data >---- 'Ok now add some data to make it read.\012' ----< end, now totaling 91 bytes >--- KeyboardInterrupt: Usage monf.py filename firstpos(byte offset) period(seconds) bokr at springbok:~/junk$ (I hit Ctrl-C via telnet to kill it). This is just simple a hack, not tested beyond what you see. YMMV with your environment. You can mod to suit your task, hopefully. It would have been better to make a directory keyed by error strings so unique info wouldn't get supressed in the total. Plus a time-tagged log file would be better than a scrolling screen. Etc., etc., but it was an experiment. You could also wath the file size with int(string.split(os.popen('ls -ls' % fname).read())[4]) # or something like that ;-) but I imagine that's a fair bit more overhead than open/seek/tell. Of course it would also give you a chance to monitor other aspects of the file, or a directory. I guess if you had the privileges and the time, you could possibly create a special file system that you could symlink the file into and that would provide side effect hooks to block on and read event-driven special data. Maybe that's what sgi did? Regards, Bengt Richter From bdesth at nospam.free.fr Mon Sep 23 00:38:16 2002 From: bdesth at nospam.free.fr (laotseu) Date: Mon, 23 Sep 2002 00:38:16 -0400 Subject: Overriding all methods in a class References: Message-ID: <3D8E9AB8.9090000@nospam.free.fr> Joao Prado Maia wrote: > Hi, > > I have been looking for an answer for this question for a while, but > couldn't find anything that would work for what I want to do. > > I know that you can use __getattr__ to overload methods that your class > don't have, but what about overloading all methods, so I could in a way > 'intercept' calls to my methods and do something different if I wanted, is > that possible ? > > What I want to do basically is create a caching system for a specific > class, and have __getattr__ (or any other magic method name) handle the > decision to sue the cached return value or to actually call the method. > > Maybe it would be just easier to rename my current class to _Classname and > create a new Classname with just __getattr__. > > Any suggestions ? > > Cheers, > Joao > > from stupidQ import whyBlackMagic Well, if it's only about caching, why do you need to go into 'black magic' to implement it ? Couldn't you just handle the cache etc in the method itself ? laotseu From Oschler at earthlink.net Wed Sep 11 12:18:25 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Wed, 11 Sep 2002 16:18:25 GMT Subject: Any C++/Python sig members here? Message-ID: I joined the C++ sig for Python, to talk with others about BoostPython. I joined more than a day ago and got my subscription confirmation request from the sig server. I have not seen any messages yet, is it a very low traffic sig or something? thx From aglyportREMOvethispart at nospam.yahoo.com Wed Sep 4 15:09:57 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Wed, 04 Sep 2002 12:09:57 -0700 Subject: Memory fault - core dumped while compiling 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> Message-ID: <3D765A85.9080904@nospam.yahoo.com> Andrew Koenig wrote: > Anton> Any ideas? > > Looks like the same symptom I had. > > If you are using binutils 2.13, try going back to 2.12.1 and > see if that fixes the problem. > I don't think I use binutils: Wed Sep 4 11:37:53 PDT 2002 bongo:/u5/src/Python-2.2.1 $ as --version Assembler: (null) aline 1 : Warning: Illegal flag (-) - ignored aline 1 : Warning: Illegal flag (v) - ignored aline 1 : Warning: Illegal flag (e) - ignored aline 1 : Warning: Illegal flag (r) - ignored aline 1 : Warning: Illegal flag (s) - ignored aline 1 : Warning: Illegal flag (i) - ignored Nonexistent file Wed Sep 4 11:37:48 PDT 2002 bongo:/u5/src/Python-2.2.1 $ ar --version ar: ERROR: Illegal option -- - Usage: ar [-V?] -key[arg] [posname] afile [name ...] where key[arg] is one of the following: r[uabi], m[abi], d, q, t, p, x Can't think of other utils in binutils. From markus.vonehr at ipm.fhg.de Tue Sep 10 06:05:49 2002 From: markus.vonehr at ipm.fhg.de (Markus von Ehr) Date: Tue, 10 Sep 2002 12:05:49 +0200 Subject: compile error on SWIG file References: <3D7C55EE.D9278B1C@ipm.fhg.de> <3D7D97A6.A63610AF@ipm.fhg.de> Message-ID: <3D7DC3FD.815BF6E0@ipm.fhg.de> I put the file in the DLL directory. In a pyhon shell I typed: import mvelib Traceback (most recent call last): File "", line 1, in ? import mvelib SystemError: _PyImport_FixupExtension: module mvelib not loaded So python doesn't find the module, I guess? Any ideas? Markus Markus von Ehr schrieb: > > Hi Lyle, > > thanks for your answer and your efforts! > I changed everything to .cpp > The first error has gone > Now I have an error (translated from german): > > mvelib.obj: error LNK2001: unresolved external symbol initmvelib > build\temp.win32-2.1\Release\mvelib.lib : fatal error LNK1120: 1 > unresolved reference > LINK : fatal error LNK1141: Creation error of export file > error: command 'c:\Programme\VC98\BIN\link.exe' failed with exit status > 1141 > > Markus > > Markus von Ehr schrieb: > > > > Hi, > > > > compiling my c-file generated from SWIG > > (swig -c -python -o mvelib.c mvelib.i) > > with a setup-file, I receive the error: > > > > c:\programme\vc98\include\eh.h(32) : fatal error C1189: #Error: "eh.h > > is only for C++!" > > > > Anybody knows what I have to change??? > > > > Thanks Markus > > > > **************************** > > setup.py > > **************************** > > from distutils.core import setup, Extension > > > > setup (name = "mvelib", > > version = "1.0", > > maintainer = "Markus von Ehr", > > maintainer_email = "markus.vonehr at ipm.fhg.de", > > description = "mvelib Python module", > > > > ext_modules = [Extension('mvelib',sources=['mvelib.c'])] > > ) From loewis at informatik.hu-berlin.de Mon Sep 23 07:29:25 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 23 Sep 2002 13:29:25 +0200 Subject: UpToDate SOAP-module ?? References: Message-ID: "Thomas Weholt" <2002 at weholt.org> writes: > Anyway, if you want to provide more information about why I safely can > ignore SOAP feel free. It would make my project a bit less complicated so > I'd be glad to skip it. :-) It all depends on what your users want to use; and I'm talking about *real* users here, not people that just have wishlists, but don't seriously plan to use your service. I think that clients will prefer whatever makes development of their applications simplest. Which technology is simplest depends on various aspects, such as the complexity of the interface, the target language for developing clients, and any libraries that client developers may have. If the interface is a simple one, clients might be happy with XML-RPC, except for the result-parsing part (if they use Python or Perl, they might be happy with XML-RPC even for results). If the interface is complex and out-of-the-box interoperability is important for unknown clients, I'd prefer CORBA over SOAP. If you are not only developing the server, but also the client, I'd prefer CORBA over SOAP also. About the only scenario where offering SOAP might be needed is that people want to develop clients with C#, in .NET, since there are no .NET ORBs available, yet. Regards, Martin From timh at zute.net Wed Sep 25 09:30:11 2002 From: timh at zute.net (Tim Hoffman) Date: Wed, 25 Sep 2002 21:30:11 +0800 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> Message-ID: <3D91BA63.7090203@zute.net> > > There ought to be severe penalties for idiots that use floating point > dollars for financial applications. If forced to use floating point > (e.g. because customer demands BASIC), then keep money amounts in > whole pennies (or whatever the smallest currency unit for the country > is), and divide by 100 (or whatever) for printing only (or just add the > decimal point yourself). > In many circumstances this is exactly what you can't do. The minute you need to calculate percentages you will get in to the things like .0001254 of a cent, no matter what is you smallest unit of currency. I worked for a insurance company (using Business Basic) many years ago on MAI and Prime gear, and we did everything as floats with 14 places after the decimal point,and only rounded when a human needed to see a number, and then used standard accounting practices for rounding, Rgds Tim From merman at snafu.de Sat Sep 14 16:13:06 2002 From: merman at snafu.de (T. Kaufmann) Date: Sat, 14 Sep 2002 22:13:06 +0200 Subject: newbie-question: abstract classes Message-ID: <3D839852.2060405@snafu.de> Hi everybody, I have a problem: I want to create an abstract class but it doesn't work. What' s wrong here? class Abstract: def __init__(self): return def method(self): raise NotImplementedError class Concrete: def __init__(self): Abstract.__init__(self) return def method(self): print "\n ... in Concrete!\n" if __name__ == '__main__': #a = Abstract() #a.method() c = Concrete() c.method() thanx for help o-o thomas From jfaris at sbcglobal.net Thu Sep 12 10:21:45 2002 From: jfaris at sbcglobal.net (Jordan Faris) Date: Thu, 12 Sep 2002 07:21:45 -0700 Subject: Best tutorial Message-ID: <00c901c25a67$b9dcecb0$e780cf3f@leader1> Of the several fine tutorials on the Web, which one would be the most direct in getting a novice up to snuff on Python? Thanks....... From jacob at boris.cd.chalmers.se.cd.chalmers.se Wed Sep 25 10:03:32 2002 From: jacob at boris.cd.chalmers.se.cd.chalmers.se (Jacob Hallen) Date: 25 Sep 2002 14:03:32 GMT Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> Message-ID: In article <3D8E6353.7030303 at something.invalid>, Greg Ewing wrote: >Courageous wrote: > >> One should use spaces >> and not tabs in Python code. Otherwise, any python file where >> tabs and spaces are mixed is also a choice of which indentation >> level other viewers of the code MUST use in their editors. > > >If you use spaces only, you're also choosing how other >people will see it in their editors (unless they're >willing to use a tool to re-indent it). > >Using *tabs* only is the only way to get truly >preference-independent indentation. Exactly the point! My code is my work of art. Why should anybody be allowed to change it? We don't allow people to go painting moustaches on the Mona-Lisa, do we? Jacob Hall?n -- From LogiplexSoftware at earthlink.net Wed Sep 11 17:31:52 2002 From: LogiplexSoftware at earthlink.net (Cliff Wells) Date: 11 Sep 2002 14:31:52 -0700 Subject: deleting the first and the last character of a string In-Reply-To: <1031777408.17116.65.camel@software1.logiplex.internal> References: <20020911105818.GC2054@partagas.as.de.cw.net> <200209111246.03080.shalehperry@attbi.com> <1031777408.17116.65.camel@software1.logiplex.internal> Message-ID: <1031779912.17116.77.camel@software1.logiplex.internal> On Wed, 2002-09-11 at 13:50, Cliff Wells wrote: > >>> def chopd(s, d): > ... s = s.strip() > ... return s[s[0] == d : {0:len(s), 1:-1}[s[-1] == d]] Er, slightly better: return s[s[0] == d : (len(s), -1)[s[-1] == d]] (Note to self: dictionaries aren't answer to everything...) -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 x308 (800) 735-0555 x308 From pereira at cis.upenn.edu Sat Sep 21 22:21:12 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Sat, 21 Sep 2002 22:21:12 -0400 Subject: general thoughts References: Message-ID: On 9/20/02 9:40 AM, in article azFi9.163782$5r1.6708151 at bin5.nnrp.aus1.giganews.com, "Terry Reedy" wrote: > > "Benjamin" wrote in message > news:ifjloug0dkla5o3lvli464mmou5mbh47d5 at 4ax.com... >> i've been learning python not for becoming a programmer >> (i study modern languages at the university), but for having >> fun. my personal motto is "i want to know how it works". > ['but I'm getting bored'] > > Perhaps you should look into some area of computer-aided language > analysis and processing. In that vein, some suggestions for further reading: http://nltk.sf.net http://www.cis.upenn.edu/~cis530/ http://www.norvig.com/python/python.html -- F From duduca007 at yahoo.com Tue Sep 24 14:00:22 2002 From: duduca007 at yahoo.com (Carlos Moreira) Date: Tue, 24 Sep 2002 11:00:22 -0700 (PDT) Subject: Pyro Error. In-Reply-To: <20020924174641.40449.qmail@web11403.mail.yahoo.com> Message-ID: <20020924180022.33444.qmail@web11408.mail.yahoo.com> Oh right, oh right....I found the problem (a silly problem :) ) and fix it. I need more coffe... []'s Cadu Moreira KaduSoft President ------------------------ [...Please god, put down the dollar ( U$ 1 == R$ 3.57 )...] --- Carlos Moreira wrote: > Testing the simplest example of docs/8-example.html, > on client side, generate an error message: > > Traceback (most recent call last): > File "./client.py", line 10, in ? > print jokes.joke("Irmen") > File > "/home/pgs/carlos/python/Python-2.2/lib/python2.2/site-packages/Pyro/core.py", > line 315, in __invokePYRO__ > self.adapter.bindToURI(self.URI) > File > "/home/pgs/carlos/python/Python-2.2/lib/python2.2/site-packages/Pyro/protocol.py", > line 224, in bindToURI > raise ProtocolError('connection failed') > Pyro.errors.ProtocolError: connection failed > > Where I must seek for inconsistences? Pyro.conf? > > []'s > > Cadu Moreira > KaduSoft President > -------------------------- > [......] > > __________________________________________________ > Do you Yahoo!? > New DSL Internet Access from SBC & Yahoo! > http://sbc.yahoo.com > > -- > http://mail.python.org/mailman/listinfo/python-list ===== "Liberdade, Igualdade, Fraternidade e Foda-se" -- Millor Fernandes __________________________________________________ Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! http://sbc.yahoo.com From sismex01 at hebmex.com Mon Sep 9 10:26:47 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Mon, 9 Sep 2002 09:26:47 -0500 Subject: xml.minidom is stripping out my CRLF's in attrib values!! Message-ID: Probably not sripped, but normalized: for example, your original string: >>> s = "spotted\x0Awith black and white" becomes the normalized string: >>> s = "spotted with black and white" Is something like this happening? If it is, then it's the correct behaviour, according to the XML standard: all text should be normalized, except if it's in a CDATA block. HTH -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From gmuller at worldonline.nl Tue Sep 17 15:14:36 2002 From: gmuller at worldonline.nl (GerritM) Date: Tue, 17 Sep 2002 21:14:36 +0200 Subject: Will "Python in a Nutshell" be too short? References: Message-ID: "Hamish Lawson" schreef in bericht news:mailman.1032288261.15607.python-list at python.org... > O'Reilly doesn't yet list the forthcoming "Python in a Nutshell" by Alex > Martelli, but according to Amazon.com's page for the book, it will have 400 > pages. Is that indeed the plan? <...snip...> > By comparison, O'Reilly's "Perl in a Nutshell" is 800 pages and has the > following chapters <...snip...> > > Hamish Lawson By comparison "Java in a nutshell" is 600 pages and on top of that "Java examples in a nutshell" is another 400 pages. By the way I liked the set up of this second book. It is close to the cookbook idea. (The Python Cookbook is GREAT!). regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From pcarey at lexmark.com Fri Sep 20 12:17:54 2002 From: pcarey at lexmark.com (pcarey at lexmark.com) Date: Fri, 20 Sep 2002 12:17:54 -0400 Subject: Newbie questions: write permission, interpreter minimizing Message-ID: Win2K, Python2.2 Hello list. I'm relatively new to Python. When I want to test for write permissions (on Win2K), I use try: except: clauses, something like this: try: os.mkdir("X:\\anydir") except OSError (e,s): print s os.rmdir("X:\\anydir") Is there an easier way? I tried os.access("X:\\anydir", W_OK), but it always returns 1, so I guess I am misunderstanding that. Also, (and forgive me if I betray woeful ignorance)... I use PythonCardPrototype to make UI's. When launching these apps (double-clicking), the interpreter launches (as it should) and remains in the background (as it should)... but is there any way to automatically minimize the interpreter? Thank you, Pete From padraig at linux.ie Sun Sep 15 15:50:04 2002 From: padraig at linux.ie (Padraig Brady) Date: Sun, 15 Sep 2002 19:50:04 GMT Subject: regular expression for space seperated quoted string References: <%jHf9.3635$cP3.7161@news.iol.ie> Message-ID: <3D84E4B4.4040305@linux.ie> Padraig Brady wrote: > Padraig Brady wrote: > >> Eric Brunel wrote: >> >>> Padraig Brady wrote: >>> >>> >>>> Hi, I'm trying to split a string that is seperated >>>> by spaces and also contains double quoted words which >>>> can contain spaces: >>> >>> >> >> [snip] >> >>> What about: >>> >>>>>> p = r'[^ \t\n\v\f"]+|"[^"]*"' >>>>>> re.findall(p, '1 2 3') >>>>> >>>>> >> >> FYI, I'm using the following: >> >> import fileinput, re >> for line in fileinput.input(): >> #split fields >> fields = re.findall('[^ "]+|"[^"]+"', line[:-1]) >> #remove quotes >> fields = map(lambda field: field.replace('"', ''), listLine) >> >> thanks again, >> P?draig. >> > > Just in case it's useful I might as well make it correct and more > efficient: > > import fileinput, re > reFieldSplitter = re.compile('[^ "]+|"[^"]+"') > for line in fileinput.input(): > #split fields > fields = reFieldSplitter.findall(line[:-1]) > #remove quotes > fields = map(lambda field: field.replace('"', ''), fields) Just to be more complete the compilation of the regular expression above gave a 1.3% speedup. However changing the map(lambda...) to a list comprehension gives another 4% speedup. import fileinput, re reFieldSplitter = re.compile('[^ "]+|"[^"]+"') for line in fileinput.input(): #split fields fields = reFieldSplitter.findall(line[:-1]) #remove quotes fields = [field.replace('"', '') for field in fields)] P?draig. From syver-en+usenet at online.no Mon Sep 16 05:12:57 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Mon, 16 Sep 2002 09:12:57 GMT Subject: basic question References: Message-ID: s3v3n3v3s73 at yahoo.com (7) writes: > I am using Pythonwin. How can I always make sure when I make a change > to a script and save it, that when I go to run it, that I run the > changed version. I know there is a very basic answer, this has been > getting to me. reload(modulename) should do the trick -- Vennlig hilsen Syver Enstad From jingguoming at yahoo.com.cn Wed Sep 11 22:22:55 2002 From: jingguoming at yahoo.com.cn (jgm2163) Date: 11 Sep 2002 19:22:55 -0700 Subject: how can i make a binary executable program with a python2's script Message-ID: os:redhat7.2 python:2.1 how can i make a binary executable program with a python2's script From neil.padgen at mon.bbc.co.uk Fri Sep 6 05:06:50 2002 From: neil.padgen at mon.bbc.co.uk (Neil Padgen) Date: Fri, 06 Sep 2002 09:06:50 +0000 Subject: How to force built-in commands over imported. References: Message-ID: Delaney, Timothy wrote: > [ unit testing framework snipped] > > which allows me to perform each set of tests independently, and run them > all through a single command. Even so, it should probably specify the > actual names of the test cases in case there is a conflict somewhere, but > that would fail to pick up any new test cases. There's a fabulous regression testing script in Dive Into Python which takes care of this for you, by running all tests in the current (or given) directory which are in modules called *test.py. http://www.diveintopython.org/regression_divein.html I've modified this to work in the current directory and below, but haven't been able to test it thoroughly in anger yet. (I'm not yet confident enough at writing tests...) -- Neil From sismex01 at hebmex.com Wed Sep 18 11:48:50 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 18 Sep 2002 10:48:50 -0500 Subject: isFloat: Without Exception-Handling Message-ID: > > Is there a way to write the following > method without using exceptions? > > def isFloat(string): > is_float=1 > try: > float(string) > except: > is_float=0 > return is_float > > print isFloat("asdf") # --> 0 > print isFloat("0.1") # --> 1 > > Somehow I don't like to catch exceptions. Maybe > that's because my first language was C. > > thomas > Catching exceptions in Python is quicker than in other languages, because of internal implementation issues. So, you could rewrite the following like this: def isFloat(S): R = 0 try: float(S) R = 1 finally: return R A bit shorter, and more concise, since using "except:" is bad form (you're not specifying which exception you're interested in catching), and "finally:" says what you really meant: "In the end, return R, no matter what happens". HTH -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From bfarwick at juno.com Sun Sep 22 06:42:06 2002 From: bfarwick at juno.com (brrrent) Date: 22 Sep 2002 03:42:06 -0700 Subject: module name errors (trying to import curses functions from modules as needed) Message-ID: <1b6dca50.0209220242.d9afc12@posting.google.com> I use some very simple curses functions with Python 1.5.2. I don't have a problem with curses per se. I use the old top level setup code shown in Andrew Kuchling's early curses HOWTO. It works well. But ... I want to keep all my various curses input and output functions in separate modules, calling them when needed, instead of defining them all at the top of my main program. If I include top level curses setup code in each module, they import with no problem. I call them with the desired parameters and they do their job. The real problem is that when a function imported with one module finishes, so does curses (albeit briefly). Then of course the screen flashes annoyingly (very briefly) before the next module once again reactivates curses. If I try to omit the curses top level setup in the modules and put it in my main program, of course Python complains about things such as "stdscr" name errors. This makes sense, but I don't know how to work around it. I can of course finish my program, putting up with the brief screen flashes, and when finished, pull all my function definitions into my main program. If there's a better way, I would be grateful for advice on same. Sincerely, b From at_news at pontos.net Sat Sep 21 07:46:17 2002 From: at_news at pontos.net (ilias) Date: Sat, 21 Sep 2002 14:46:17 +0300 Subject: LISP - [SPECS ERR] - Backquote - please confirm. - [#V0.3] References: Message-ID: I've found a simple bug in the ANSI Common Lisp specification. At least i think so. I've published this in comp.lang.lisp, and asked for validation. The bug is very simple. But i got no responses that leads to a confirmation. I had this again. When i was claiming that: ---------------------------------------------------------------- () can be changed to [] with 2 lines of ANSI Common Lisp Code An ANSI Conforming Common Lisp implementation *must* execute: (set-syntax-from-char #\] #\) ) ; => T (set-syntax-from-char #\[ #\( ) ; => T [+ 3 2] ; => 5 http://groups.google.com/groups?selm=alot2c$pkv$1 at usenet.otenet.gr (LispWorks *does*, Franz Allegro *does not*, Corman Lisp *does not*, other versions: don't know, i got no feedback ! ---------------------------------------------------------------- But this case is much simpler. Interested in "The 'Savages' of C.L.L." ? Interested in LISP? Interested in Software Engeneering? Here's a showcase. The Medium 'Public Newsgroups'. Used for quick 'Language Evolution'. ============================================================== -------------------------------------------------------------------- NESTED BACKQUOTE -------------------------------------------------------------------- The [online-version of the] standard-document states: http://www.lispworks.com/reference/HyperSpec/Body/02_df.htm "[...] If the backquote syntax is nested, the innermost backquoted form should be expanded first. This means that if several commas occur in a row, the leftmost one belongs to the innermost backquote.[...]" => "the *innermost* backquoted form *should be* expanded first" This definition is wrong. ------------------------------------------------------------------------ Testing with implementations: Allegro: (setq d 1 c 'd b 'c a 'b ) `(,a `(,b ,,c)) ; => (B (EXCL::BQ-LIST B D)) ;;; which is same as: (B `(,B ,D)) LispWorks: `(,a `(,b ,,c)) ; => (B (SYSTEM::BQ-LIST B D)) ;;; which is same as: (B `(,B ,D)) We see in the processing of both implementations: - The *outermost* backquoted form is expanded first => direct contradiction to the specification - The *innermost* backquoted form is processed *partially* by the outermost backquote to evaluate the ,,c => ,D. This confirms: The definition of nested backquote is wrong. ------------------------------------------------------------------------ one could say now: The specification is correct. The implementors are wrong. -------------------------------------------------------------------- The 'natural' flow of things will help out. Naturally (as given by reading in the stream) the outermost backquote is expanded first. The Lisp-Reader cannot preview more than *one* char. Thus it is impossible to detect the existence of the innermost quote to avoid evaluation of the outermost backquote. -------------------------------------------------------------------- (setq d 1 c 'd b 'c a 'b ) `(,a `(,b ,,c)) ; => (b `(c ,d)) |_|__|| |_|________| the only , prior to a will be processed from the outermost ` the only , prior to b will be processed from the innermost ` the left , prior to c will be processed from the innermost ` the right , prior to c will be processed from the outermost ` -------------------------------------------------------------------- The author meant probably this: If the backquote syntax is nested, the innermost backquoted form should be *served*[not expanded] first [with a comma]. This means that if several commas occur in a row, the leftmost one belongs to the innermost backquote [and so on]. in any case: http://www.lispworks.com/reference/HyperSpec/Body/02_df.htm "[...] If the backquote syntax is nested, the innermost backquoted form should be expanded first.[...]" is wrong. -------------------------------------------------------------------- 'Looking around' i follow an suggested link in the specs: http://www.lispworks.com/reference/HyperSpec/Body/02_dfa.htm "[...] Implementors who have no particular reason to make one choice or another might wish to refer to IEEE Standard for the Scheme Programming Language,[...]" http://www.cs.indiana.edu/scheme-repository/doc.standards.html nothing found there, but i reached finally this point: http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-7.html#%_sec_4.2.6 "[...] Quasiquote forms may be nested. Substitutions are made only for unquoted components appearing at the same nesting level as the outermost backquote. The nesting level increases by one inside each successive quasiquotation, and decreases by one inside each unquotation. `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f) ===> (a `(b ,(+ 1 2) ,(foo 4 d) e) f) (let ((name1 'x) (name2 'y)) `(a `(b ,,name1 ,',name2 d) e)) ===> (a `(b ,x ,'y d) e) [...] " Which confirms what already is obvious: The ANSI Common Lisp specification about nested Backquote is wrong. My main interest now is: I've lost *many* time due to this wrong specification, which ruins my understanding process for days. I've invested *many* time to find out whats happened and to write everything down, so other newcomers to lisp (i'm a lisp-novice) don't run into the same problem. Now look at the behaviour of comp.lang.lisp. And explain me please: - Is this a common behaviour of Lisp people? - Or is this only the behaviour of the few people online in cll? - are other languages-lovers like this people? i mean, declaring the specs as a religion which has no errors? Believe - don't doubt. Are this people not able to say: - Yes, it's maybe an bug. - Yes, it's an bug. - Ok, we've a bug in the specs, so what? - Ok, we've a bug in the specs, lets look what to do. Simply to raise the image and the quality of comp.lang.lisp. And of Common Lisp. I've a strange feeling, that the nature of Common Lisp is like the nature oth the people in c.l.l. Talking, talking, talking. And silence, when it is time to talk. - I'm a lisp-novice. Be happy. From peter at engcorp.com Tue Sep 10 08:35:43 2002 From: peter at engcorp.com (Peter Hansen) Date: Tue, 10 Sep 2002 08:35:43 -0400 Subject: Windows/DOS: double clicking a .py file References: <3d7d6f26@news.sentex.net> Message-ID: <3d7de70a$1@news.sentex.net> Just wrote: > Not only that, but I want to only keep the window open when an exception > occurred. > > But thanks for all the input! Just, maybe your users would be happy to enable an option that would just *mail* you the exception traceback when a problem occurs, rather than having to read it in an ugly DOS window and perhaps make mistakes in transcribing it when they tell you about it. There was at least one recent thread which showed examples of how to do this. If you can't dig them up (might be in the Cookbook too) ask and someone can find a link or repost. If these are internal users, that is certainly a better option than just printing the traceback. -Peter From tjreedy at udel.edu Fri Sep 27 23:25:21 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 28 Sep 2002 03:25:21 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <7nHk9.172208$pX1.6117207@news2.tin.it> Message-ID: "Fernando P?rez" wrote in message news:an325r$hir$1 at peabody.colorado.edu... > Mike Rovner wrote: > > > > > "Terry Reedy" wrote in message > > news:t_3l9.334924$AR1.14880141 at bin2.nnrp.aus1.giganews.com... > >> na=1; np=3; nl=1; ng=0 > >> print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\ > >> (na, na!=1 and 's' or '', np, np!=1 and 's' or '', nl, nl!=1 and 's' > >> or '', ng, ng!=1 and 's' or '') > >> > >> Found: 1 apple, 3 plums, 1 lemon, and 0 grapes. > > 4. Try: > > use_s=('','s') > > print "Found: %d apple%s, %d plum%s, %d lemon%s, and %d grape%s." %\ > > (na, use_s[na!=1], np, use_s[np!=1], nl, use_s[nl!=1], ng, use_s[ng!=1]) Of course. > Why not just a simple function? > > In [23]: plur=lambda s,n:'%s %s' % (n,s+('','s')[n!=1]) > In [27]: na=1; np=3; nl=1; ng=0 > In [28]: print "Found %s, %s, %s, %s" % (plur('apple',na),plur('plum',np), > ....: plur('lemon',nl),plur('grape',ng)) > Found 1 apple, 3 plums, 1 lemon, 0 grapes Nice. I like both of these better than my version. Thanks. Terry J. Reedy From syver-en+usenet at online.no Tue Sep 17 07:01:57 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Tue, 17 Sep 2002 11:01:57 GMT Subject: don't understand error message References: Message-ID: Manuel Hendel writes: > But I already got a new one. > > [....] > if domainfield in domain: > domainlines.append(line) > [....] > > This should work if the domainfield and domain got the following > values, shouldn't it? > > domainfield = 1234.ab.cdef.de > damain = 1234.ab.cdef.de No I don't think so. It will only work when the conditions are as described in the error message. I think it would be wise to assume that your code is at fault first, instead of assuming that the error is elsewhere. Assume that you've just made a simple mistake first, and only after having ruled that out, progress to more and more unlikely error sources, usually ending with blaming the compiler or interpreter, which should be the last bug source that you consider. In my understanding *in* works as follows. It takes an element as the left argument and a collection as the right element. I is therefore quite natural that you have to have a single character on the left and a string on the right. > > But I get this error message: > > TypeError: 'in ' requires character as left operand Yes, read the error message. It tells you that what you did is invalid, and it also tells you what you have to do if you are going to use this construct. I think what you want is closer to this: if domain.find(domainfield) != -1: # do stuff >From the python documentation: find(sub[, start[, end]]) Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end). Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. -- Vennlig hilsen Syver Enstad From tjreedy at udel.edu Thu Sep 5 00:48:41 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 05 Sep 2002 04:48:41 GMT Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> Message-ID: "Naveed Iqbal" wrote in message news:6afb9d2c.0209041044.43c5f5f1 at posting.google.com... > I have to print to a standard printer. I take the data from the > keyboard and print it using the printer. Please help me....my job > depends on this!!!! On *nix or dos/windows, you open the printer port as if it were a file, just like other ports and devices. On *nix, this maybe be something like '/dev/lpt' or a the numbered serial or parallel port that your printer is attached to. On Dos and my win98 machine, this does the trick: >>> p=file('LPT1:','w') >>> p.write('Test Line\n\f') >>> p.flush() # p.close() also flushes and out come a sheet with 'Test Line' printed. Note that \f is formfeed char; without it, nothing is printed on page printers (*jets, etc.). Terry J. Reedy From sadams123 at optushome.com.au Wed Sep 4 15:03:43 2002 From: sadams123 at optushome.com.au (Steven) Date: Thu, 5 Sep 2002 05:03:43 +1000 Subject: How do i print to a printer using python? References: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> Message-ID: <3d765914$0$26216$afc38c87@news.optusnet.com.au> "Naveed Iqbal" wrote in message news:6afb9d2c.0209041044.43c5f5f1 at posting.google.com... > I have to print to a standard printer. I take the data from the > keyboard and print it using the printer. Please help me....my job > depends on this!!!! What operating system are you using? you'll need o post a few more details. Steven From josef.buergi at bluewin.ch Sun Sep 29 05:21:36 2002 From: josef.buergi at bluewin.ch (Josef Bürgi) Date: Sun, 29 Sep 2002 10:21:36 +0100 Subject: Python and GUI question Message-ID: <3d96b808_3@news.bluewin.ch> Dear NG I designed a CMS using mySQL and PHP. Now I like to write an administrativ GUI Client Tool using Python. So I bought a few books about it, saying that there is more then one GUI interface (Tk, Qt, xvWindow). So can anyone tell me which one you use and why ? And how do you Design GUI interfaces (IDE) ? Best wishes fromSwitzerland Joe From aleax at aleax.it Fri Sep 20 10:10:35 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 14:10:35 GMT Subject: Python sequences reference - problem? References: <3D8B0F86.9000600@one.net> Message-ID: Michael Schneider wrote: > I also like python. > > When doing pure math I have been using J for prototyping algorithms. > J is basically APL without the special symbols . Brings me back a LONG time -- APL and APL2 were all the rage in IBM Research back in the '80s, which is where I first worked. I also used APL for the prototype of my master thesis in the '70s (later completed it in Vax/VMS Fortran and Assembler -- and, for the specific job that program was doing [compiling AHPL code into a gate-level circuit design], Fortran with a bit of Assembler turned out to be much more productive than APL, too:). However, I just can't get into J: what used to be "at first weird, soon learned and readable" symbols have mutated into "totally obscure forever" symbols (in my opinion). I still *THINK* in APL for some problems: I want an `expand` primitive, don't really care about its syntax or how it's spelled, a `reduce` one too, etc, etc... but J's cconcrete syntax is just too weird for me. Alex From robin at jessikat.fsnet.co.uk Tue Sep 3 18:17:43 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Tue, 3 Sep 2002 23:17:43 +0100 Subject: [Q] win32com/Excel References: Message-ID: In article , Mike Brenner writes >Hi Robin, > >That was great, but most importantly, it was FAST! > >Would it be possible to tell how you did that so quickly? Is there a reference >that would tell me that x1LastCell is in constants? or that you put the >activeWindow in front of ActiveCell? OK let me tell you how I did this. I'm getting old so my memory is fairly poor these days so I rely on the source of the interface file generated by win32com\client\makepy.py. I scrolled down and built the interface for my excel which appeared in the list as 'Microsoft Excel 9.0 Object Library (1.3)'. The I edited the generated file in win32com\gen_py it was called 00020813-0000-0000-C000-000000000046x0x1x3.py derived from the GUID I guess. Scanning I see the xlLastCell constant in a class called constants. I don't normally use these constants so I checked what happens to constants; right at the bottom I see win32com.client.constants.__dicts__.append(constants.__dict__) ie the constants are added into the win32com.client.constants thing's dict so should appear as attributes of win32com.client.constants. Then I looked for something to hang this constant on, seems like a range has this method. The vb seemed to like using ActiveCell as the start point and scanning for that method reveals a method in a class called Window. As for the book, sheet and window things I seem to remember them from some previous era when I did a lot of excel (horror show). As for the nitty gritty details of how to turn off various bits of interactive code I can only recommend detailed reading of any available documentation. My boss is Andy Robinson co-author with Marc Hammond of the win32 python book so from the python side I know that's a very good start. On the other side I recommend asking an expert or consulting the appropriate newsgroup. Writing an application in excel obviously requires answers to your questions. A quick check reveals that there is a way to stop checking for viruses in macros (at least in my excel) that might be the way to go. Googling with 'microsoft project option' reveals a lot of hits so perhaps that might be a good source. > >Do you know of any references as to how to do it in Microsoft Project whose >object model seems much less documented than Excel's is? > >I know how to use Project Explorer in the Visual Basic Editor inside the >Microsoft OLE applications like Microsoft Project, and I know how to get the >Python list of objects using makepy. However, that does not seem to be enough to >figure out many questions in Microsoft Project (and even some questions in >Microsoft Excel). > >What would be really nice is a document that explains what each object in the >list is used for. For example, when opening a Microsoft Project file, it asks a >bunch of questions like: are macros okay? should I open related files? should I >save the changes I think you made to the previous file? > >I would like to learn how to cancel out those messages when I open a Microsoft >Project file from Python. What book or application do you recommend I purchase? >Or what file can I download to learn how to do these things? > >Thanks, >Mike > > > >>I would like to emulate this Visual Basic statement from Python, using >>Com: >> >> Range(Range("A1"), ActiveCell.SpecialCells(xlLastCell)).Select >> >>this statement selects the active worksheet (which is, incidentally, >>not similar to UsedRange). >> >>any clues? >> >>thank you, >from win32com.client import Dispatch >from win32com.client import constants >xl = Dispatch("Excel.Application") >AB = xl.ActiveWorkbook >AS = AB.ActiveSheet >AW = xl.ActiveWindow >R = AS.Range('A1',AW.ActiveCell.SpecialCells(constants.xlLastCell)) >print AB.Name, AS.Name, R -- Robin Becker From henk.derudder at nospam.sciatl.com Thu Sep 26 07:37:55 2002 From: henk.derudder at nospam.sciatl.com (henk.derudder at nospam.sciatl.com) Date: Thu, 26 Sep 2002 11:37:55 GMT Subject: getting system time Message-ID: <3d92ec67.596514453@news.skynet.be> Hi, I wondered whether it is possible (and if possible, how) to monitor changes in the system time on a Windows machine. Suppose one resets the clock: where is this info stored (registry,file). Which format? Can I get this using Python? thanks, Henk From roffe at aqualene.uio.no Sat Sep 28 09:45:42 2002 From: roffe at aqualene.uio.no (Rolf Marvin Bøe Lindgren) Date: Sat, 28 Sep 2002 15:45:42 +0200 Subject: [Mac] Editor on Macintosh? References: <1fj7za2.1erbqps1uvzpj8N%news@agapow.net> Message-ID: [Paul-Michael Agapow] | .) I found it the best editor for Python on | the Macintosh, having never been really happy with the alternatives. GNU Emacs is available on the Mac. there's a carbonized version available, no need for X11. -- Rolf Lindgren http://www.roffe.com/ roffe at tag.uio.no From robin at alldunn.NOSPAM.com Thu Sep 19 22:24:39 2002 From: robin at alldunn.NOSPAM.com (Robin Dunn) Date: Fri, 20 Sep 2002 02:24:39 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <6_Ph9.479711$q53.16315681@twister.austin.rr.com> Message-ID: Lee Gray wrote: > > For a newbie, what's easier, Tk or wxWindows? > I've found that it depends on how your brain is wired. There are some people who love Tkinter because it just fits the way they think but just can't understand wxPython no matter how much they try. There are other folks where the opposite is true, I am one of them and that is the main reason wxPython was created. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From jmiller at stsci.edu Mon Sep 9 14:01:08 2002 From: jmiller at stsci.edu (Todd Miller) Date: Mon, 09 Sep 2002 14:01:08 -0400 Subject: Can't exponentiate zero in NumPy References: Message-ID: <3D7CE1E4.3000600@stsci.edu> Rick Muller wrote: > I found out more about this problem, and I'm still hoping that someone > can suggest a good fix. > > The problem comes when I take a power of a NumPy array that has very > small values in it: > > >>> from Numeric import * > >>> a = zeros(3,Float) > >>> a**2 > array([0., 0., 0.]) > >>> a[1] = 1.e-310 > >>> a**2 > Traceback (most recent call last): > File "", line 1, in ? > OverflowError: math range error > > This crashes on Linux, but not on Mac OS X. > > Is this a bug or a feature? > > If it's a feature (which it might be), can someone offer a one-line > workaround? What I would like to do is set everything below a small > value (say 1.e-16) to zero. Obviously, > >>> for i in range(len(a)): if a[i] < 1.e-16: a[i] = 0 > or something like it should work, but it will also be slow, and I was > hoping that one of the Numeric UFuncs might do the same thing more > effectively. > > Thanks in advance for any help anyone can offer. > > Rick > I think what you're looking for is "where". You use it like: >>> b = where( abs(a) < 1.e-16, 0, a) Which means "where the absolute value of a is less than 1.e-16, use 0, else use a". The "<" operator only works like this for Python-2.1 and up; prior to that you have to substitute a "lessthan" function call. Todd From andrew.thompson at ashecastle.com Mon Sep 23 13:15:37 2002 From: andrew.thompson at ashecastle.com (Andrew Thompson) Date: Mon, 23 Sep 2002 18:15:37 +0100 Subject: e vs exp()? / financial applications In-Reply-To: Message-ID: <011a01c26324$d6300940$4802a8c0@blair> One must be aware of the representational issues and accuracy of arithmetic within a datatype when using numerical types. This is not so much a Python issue as one of representing the real number line with float types. For example, the following on Python 2.2.1 #34 running on Windows XP Pro, Celeron Processor (probably different elsewhere) W=0.89 / 4 Now evaluate 1+w+w+w+w and w+w+w+w+1 which are both *different* according to the == operator, but for the purposes of numerical accuracy are identical. This behaviour is quite mild, but it shows the point that rounding errors can easily creep in, and using == to test for equality is not always sensible. Caveat Emptor! From aleax at aleax.it Mon Sep 30 05:00:45 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 30 Sep 2002 09:00:45 GMT Subject: Best way to create a class dynamically on the fly? References: Message-ID: <1pUl9.160835$ub2.3602794@news1.tin.it> Robert Oschler wrote: ... > I forgot to mention, I would like the classes I create dynamically to be > fully "pickle-able". If there are any caveats or limitations in this area > please let me know. Classes are pickled by name (assuming that using modules pickle or cPickle as they stand is what you mean by "fully pickle-able"). So, in general, classes you pickle (or, classes whose instance you pickle) must be top-level names exported by some module. Dynamically created classes obviously don't qualify -- saving all the data needed to recreate such classes, and recreating them just as dynamically when unpickled, is a harder problem. You can register your own arbitrary factories for unpickling, but I don't know if that satisfies your criteria for "fully pickleable". Alex From james.kew at btinternet.com Wed Sep 4 17:29:33 2002 From: james.kew at btinternet.com (James Kew) Date: Wed, 4 Sep 2002 22:29:33 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 4) References: <448A0F008E0AFE11.19B9EF86BEE2B191.107D5020B234F743@lp.airnews.net> Message-ID: "Ian Bicking" wrote in message news:448A0F008E0AFE11.19B9EF86BEE2B191.107D5020B234F743 at lp.airnews.net... > QOTW: The canonical, "Python is a great first language", elicited, > "Python is a great last language!" -- Noah Spurrier > > A thoughtful note on one person's decision to use Python in a > scientific environment: > <3D60A1E2.7FD246E0 at anansispaceworks.com> *cough* My newsreader turns this into an email address, not a news article. I can't persuade Google to find this message-id; any chance of a link? I don't remember that thread but it sounds interesting. -- James Kew james.kew at btinternet.com From DennisR at dair.com Tue Sep 17 10:59:33 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Tue, 17 Sep 2002 14:59:33 GMT Subject: Windows AutoRunning Python Hello -- feedback requested References: <8a6ba1da.0209170148.23bca1e8@posting.google.com> Message-ID: > "Netscape" or "Internet Explorer", but given a system like yours plus > a framework for building an HTML user interface (based on one of the > many web application frameworks for Python) I think this system is > just as valid as Tk, wxWindows, Qt or whichever other 'real' toolkit > you care to name. I think you got it. My system allows one to prototype an app on your web page. Using server logs, you can see how people use it and what the usage problems are. Then a version of the web page can be turned into an executable. Also, client-server apps can be implemented with the client and server displaying in different frames (example at http://www.autorunning.com/present.cgi click on "here" for client part). > ... is it simply a toolkit for distributing > and running browser-based code? Yes > Zope-based Windows applications, anyone? Gasp. I am now in my third day of testing Python support. I have previously implemented Perl but have not distributed it publicly (i.e. it is an undocumented capability). Zope would pose a number of challenges. But, it is an interesting idea. I'll put it into the hopper. Thanks for your reply. -- Dennis Reinhardt http://www.dair.com From rgkindya at yahoo.co.in Sun Sep 8 22:13:43 2002 From: rgkindya at yahoo.co.in (rgkindya) Date: 8 Sep 2002 19:13:43 -0700 Subject: getting input in a embeded GUI app ... References: Message-ID: Chris Liechti wrote in message news:... > tha pythonwin way: you can write your own input function in c/c++ that gets > the input from a message box. it should return Python string. (i assume > you've found out how to write python funcs in c/c++, i.e. like those for in > a module) > then you can replace the builtin function raw_input with your function > (assign it to __builtin__.raw_input). take a look at the python win sources > on how to do this in python. > > chris thank chris, as a newbie , i request you to provide that code ,that will help me to save my work nights and headache. please Chris i'm a newbie ... From richie at entrian.com Thu Sep 12 10:58:40 2002 From: richie at entrian.com (Richie Hindle) Date: Thu, 12 Sep 2002 15:58:40 +0100 Subject: Coding Style: Quotes References: Message-ID: > I'm curious if others have adopted any standards for choice of single vs. > double quotation marks to delimit strings. I tend to use double-quotes for user-visible strings, and single quotes for internal ones. For instance: print "Hello, %s." % userRecord[ 'name' ] In a library module, docstrings count as user-visible because the "users" include the programmer using the library: def greetUser( userRecord ): """Says hello to the user.""" print "Hello, %s." % userRecord[ 'name' ] Don't ask me why I starting using this standard, or where the idea came from, 'cos I have no idea. It just seems to make sense. -- Richie Hindle richie at entrian.com From roy at panix.com Mon Sep 16 22:22:03 2002 From: roy at panix.com (Roy Smith) Date: Mon, 16 Sep 2002 22:22:03 -0400 Subject: Converting Python app to C++ completely References: <3D85D9EB.9020102@thinkware.se> <3D86209F.4080501@earthlink.nospam> <3d868a77$1@news.sentex.net> Message-ID: Peter Hansen wrote: > Hmmm... if instead you choose to wait until you actually *need* C++ > to solve a problem that Python can't handle, you just might find that > you don't ever need to learn C++. Then the second one is actually > not a problem at all! :-) > > This thought courtesy of XP's philosophy of avoiding unnecessary > work, which is acronymized as YAGNI (You Aren't Going to Need It). I'm reasonably convinced that I'll never need C++ to solve real problems. I'm also reasonably convinced that I do need C++ to get invited to job interviews. This thought courtesy of today's economy. Could be worse. I could be trying to learn Cobol, for which I see a lot more job postings than I do for Python :-( From b.maryniuk at forbis.lt Mon Sep 2 06:31:58 2002 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Mon, 2 Sep 2002 12:31:58 +0200 Subject: Why it is so dramatical? In-Reply-To: <200209021228.58453.b.maryniuk@forbis.lt> References: <200209021228.58453.b.maryniuk@forbis.lt> Message-ID: <200209021231.58678.b.maryniuk@forbis.lt> On Monday 02 September 2002 12:28, Bo M. Maryniuck wrote: > Since time() always show me zero, I've used UNIX time command: Well, not exactly... ;-) -- Regards, Bogdan Microsoft is not the answer. Microsoft is the question. "No" is the answer. From rune.hansen at viventus.no Tue Sep 17 07:28:37 2002 From: rune.hansen at viventus.no (Rune Hansen) Date: Tue, 17 Sep 2002 13:28:37 +0200 Subject: tkinter asyncore.loop Message-ID: Hello, Some months back I sendt a question to the list where I asked if anyone knew how to catch errors in an asyncore loop. I got an answer to override the "handle_error" in the client. I still can't get it to trap any errors though. The error I need to trap is "Connection lost". If I remove the network connection and try to update the stream or post to the socket nothing happens. When I reconect the network my application just continues to serve like nothing has happened. This is of course nice, but not the functionallity I'm looking for. Here's the code I'm working with: class StreamApp(StreamAppTK): def __init__(self): ... def streamOn(self): ... self.sc = client(host[0],int(port[0]),self,self.readPasswordFile()) self.poll() def poll(self): try: asyncore.poll(0.05) if self.sc.connected: self.master.after(100, self.poll) except: pass class client(asyncore.dispatcher): def __init__(self,host,port,StreamApp,userPwd): asyncore.dispatcher.__init__(self) try: self.host = host self.port = port self.StreamApp = StreamApp self.fp = "" username, password = userPwd self.buffer = "login "+username+" "+md5.new(password).digest()+"\n" self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect( (self.host, self.port) ) except socket.error,errMsg: self.StreamApp.messageBar.message('state','Error %s, %s' % (errMsg)) def handle_connect(self): pass def handle_read(self): try: self.fp = self.fp + self.recv(65565) if "\n" in self.fp: tmp = self.fp.split("\n")[:] for i in tmp[:-1]: self.StreamApp.insertItem(i) self.fp = tmp[len(tmp)-1] except socket.error,errMsg: self.StreamApp.messageBar.message('state','Error %s, %s' % (errMsg)) def writeable (self): return (len(self.buffer) > 0) def handle_write(self,buffer=""): try: if buffer: self.buffer = buffer sent = self.send(self.buffer) self.buffer = self.buffer[sent:] except socket.error,errMsg: self.StreamApp.messageBar.message('state','Error %s, %s' % (errMsg)) def handle_error(self, etype, evalue, etb): print 'handling error: %s, %s, %s' % (etype, evalue, etb) def handle_close(self): self.connected=0 self.close() As always I'll apreciate any help... regards /rune From aleax at aleax.it Wed Sep 25 05:33:18 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 09:33:18 GMT Subject: Shadow password handling References: <3d90e36d$0$123$7b0f0fd3@reader.news.newnet.co.uk> Message-ID: Phil Edwards <"phil (at) linux2000.com"> wrote: > Hi: > > Does anybody know of a Python module which will allow username/password > credentials to be validated ona Linux box which is configured to use md5 Perhaps PyPAM, http://www.pangalactic.org/PyPAM/ , but I haven't tried it. PAM is supposed to let you access any installed authentication module on your Linux box, isn't it? Alex From torkil at fast.no Wed Sep 18 04:21:42 2002 From: torkil at fast.no (Torkil Grindstein) Date: Wed, 18 Sep 2002 10:21:42 +0200 Subject: Regular expression help needed References: Message-ID: <3D883796.AF573144@fast.no> Thank you all for your help! I appreciate it a lot. Torkil From amdescombes at qualicontrol.com Mon Sep 9 03:43:52 2002 From: amdescombes at qualicontrol.com (Andre Michel Descombes) Date: Mon, 9 Sep 2002 09:43:52 +0200 Subject: Python and Jython inconsistencies when encoding strings References: <3d78ce33$1_3@news.bluewin.ch> Message-ID: Thanks, > sticking to ascii there can avoid some troubles :). unfortunately it is not always possible :( Cheers, Andre "Samuele Pedroni" wrote in message news:3d78ce33$1_3 at news.bluewin.ch... > > Martin v. L?wis wrote in message > j4ofbbclfp.fsf at informatik.hu-berlin.de... > > >>> s > > u"\u0153" > > > > Now, U+0153 is LATIN SMALL LIGATURE OE. It so happens that \x9c (what > > the terminal sends) is U+0153 in CP 1252 (which is the ANSI code page > > on your Windows installation). This might be a bug in Java, which > > assumes that bytes sent by the terminal are in the ANSI code page, > > when they are really in the OEM code page. > > no it's more the Jython parser that does that, things can be fixed running > Jython as > > jython -Dpython.console.encoding=cp850 > > on the other hand output seems buggy for: > > print s.encode("cp850") > > [I have reported that on our SF bug tracker] > > > > > Does anybody know what is causing this inconsistency? Is there any way > to > > > avoid it? > > > > Yes. Don't use the console. > > sticking to ascii there can avoid some troubles :). > > regards > > From gerhard.haering at gmx.de Tue Sep 3 16:23:55 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 3 Sep 2002 20:23:55 GMT Subject: https in Python? References: Message-ID: Martin v. Loewis wrote in comp.lang.python: > s_gherman at yahoo.com (Sorin Gherman) writes: > >> Is it possible to handle https using Python's libraries? > > Sure. Just use httplib.HTTPS. This requires SSL support in the > socket module, which is only available on Unix, and only if you have > OpenSSL. See my page http://www.cs.fhm.edu/~ifw00065/pyssl/index.html for Windows. I wonder why ActiveState doesn't provide SSL support with their Python distribution. I thought they want to distinguish themselves by adding value ;-) -- Gerhard From erikprice at mac.com Mon Sep 9 23:52:55 2002 From: erikprice at mac.com (Erik Price) Date: Mon, 9 Sep 2002 23:52:55 -0400 Subject: IDLE In-Reply-To: Message-ID: On Monday, September 9, 2002, at 08:54 PM, Ali K wrote: > Why won't my IDLE work? If your engine chokes within a second or so of turning over, your idle could be set too low. If it feels like it's running at a higher RPM, then it's probably set too high. I'm not sure about your exact model, but if it's older you may also wish to inspect the carburetor. In a newer one I wouldn't even suggest doing the repairs yourself, since most of the time proprietary tools are required for maintenance (including something as simple as accessing the plugs in a mid-late-90's Honda). It's deplorable what they're doing these days. Erik -- Erik Price (zombies roam) email: erikprice at mac.com jabber: erikprice at jabber.org From aleax at aleax.it Thu Sep 19 11:36:33 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 15:36:33 GMT Subject: strong/weak - dynamic/static [Was: Getting started] References: Message-ID: <5ami9.114674$ub2.2440492@news1.tin.it> Jacek Generowicz wrote: ... > Could someone provide a serious reference (i.e. something which would > have gone through some sort of editorial/peer/technical review, rather > than someone's random opinions on the web) explaining or defining the > concepts of weak, strong, dynamic and static typing. For example, Amer Diwan's lessons on Fundamentals of Programming Languages at the University of Colorado are on the web as PDF files, all info and links at http://www.cs.colorado.edu/~diwan/5535/ -- I wouldn't consider these "somebody's random opinions on the web"... it IS a regular, qualified university course. The introduction to types, in particular, is at: http://www.cs.colorado.edu/~diwan/5535/lectures/2-types.PDF and the already-referenced URL gives some fundamental bibliography (I'm prejudiced in favor of Carlo Ghezzi's text, but that, of course, is just because he's a compatriot:-). Alex From pan-news at asheeshenterprises.com Fri Sep 20 17:53:38 2002 From: pan-news at asheeshenterprises.com (Asheesh Laroia) Date: Fri, 20 Sep 2002 17:53:38 -0400 Subject: access to palm with pilot-link pisock library (python binding) References: <24165ed4.0209200308.4d6b3b7a@posting.google.com> Message-ID: You could try the jpilot-Python tools that integrate Python and JPilot. While it's not a perfect solution, it's the best I can find that works for Python right now. You can get it from http://www.nickpiper.co.uk/jpilot-python.php3. If something doesn't work for you, *make sure to email the author*; he is very responsive. Best luck! Feel free to reply! -- Asheesh. On Fri, 20 Sep 2002 04:08:43 +0000, Solon Kazantzidis wrote: > Hello, > > I want to achieve the following: > > - I want to use the python language to access my palm pilot Vx - I found > the pilot-link package which provides a python binding of the pisock > library written in c > - Unfortunately the documentation I need as newbie to this is listed in > the TODO list so I am searching a documentation - I want to be able to > connect to the Palm (I have some example for a connection from the > pyrite-publisher .py file) - I want to be able make what the pilot-xfer -l > command does - I want to be able to create/delete/access databases stored > on my Palm > - I need to have access on data which I want to gather with the Palm > > What I achieved so far: > 1. downloaded pilot-link package (version 0.11.3) 2. build it and created > the python binding (python version 2.2.1) 3. from file > plugin_instpisock.py (pyrite-publisher) I got some starting information to > establish connection to the palm: > > ------------------------------------------------------------------------- > > #!/usr/bin/python2.2 > import pisock > > port = "/dev/pilot" > > sd = pisock.pi_socket(pisock.PI_AF_SLP, pisock.PI_SOCK_STREAM, > pisock.PI_PF_PADP) > if not sd: > print "failed to create socket" > exit > if (pisock.pi_bind(sd, (pisock.PI_AF_SLP, port))) == -1: > print "failed to bind socket" > exit > if (pisock.pi_listen(sd, 1)) == -1: > print "failed to listen on socket" > exit > ret = pisock.pi_accept(sd) > if ret == -1: > print "failed to accept connection" > exit > socket = ret[0] > pisock.dlp_OpenConduit(socket) > pisock.dlp_ReadDBList(sd,0,pisock.dlpDBListRAM,0) > > -------------------------------------------------------------------------- > > As there is no documentation out there and I am not the best programmer I > can only say that the whole procedure stops with a: > "Speicherzugriffsfehler"-->(translated) "Memory access failure" > > All works fine until the "ret = pisock.pi_accept(sd)". At this point the > python interpreter stops and waits for me to press the hotsync button. > After I press it the above mentioned error arises. > > > I need urgently help with this as I cannot with the start form my thesis > until the mechanism for accessing works. (and then the real work of > synchronising gathered data starts....) > > > Thanks alot for your help/comments, > > Solon. From scott at projtech.com Fri Sep 6 04:10:34 2002 From: scott at projtech.com (Scott Finnie) Date: Fri, 6 Sep 2002 08:10:34 +0000 (UTC) Subject: 4Suite Server bombs on win32 - suggestions? Message-ID: <3D786370.3E5666FC@projtech.com> As it says: I installed 4Suite (0.12.0a2) and everything seemed to go OK, but 4ss_manager bombs (protection violation). Python 2.2.1 on winNT sp6 (tried 2.2 on win2K with same result). Has anyone else seen/fixed this? Tried the mailing list but got no reply... Thanks, Scott. From jdhunter at ace.bsd.uchicago.edu Mon Sep 23 10:58:15 2002 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 23 Sep 2002 09:58:15 -0500 Subject: numpy array assignment Message-ID: I have a 2 dimensional array X which is NxM and a 1 dimensional array v which is Nx1. I want to assign v to the k-th column of X import Numeric import RandomArray Z = Numeric.zeros( (3,10), Numeric.Float ) v = Numeric.ones( (3,1), Numeric.Float ) Z[:,4] = v But I get the ValueError: Object too deep for desired array. I have read over the numpy manual on slices and array methods and the closest thing I saw was the 'put' method, but this seems to be designed for 1d indexing. What's the best way to assign an arbitrary Nx1 array to a column of X? Thanks, John Hunter From jeremy at alum.mit.edu Mon Sep 9 12:56:20 2002 From: jeremy at alum.mit.edu (Jeremy Hylton) Date: 9 Sep 2002 09:56:20 -0700 Subject: Zope Status? References: Message-ID: "Jeff Sasmor" wrote in message news:... > Speaking from what I understand about this subject, it's not > simple for the Zope Corp to merely plug-in a new version of > Python and make a release. Disregarding any issues about > changes they might want to make that would take advantage of > new features of Python 2.2 (and up), the underlying instrumentality > of Zope, the ZODB (Zope Object DataBase) as it exists in Zope 2.5 > and so on, will not run under Python versions > 2.1 due to > incompatibilities of the C extension classes with the changes made > (in Python 2.2) regarding type-class unification. > > Obviously, there's already a version of ZODB for Python 2.2, but > I think it's not something that one cannot just 'drop in' to a current > version of Zope. The issue is a little more subtle, actually. The existing version of ZODB -- the one that ships with Zope 2.5 -- works just fine with Python 2.3. Python works hard to be backwards compatible with C extensions written against older versions of the C API. The current version of ZODB uses ExtensionClass, and that compiles cleanly and runs with Python 2.1 and up. The only compatibility issue is that ExtensionClass types don't mix cleanly with new-style types. But if you're not depending on new-in-2.2 features, then you've got nothing to worry about. Python 2.2 provides an opportunity to re-write ZODB to use new-style types instead of ExtensionClass. The new implementation will work cleanly with new-style types. The rewrite, dubbed ZODB4, is working, but experimental. We're may rewrite the API completely tomorrow <0.8 wink>. You can checkout ZODB4 or Zope3 from cvs.zope.org to play with the new version. We're also discussing some ZODB issues -- basic persistence and transaction APIs -- on the persistence-sig. http://www.python.org/sigs/persistence-sig Jeremy From phr-n2002b at NOSPAMnightsong.com Sat Sep 21 01:34:10 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Sep 2002 22:34:10 -0700 Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> <7xn0qcfafp.fsf@ruckus.brouhaha.com> Message-ID: <7xwupf52jx.fsf@ruckus.brouhaha.com> Christopher Browne writes: > REALITY CHECK for a moment. > > What do you think A Real Live bank uses to compute interest? If I had to guess, I'd guess they use floating point. I do know that financial modelling software I worked on that was sold to banks used floating point. Also, spreadsheets use floating point. But it's possible (likely even) that some bookkeeping applications use BCD. One that I worked on actually used exact, multi-precision rational arithmetic, but I think that's unusual. Note that the x86/x87 still supports BCD arithmetic in microcode. In reality, though, programs that use BCD to keep track of money don't do all that much arithmetic, so software emulation is plenty fast enough. From Lutz.Schroeer at kybernetik-manufaktur.de Thu Sep 5 17:46:57 2002 From: Lutz.Schroeer at kybernetik-manufaktur.de (Lutz Schroeer) Date: 5 Sep 2002 21:46:57 GMT Subject: What database should I use References: Message-ID: "A" wrote in news:mailman.1031257921.29400.python-list at python.org: > I am going to program a small application (in Python and wxPython) > which consists about 2000 - 3000 records . Can you please recommend > which database is the best for that. I use Windows. > Maybe MS Access or FoxPro or MySQL or better? > I want to keep the program as small as possible. >From your question I derive that you want to run the program on an MS Windows system. Access seems to be the best solution. You can access the database over the ODBC driver without having a "real" server running in the background. You only need the *.mdb files. But keep in mind, that you're stuck to Billy's system. I don't think that there are any modules providing access to *.mdb files on other systems. If there is, please enlighten me.... Latz From fredrik at pythonware.com Wed Sep 4 03:14:11 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Sep 2002 07:14:11 GMT Subject: Tkinter: text widget predefined key bindings References: <2259b0e2.0208270502.5eb0a330@posting.google.com> <200208271417.21285.mfranklin1@gatwick.westerngeco.slb.com> Message-ID: <7pid9.5887$e5.1033373@newsb.telia.net> Eric Brunel wrote: > Yep, but it does not work in all cases: if you type accented characters, > they are ignored by your undo; same if you do a XWindows-style paste > (selecting, then Button2 anywhere in your Text widget). I suppose any text > change done via any default binding will probably also be ignored... > > Believe me: it's really harder than it seems... We tried to do it once and > it never worked correctly... the "right" way to do this is to dynamically override the "insert" and "delete" commands, on the Tcl level. IDLE has code to do this. (for true enlightenment, write your own keyboard controller, and plug it in using bind_class...) ::: I once wrote a patch to Tkinter that added bind_insert and bind_delete methods to the standard text widget, but I seem to have lost the code. If I find it, I'll post it here: http://effbot.org/zone/tkinter-text-bind-insert-delete.htm From gerhard.haering at gmx.de Sun Sep 15 22:19:03 2002 From: gerhard.haering at gmx.de (Gerhard Haering) Date: Mon, 16 Sep 2002 04:19:03 +0200 Subject: can wxpython do this? In-Reply-To: References: <737aefee.0209151702.3f735252@posting.google.com> Message-ID: <20020916021903.GA4833@gargamel.ghaering.test> * Erick [2002-09-16 10:42 +0900]: > Thank you very much Lothar. > > > There is no problem to setup an installer easily that takes > > Python,WXPysthon and whatever you need. It simply blowes up the > > installer package size. > > Isn't this the way to distribute wxpython apps? Because most users will not > have python installed on their machines, much less the wxpython libraries? > Or is it that after compilation users do not need Python installed at all? There is no compilation step in Python ;-) You can go both ways: 1) Put a Python installation with the necessary libraries and DLLs (wxPython + python22.dll) in a directory, then feed that directory to your favourite installer maker (NSIS, whatever) 2) Use a tool like py2exe or McMillan's installer to automatically find dependencies and make a .exe out of your app. This will still need the Python runtime & DLLs and about the only difference is that you don't have lots of .py{c|o} files lying around. I personally favour option #1 and cutting down the Python runtime manually, as I experienced that apps created with py2exe don't produce very useful tracebacks any more. Besides, for some libraries like PIL the automatic dependency checking of py2exe doesn't work very well, anyway. > > >for instance, can i minimize my application to a user's desktop's taskbar > > >and have a right-click context menu on that taskbar entry? > > > I think its not comfortable but possible. Look at the API to find out. > > I searched the html help for "taskbar" and there is only one function for > Win95/NT (wxTaskBarIcon). Looks like this feature is not yet supported? It is. Just install wxPython on Windows, start the demo app and minimize it. Voil? a taskbar icon. I recently wrote an IMAP mail watcher for win32 myself that doesn't have any visible window and only consists of one wxPython taskbar icon that changes icons and can be double-clicked :-) > > There is a really simple WxHTML Widget and at least a C++ version of a > > wrapped IExplorer control. > > The wxHTML widget supports only some very basic HTML tags, but I guess > that'll do for now. What I really wanted to know was if there is a way for > me to connect to the Internet, make a call to a webserver as a browser would > do, retrieve data and display it inside my application (with or without > HTML...does not have to be HTML at all, actually). You don't need wxPython for that, the Python standard library has all the means for that, including support for the most popular protocols like http, ftp, smtp, pop3, imap and nntp. Raw sockets of course, too. > Perhaps wxSocket is what I am talking about. Features that Python has already (like sockets, threads, ODBC, ...) aren't wrapped from wxWindows to wxPython. You can use standard Python libraries like socket and threading for these. > But I did not see anything in the "demo" that has much to do with sockets. > Would anyone know an example of using sockets in wxpython? There is. Check out the Slashdot headline watcher and the Hangman example. But that's really a Python rather than a wxPython issue. -- Gerhard From David.Kastrup at t-online.de Tue Sep 17 08:16:12 2002 From: David.Kastrup at t-online.de (David Kastrup) Date: 17 Sep 2002 14:16:12 +0200 Subject: Using emacs gud/pdb python debugger under windows References: <87elbuo46g.fsf@tleepslib.sk.tsukuba.ac.jp> <87n0qiul6j.fsf@computer.localdomain> <3cs86d38.fsf_-_@online.no> Message-ID: Syver Enstad writes: > Felix writes: > > > Syver Enstad writes: > > > > u just need to fix a few things to make it recogonize the win32 path. > > here's how, open gud.el and search for the variable > > 'gud-pdb-marker-regexp', > > > > then modify it to something like: > > (defvar gud-pdb-marker-regexp > > "^> > > \\([-a-zA-Z0-9_/.:\\]*\\|\\)(\\([0-9]+\\))\\([a-zA-Z0-9_]*\\|\\?\\)()\\(->[^\n]*\\)?\n") > > > > this works well for me. > > Ha, ha it works, it works! (Dancing around the room) I want to hug you > Felix! I didn't think of that, obviously. So it was just pdb failing > to recognize the output from the windows version of python. When you are done frolicking, you should be sending this information on to the package maintainer, so that others will not have to bear this problem in future. -- David Kastrup, Kriemhildstr. 15, 44793 Bochum Email: David.Kastrup at t-online.de From johnroth at ameritech.net Mon Sep 2 17:49:23 2002 From: johnroth at ameritech.net (John Roth) Date: Mon, 2 Sep 2002 17:49:23 -0400 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: "Gerson Kurz" wrote in message news:3d725881.345921 at news.t-online.de... > I wrote a small wrapper module to "struct" today that will allow me to > write C declarations and have > > ... > print p.declare(""" > > struct test1 > { > int a,b; > float this,and,that; > }; > > struct test2 > { > int count; > struct test1 data[80] > }; > > """) > ... > and have it create instances I can easily assign data to > ... > t2 = p.createInstance("test2") > t2.data[0].a = 42 > ... > and pack for C extensions by utilizing the struct module > ... > data = p.pack(t2) > ... > > because of being fed up with that pack("qh34s>id",...) stuff. (I'll > post that to my website once its in a state I can let somebody else > see ;) > > Anyway, that got me thinking on why do we have to deal with regular > expressions like r"((?:a|b)*)", when in most cases the code will look > something like this: > > r = re.compile("") > ... > r.match(this) or r.find(that) > > which means the real time is not spent in the compile() function, but > in the match or find function. So basically, couldn't one come up with > a *human readable* syntax for re, and compile that instead? Python > prides itself on its clean syntax, and human readability, an bang - > import re, get perl-ish code instantly! > > Also, I think it would already be an improvement if the syntax > provided for clear and easy-to-understand special cases, like > > re.compile("anything that starts with 'abc'") > > and if you cannot find something in the special cases for you, you can > always go back to > > re.compile("") > > After all, *everyone* starting with re thinks the syntax is cryptic > and mind-boggling, and only if you get yourself into the "re mindset", > you understand things like r"\s*\w+\s*=\s*['\"].*?['\"]" instantly. If > we had an easier syntax, more people would be using re ;) > > Is the idea utterly foolish? No, it's not utterly foolish. You might be surprised to learn that Larry Wall agrees with you that the Perl regex syntax is much too obtuse, and in need of a basic, ground up redesign. Even current Perl syntax allows you a special form where you can insert blanks for readability. http://www.perl.com/pub/a/2002/06/04/apo5.html http://www.perl.com/pub/a/2002/08/22/exegesis5.html It's an interesting redesign of basic regex functionality. Some of the things you can do with it are very, very interesting indeed. John Roth > From aahz at pythoncraft.com Sun Sep 8 10:40:20 2002 From: aahz at pythoncraft.com (Aahz) Date: 8 Sep 2002 10:40:20 -0400 Subject: Names and bindings (was Re: Scope of instantiated class) References: <3D3ACCA6.7030002@lmco.com> Message-ID: [silent snippage ahead] In article , Michael Hudson wrote: >aahz at pythoncraft.com (Aahz) writes: >> In article , >> Michael Hudson wrote: >>> >>>Common Lisp calls them "places", which is a reasonable name. It's not >>>that much of an issue in Python as there aren't that many of them >>>(names, attributes, subscripts, slices). In CL, you can define your >>>own (tho' it's a bit tricky). >> >> What exactly does "place" refer to in Common Lisp? Is a place capable >> of holding a value, or can places only contain references? > > place n. 1. a form which is suitable for use as a generalized > reference. 2. the conceptual location referred to by such a > place[1]. > >and > > generalized reference n. a reference to a location storing an object > as if to a variable. (Such a reference can be either to read or > write the location.) See Section 5.1 (Generalized > Reference). See also place. > >So I guess more of the latter of your two options. Do Common Lisp places have automatic reference/dereference semantics like Python? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From bobx at linuxmail.org Wed Sep 11 21:07:45 2002 From: bobx at linuxmail.org (Bob X) Date: Thu, 12 Sep 2002 01:07:45 GMT Subject: [FEEDBACK] Is this script efficient...is there a better way? References: Message-ID: Fernando P?rez wrote: > Bob X wrote: > > >>I use this to parse a log file (30MB+) for keywords and write the lines >>that are found into another file. >> >>Any thoughts would be appreciated... :-) >> > > > How about > > $ grep words infile | tee outfile > > Cheers, > > f. grep is not usually on Windows...and I *want* to use Python. :-) From christian.schmutzer at gmx.net Tue Sep 3 07:45:37 2002 From: christian.schmutzer at gmx.net (christian) Date: 3 Sep 2002 04:45:37 -0700 Subject: can't access com object - why doesn't this work? Message-ID: Hi I ran into a strange problem when accesing the com interface of VC7 using python. (I am using python and makepy to access the com interface of VC7.) ------------------------------------------ my python code looks as follows: ------------------------------------------ ... DTE = win32com.client.Dispatch('VisualStudio.DTE') cfgs = DTE.Solution.Projects.Item(1).ConfigurationManager.Platform("Win32") cfg = cfgs.Item(1) print cfg props = cfg.Properties ... ----------------------------- Basically I retrieve a configuration object from the configuration manager and then try to access a member function. But the configuration object always seems to be broken. When I execute the script, the print still works fine: output: "" but accessing the python-property "Properties" causes this error: Traceback (most recent call last): [...] File "C:\PROGRA~1\python\lib\site-packages\win32com\client\__init__.py", line 355, in __getattr__ return apply(self._ApplyTypes_, args) File "C:\PROGRA~1\python\lib\site-packages\win32com\client\__init__.py", line 349, in _ApplyTypes_ return self._get_good_object_(apply(self._oleobj_.InvokeTypes, (dispid, 0, wFlags, retType, argTypes) + args), user, resultCLSID) pywintypes.com_error: (-2147352567, 'Exception occured.', (0, None, None, None, 0, -2147467259), None) But I really don't understand, why this is illegal. I have researched the com interface, its relations and internal structures in the documentation and this should be valid. I looked at what makepy generated, and that also says that this call should be possible: class ConfigurationManager(DispatchBaseClass): [...] # Result is of type Configurations def Platform(self, Name=defaultNamedNotOptArg): """Returns a collection of ConfigurationAssignment object for the specified platform.""" ret = self._oleobj_.InvokeTypes(0x8, LCID, 1, (9, 0), ((8, 0),),Name) if ret is not None: ret = win32com.client.Dispatch(ret, 'Platform', '{B6B4C8D6-4D27-43B9-B45C-52BD16B6BA38}', UnicodeToString=0) return ret ... class Configurations(DispatchBaseClass): """A collection of Configuration objects.""" CLSID = pythoncom.MakeIID('{B6B4C8D6-4D27-43B9-B45C-52BD16B6BA38}') # Result is of type Configuration def Item(self, index=defaultNamedNotOptArg): """Returns an indexed member of a collection.""" ret = self._oleobj_.InvokeTypes(0x0, LCID, 1, (9, 0), ((12, 1),),index) if ret is not None: ret = win32com.client.Dispatch(ret, 'Item', '{90813589-FE21-4AA4-A2E5-053FD274E980}', UnicodeToString=0) return ret ... class Configuration(DispatchBaseClass): [...] _prop_map_get_ = { [...] # Method 'Properties' returns object of type 'Properties' "Properties": (7, 2, (9, 0), (), "Properties", '{4CC8CCF5-A926-4646-B17F-B4940CAED472}'), "Type": (5, 2, (3, 0), (), "Type", None), So for all I can see, this should work. So I have also tried out a VB script to retrieve the information, and it works just fine, so the com objects seem to be valid after all. ------------------------------------- The VB script looks like this: ------------------------------------- Dim cfgs As Configurations Dim cfg As Configuration Dim props As Properties cfgs = DTE.Solution.Projects.Item(1).ConfigurationManager.Platform("Win32") cfg = cfgs.Item(1) props = cfg.Properties -------------------------------------- This script works just fine. As you can see, apart from some minor sytactical things, the script is identical. I really don't get why this doesn't work in python. So what am I doing wrong? Am I using python the wrong way, or could this be a python-com problem? Has anybody encountered a similar problem? Thanks, Christian From ralf_ahlbrink at web.de Sat Sep 21 12:45:02 2002 From: ralf_ahlbrink at web.de (RA) Date: Sat, 21 Sep 2002 18:45:02 +0200 Subject: PyQt setup on Linux Mandrake 8.2 References: <3D8B4898.20808@nospam.attbi.com> <3D8BC2F4.8080107@nospam.attbi.com> Message-ID: <3d8ca20e$0$151$9b622d9e@news.freenet.de> On Sat, 21 Sep 2002 14:33:00 +0000, dwelch wrote: > Armin Steinhoff wrote: >> dwelch wrote in message news:<3D8B4898.20808 at nospam.attbi.com>... >> >>>I would like to setup PyQt 3.4 on my Mandrake 8.2 box. I am having >>>difficulty, and I am worried that if I do the wrong thing, KDE will go >>>belly-up on me since it is Qt based. >>> >>>First, question is: why isn't QTDIR defined by default? >>> >> >> PyQt works with Qt2.x.x and Qt 3.x.x ... so YOU have to choose the >> correct directory. >> >> >>>Is QTDIR a >>>runtime setting or a development setting? >>> >> >> Both .. >> >> >>>So I set QTDIR to /usr/lib/qt2 (that seems to be where the libqt2 RPMs >>>files are). Next question is: Since I have libqt2 already on my system, >>>how do I add the Qt development pieces without screwing up Qt/KDE? Is >>>/usr/lib/qt2 even the correct location? >>> >> >> Yes ... if you want to use only the latest version of Qt 2.x.x >> >> >>>When I run SIP 3.4 build.py, it complains about tmake not being >>>available. Is tmake included with Qt2 development files? >>> >> >> It's available at the Trolltech homepage or its mirrors. >> >> >>>SIP doesn't >>>seem to have any docs, so I'm not sure how to proceed. >>> >> >> Nomally you haven't to care about SIP .. >> >> >> >>>Also, my RPM manager says that I have libqt2-devel (2.3.1-29mdk) >>>installed. No tmake listed in the files, though. And, PyQt-devel >>>(2.5-1mdk) is also listed as installed, but there aren't any .py files >>>included, only .sip files (I found this curious). >>> >> >> Corious ... there must be examples included. >> >> I would suggest to dowload the latest version of Qt from the Trolltech >> homepage, just for a simple and clean recompilation. >> >> And do the same with SIP and PyQt from the Riverbank homepage ... >> >> It seems to be better to forget that outdated stuff provided by the >> Mandrake distribution ... >> >> Armin >> >> >>>Installing software on Linux makes me feel like such an idiot! >>> >>>Any help or pointers would be much appreciated. >>> >>>Don >>> > > OK, I found and installed tmake. Now, SIP can't find some of the Qt > pieces it needs. So, I still don't understand the situation with Qt. Is > it really possible to install and run my applications that I write with > say Qt 3.0.5, when KDE on my system is using Qt 2.3.1? How does/would > KDE know which version to use? How will my apps know what version to > use? I am assuming there can only be one QTDIR active on a system at a > time... I'm not sure. But perhaps you can also use qmake, which is located in the libqt3-devel-3.0.5 RPM. This package contains also header files for the compilation of Qt3 apps. For compilation perhaps setting QTDIR is enough. Maybe you have to set something like --qt-dir during configure (try configure --help). > > Thanks for the help, > > Don Ralf. From max at alcyone.com Thu Sep 26 17:34:04 2002 From: max at alcyone.com (Erik Max Francis) Date: Thu, 26 Sep 2002 14:34:04 -0700 Subject: Who knows somefunction? References: <3D937B08.4090704@aon.at> Message-ID: <3D937D4C.2BFDF40A@alcyone.com> Gregor Lingl wrote: > Is there a function in Python > for which > > something is (id(something)) > > returns invariably true? Not offhand, but there's an easier test. x is y really just means id(x) == id(y), so you could change this test to: id(something) == id(somethingElse) and you probably wouldn't have the need for your hypothetical function. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Love is the wisdom of the fool and the folly of the wise. \__/ Samuel Johnson Python chess module / http://www.alcyone.com/pyos/chess/ A chess game adjudicator in Python. From news at datatailors.com Fri Sep 20 17:00:09 2002 From: news at datatailors.com (Peter van Kampen) Date: Fri, 20 Sep 2002 23:00:09 +0200 Subject: saving state in Python/CGI References: Message-ID: In article , Frank Gibbons wrote: > Hi, > > I've been using Python (and Jython) for about 5 months now. So far, so > great. I'm building a CGI app that has about 5 different stages, and I need > to maintain state between them. Specifically, it's a scientific tool that > requires the user to upload a (possibly quite large) datafile, processes > it, does some computation, then hands it back (formatted) with results. > > I need access to the data on each page, yet don't want to pass it as a > hidden field, because of its potential size. In Perl, I could just use the > save() method from CGI.pm to save the form on the server side, pass a > session key in a hidden field, then retrieve the data using the key. For > the life of me, I can't find an equivalent way in Python. cgiFormStorage > looks like a dictionary, but it's immutable, so you can't retrieve data > from disk and add it to the form. cgi.py appears to have no analog to > CGI.pm's save() method, at least not that I've been able to find. I've > tried pickling the form, but that doesn't work either (it saves something > to disk alright, but not the large data retrieved from a multi-part form > file upload). > > Perhaps I've missed something. Maybe that's just not how you do things in > Python. Can anyone help? > > Thanks, > > -Frank Gibbons > Hi Frank, Perhaps you can use the code below. It's my first little python project so I'm mainly posting this for some feedback. It's a simpler version (at least to my mind) of something I found in the vaults. It creates a dict to store sessionvars in and pickles it to the hd. You have to setup a dir where the webserver account has write (and read) access. It defaults to .session/ in the current dir. It uses cookies to pass the sessionid that's why you have be careful to write the headers that the class generates. It uses apache's mod_unique_id if it is enabled (and you're using apache ;-) I haven't tested yet but it should work in any cgi-environment) which provides nicer cookie-id's than tempfiles which is used as a fallback but I haven't checked if tempfilenames are safe sessionids. You can use it like this. #First page import CookieSession s = CookieSession.CookieSession() s["whatever"] = "you want (if it can be pickled)" s.save() print "Content-type: text/html" print s.headers() print print YourHTML #Another page import CookieSession s = CookieSession.CookieSession() restore_from_session = s["whatever"] As I said. Comments are very welcome. PterK #! /usr/bin/env python # CookieSession.py # # Based on stuff i found at http://wingide.com/opensource/httpsession # which in turn I located in the Vaults of Parnassus : # http://py.vaults.ca/parnassus/ import os import time import stat import glob import Cookie import cPickle import tempfile #python2.2 version #class CookieSession(dict): class CookieSession: """ TODO: Write docstring """ #----------------------------------------------------------------------- def __init__(self, timeout = 20, \ store = ".sessions"): """ Init the class. 1. Set timeout 2. Set where to store the pickles 3. Clear up old sessions 4. Find out if a session is active 5. Yes? Load it and 'touch' it 6. No? Create a new one, set some attributes and save it to disk. """ self.__timeout = timeout * 60 self.__session_store = store self.__cookies = "Cache-control: no-cache\r\n" self.__on_expire_is_set = 0 # expire old sessions self.__ClearOldSessions() # Get the current session or create a new one try: self.__sessionid = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"]) \ ["sessionid"].value #touch session (from an effbot-posting) now = time.time() os.utime(self.__SessionFilename(), (now, now)) #load session self.__SessionDict = self.__LoadSession() except: # Create a new session self.__sessionid = self.__CreateSessionid() self.__CreateCookie() self.__SessionDict = {} self["sessionid"] = self.__sessionid self.save() #----------------------------------------------------------------------- def expire(self): "Forces the current Session to expire" self.__on_expire() #----------------------------------------------------------------------- def headers(self): "Creates all headers for the calling page" return self.__cookies #----------------------------------------------------------------------- def save(self): "Saves the sessionDict to a pickled file" cPickle.dump(self.__SessionDict, self.__OpenSessionFile("w")) #----------------------------------------------------------------------- def __setattr__(self, name, value): "Used to check whether on_expire is set. Maybe a method is better?)" self.__dict__[name] = value if name == "on_expire": self.__on_expire_is_set = 1 #----------------------------------------------------------------------- def __on_expire(self, sessionid = None): """ Calls a function that can be assigned to the attribute on_expire similar to ASP's On_Session_End. It passes the session about to expire. def OnExpire(expired_session): if not expired_session["TransactionComplete"]: #Remove cruft from database pass s = CookieSession() s.on_expire = OnExpire ... s.expire() """ if sessionid is None: sessionid = self.__sessionid try: # Test if it is set to prevent unnecessary loading of pickles if self.__on_expire_is_set: self.on_expire(self.__LoadSession(sessionid)) finally: os.remove(self.__SessionFilename(sessionid)) #----------------------------------------------------------------------- def __CreateSessionid(self): "Create a sessionid from the apache unique_id module or a tempfile." try: id = os.environ["UNIQUE_ID"] except: id = os.path.basename(tempfile.mktemp()) return id #----------------------------------------------------------------------- def __CreateCookie(self): "Create a cookie to store the sessionid on the clientside" C = Cookie.SimpleCookie() C["sessionid"] = self.__sessionid C["sessionid"]["path"] = "/" self.__cookies += C.output() #----------------------------------------------------------------------- def __SessionFilename(self, sessionid = None): if sessionid is None: sessionid = self.__sessionid return self.__session_store + "/.session" + str(sessionid) #----------------------------------------------------------------------- def __OpenSessionFile(self, mode, sessionid = None): "Open up the on-disk session persistence file" if sessionid is None: sessionid = self.__sessionid f = open(self.__SessionFilename(sessionid), mode) return f #----------------------------------------------------------------------- def __LoadSession(self, sessionid = None): "Loads a session from a pickled file" if sessionid is None: sessionid = self.__sessionid return cPickle.load(self.__OpenSessionFile("r", sessionid)) #----------------------------------------------------------------------- def __ClearOldSessions(self): "Remove any expired session files" files = glob.glob(os.path.join(self.__session_store, '.session*')) for file in files: filetime = os.stat(file)[stat.ST_MTIME] currtime = time.time() if filetime + self.__timeout < currtime: # len(".session") = 8 sessionid = file[len(self.__session_store)+9:] self.__on_expire(sessionid) #----------------------------------------------------------------------- # In 2.2 this works : # class CookieSession(dict): # # Python map emulation : This (below) can be dropped for python2.2 #----------------------------------------------------------------------- def __len__(self): return len(self.__SessionDict) #----------------------------------------------------------------------- def __getitem__(self, key): retval = self.__SessionDict.get(key) if retval == None: retval = "" return retval #----------------------------------------------------------------------- def __setitem__(self, key, value): self.__SessionDict[key] = value #----------------------------------------------------------------------- def __delitem__(self, key): del self.__SessionDict[key] #----------------------------------------------------------------------- def keys(self): return self.__SessionDict.keys() #----------------------------------------------------------------------- def values(self): return self.__SessionDict.values() #----------------------------------------------------------------------- def items(self): return self.__SessionDict.items() #----------------------------------------------------------------------- def has_key(self, key): return self.__SessionDict.has_key(key) #----------------------------------------------------------------------- def get(self, key, f=None): return self.__SessionDict.get(key, f) #----------------------------------------------------------------------- def clear(): return self.__SessionDict.clear() #----------------------------------------------------------------------- def copy(): return self.__SessionDict.copy() #----------------------------------------------------------------------- def update(b): return self.__SessionDict.update(b) From e_fax_t at hotmail._ZAPME_.com Sun Sep 22 11:16:56 2002 From: e_fax_t at hotmail._ZAPME_.com (Justin) Date: Sun, 22 Sep 2002 17:16:56 +0200 Subject: Wanted: Tix examples Message-ID: <3d8dde58$0$30454$afc38c87@sisyphus.news.be.easynet.net> Hi, I see that Activestate's builds of python 2.2.1 both for Win32 and linux include the Tix.py module. No example at all seems to be provided, though. Even a visit to tix.sourceforge.net did not make it obvious to me where to start. The module itself mentions the tixwidgets.py demo; where does one find it? I am primarily interested in the tree-view widget. Any pointer appreciated, TIA, Justin. From andrew.thompson at ashecastle.com Thu Sep 26 04:25:59 2002 From: andrew.thompson at ashecastle.com (Andrew Thompson) Date: Thu, 26 Sep 2002 09:25:59 +0100 Subject: object changing itself to another object In-Reply-To: Message-ID: <019e01c26536$58613480$4802a8c0@blair> Smalltalk (at least the Digitalk versions) provide a means for an object changing into another object via the #become: message. -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of Eric Brunel Sent: 26 September 2002 09:22 To: python-list at python.org Subject: Re: object changing itself to another object Glen Murphy wrote: > I'm creating a program that takes user input, and passes it to an object - > however, I want that object itself, and not the parent to change where > that input goes. In the highly simplified example below, I would like the > output to be "Obj1","Obj2","Obj1" - but not suprisingly, I just get Obj1, > Obj1, Obj1 > > > ### code begin ### > > class Obj1: > def key1(self): > # do obj1 specific stuff > self = Obj2() > print "Obj1" > > class Obj2: > def key1(self): > # do obj1 specific stuff > self = Obj1() > print "Obj2" > > a = Obj1() > > # simulate user keypresses > a.key1() > a.key1() > a.key1() > > ### code end ### > > I know I could achieve the result I want by doing horribly complicated > trees of ifs and such, but I'd like my code to be nice and expandable (in > this example, to easily add new Objs). I've looked through the Python FAQ, > Google Groups and Various O'Reilly books, but I don't really know the > terminology for what I'm looking for, so I haven't found anything so far, > so does anyone have any pointers? AFAIK, there's no way to do exactly what you request. In fact, I've never seen a language allowing to dynamically change the class of an object once it's been created. But there's a quite simple workaround using a factory object. For example: class Obj1: ... class Obj2: ... class ObjFactory: def __init__(self): self.__theClasses = [Obj1, Obj2] self.__classIndex = 0 self.__theObject = None def getObject(self): self.nextObject() return self.__theObject def nextObject(self): self.__theObject = self.__theClasses[self.__classIndex] self.__classIndex = (self.__classIndex + 1) / len(self.__theClasses) And now, it does what you want: a = ObjFactory() a.getObject().key1() # Called on Obj1 a.getObject().key1() # Called on Obj2 a.getObject().key1() # Called on Obj1 I don't know if it suits your needs exactly, but you get the idea... And since the actual objects are created by the factory, you can make them know the factory and call themselves the nextObject method when needed instead of calling it systematically in getObject. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com -- http://mail.python.org/mailman/listinfo/python-list From gerhard.haering at gmx.de Sun Sep 1 14:44:39 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 1 Sep 2002 18:44:39 GMT Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: Robert Oschler wrote in comp.lang.python: > "Gerhard H?ring" wrote: >> >>> class Foo: pass >> ... >> >>> foo = Foo() >> >>> foo.bar() >> Traceback (most recent call last): >> File "", line 1, in ? >> AttributeError: Foo instance has no attribute 'bar' >> >>> def bar(self): print "bar" >> ... >> >>> Foo.bar = bar >> >>> foo.bar() >> bar >> >>> > > Gerhard, > > Thanks but I need a little bit more detail. Suppose I want to do it from > within code? For example, I create a function called > AddBarToFoo(FooObject), that given a object of type Foo (FooObject) adds the > Bar method to it dynamically, what would be the syntax then? To get the class of an instance, you can query its __class__ attribute. > Would I have to put the method declaration code, which you show > being typed in to the interpreter, in a string and then eval/exec > it? No, you hardly ever need to use eval or exec. Sometimes you only want to "specialize" an existing, more generic function. For a real-life example, here's something I experimented with yesterday: # [snip generic_insert, generic_update] def generic_delete(tablename, id): cursor = getdb().cursor() statement = "DELETE FROM %s WHERE id=%%s" % tablename cursor.execute(statement, (id,)) def make_functions(tablename): globals()[tablename + "_DELETE"] = lambda id: generic_delete(tablename, id) # Create a specialized DELETE function for the table TEST which will # be named TEST_DELETE (this will be a specialized generic_delete): make_functions("TEST") # Execute the newly created function: TEST_DELETE(25) I never really needed to add methods to classes on-the-fly, but the above technique came in useful a few times. One other thing I found useful is dynamically creating a new class (with certain class attributes) using the new module. As in certain other languages starting with "P", not everything you /can/ do in Python is actually very useful, or necessarily a good idea. Gerhard -- mail: gerhard bigfoot de registered Linux user #64239 web: http://www.cs.fhm.edu/~ifw00065/ OpenPGP public key id AD24C930 public key fingerprint: 3FCC 8700 3012 0A9E B0C9 3667 814B 9CAA AD24 C930 reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b'))) From fperez528 at yahoo.com Wed Sep 4 17:37:08 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Wed, 04 Sep 2002 15:37:08 -0600 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 4) References: <448A0F008E0AFE11.19B9EF86BEE2B191.107D5020B234F743@lp.airnews.net> Message-ID: James Kew wrote: > I can't persuade Google to find this message-id; any chance of a link? google_groups('comp.lang.python anansispaceworks.com')[0] Cheers, f. From peter at engcorp.com Fri Sep 13 21:38:55 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 13 Sep 2002 21:38:55 -0400 Subject: transform list of int in a list of string?? References: <3d8290af$1@news.sentex.net> Message-ID: <3d82931e@news.sentex.net> Peter Hansen wrote: > jubafre at brturbo.com wrote: > >> my program have other modules imported, like re and sre and i put a >> convertion int to str but doesn?t work >> t=str(x[i]) >> Traceback (most recent call last): >> File "C:\Documents and Settings\jubafre\Desktop\montador\teste.py", >> line 78, in ? >> t=str(x[i]) >> TypeError: 'list' object is not callable > > > This error is most likely because you created a list object > bound to the name "str". Do *not* use "str" or other such > reserved names as variable names if you want to preserve your > sanity. :-) More on this: they're not really "reserved", just built-in names that your local definitions will hide if you aren't careful. To see the full list: >>> import __builtin__ >>> dir(__builtin__) ['ArithmeticError', 'AssertionError', ....... 'xrange', 'zip' ] Also, you can safely use them if you know what you're doing and decide you really do want a variable with that name, but obviously you can't use the built-in function with the same name if you do so. -Peter From sismex01 at hebmex.com Thu Sep 12 13:51:09 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Thu, 12 Sep 2002 12:51:09 -0500 Subject: ANN: Thinking in Tkinter Message-ID: > > True. It would help if the command callback sent an arguement > that identified the widget (making it look a bit more like an > event binding). In any event, it doesn't and command is > unfortunately still the best way to handle button widgets. > Do something like this: # This is a kinda "ordinary" callback class. class Callback: def __init__(self, function, *args, **kw): self._args = args self._kw = kw self._func = function self._button = button def __call__(self): return self._func(*self._args, *self._kw) # And, when you define the button, do something like: btn = Tkinter.Button(someframe, label="huuuge peeectorall muscels") btn["command"] = Callback(some_func, btn, any-other-args) # When "btn" is clicked on, the first argument in some_func # will be btn. Good luck! -gus -- -- please disregard offensive and arrogant legalese. :-( > In general Tkinter has several useful callback mechanisms, > each of which > is especially easy to use for a particular type of problem > and may be a > headache for other sorts of problems (e.g. events to simulate button > command). Examples (aside from Button command): > > Event binding examples: > - Use mouse button events to do useful things in the Canvas > widget. For > instance you can easily drag objects around by binding to > and > . Or show information when the pointer is near an > object on a > Canvas using . > - Use keyboard events to modify the behavior of Entry widgets, for > example bind to the return keyto accept the data and use it > somehow, or > bind to up-arrow and down-arrow to implement a history mechanism. > > Variable trace: > - To implement input validation in Entry widgets, specify a > textvar and > put a trace on the variable. In your callback beep and > restore the old > value of the variable if the proposed new value is invalid. > > There are others. My Tkinter Summary > section > "Events and Callbacks" has what I believe is a complete set though > without examples. I'm should take another look at it and > expand it a bit. > > -- Russell > -- > http://mail.python.org/mailman/listinfo/python-list > Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From anton at vredegoor.doge.nl Fri Sep 20 14:17:04 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Fri, 20 Sep 2002 20:17:04 +0200 Subject: bit operations ? References: Message-ID: On Fri, 20 Sep 2002 16:40:18 +0200, "Shagshag13" wrote: >i'm looking for any libs which could handle bit operations on integer. >(i must be able to get 0 to n bits from any int., only bit j, etc.) If you're interested in setting/getting a lot of bits of a long integer at once, this might be faster than bitshifting. I am not guaranteeing that it is failsafe, or even that it is fast. Just hobby programmer code I wrote when I was chasing phantoms. It works only for long integers >= 0L now, but this should be easy to correct. The two functions are reciprocal, so if bits are set with the setbits function the getbits function does the reverse. Anton. #bitset.py test script from time import time import dis #list of bit positions that are set to one bitget ={'0' : [], '1' : [0], '2' : [1], '3' : [0,1], '4' : [2], '5' : [0,2], '6' : [1,2], '7' : [0,1,2], '8' : [3], '9' : [0,3], 'A' : [1,3], 'B' : [0,1,3], 'C' : [2,3], 'D' : [0,2,3], 'E' : [1,2,3], 'F' : [0,1,2,3]} #f.e. if bit at position 1 is set, '8' changes to 'A' etc. bitset = { '0' : ['1','2','4','8'], '1' : ['1','3','5','9'], '2' : ['3','2','6','A'], '3' : ['3','3','7','B'], '4' : ['5','6','4','C'], '5' : ['5','7','5','D'], '6' : ['7','6','6','E'], '7' : ['7','7','7','F'], '8' : ['9','A','C','8'], '9' : ['9','B','D','9'], 'A' : ['B','A','E','A'], 'B' : ['B','B','F','B'], 'C' : ['D','B','E','C'], 'D' : ['D','F','D','D'], 'E' : ['F','E','E','E'], 'F' : ['F','F','F','F'] } def setbits(ilist): #set bits at the positions defined in ilist, #returns a long integer dd,m = divmod(max(ilist),4) if m: dd+=1 res = ['0'] * (dd+1) for x in ilist: d, m = divmod(x,4) i = dd-d res[i] = bitset[res[i]][m] return long(''.join(res),16) def getbits(along): #return a list of integers corresponding to the #bitpositions that are set h = hex(along)[2:-1] res = [] i = 0 for j in range(len(h)-1,-1,-1): for pos in bitget[h[j]]: res.append(i+pos) i+=4 return res def test(): n =1000 a = 2349384569856987569824652587349873498723498L b = getbits(a) t=time() for i in range(n): getbits(a) print time()-t t=time() for i in range(n): setbits(b) print time()-t print setbits(b) == a # print dis.dis(setbits) # print dis.dis(getbits) if __name__ == '__main__': test() From see_reply_address at something.invalid Tue Sep 17 21:13:53 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 18 Sep 2002 13:13:53 +1200 Subject: how to cast an instance id References: <3D86E888.90AF569@millfilm.co.uk> Message-ID: <3D87D351.5090508@something.invalid> Eric Texier wrote: > It there a way to create a new reference of an object > from the string representation of its id? No. Python does not provide a way to do this, because in general it's impossible -- the original object might not exist any more. You'll have to keep a reference to the object and provide a way to get back to it. E.g. a dictionary mapping id numbers to objects. > Now, I would like to give the user some way to save > preference If you're trying to preserve an object from one Python session to another, take a look at the "pickle" module. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bokr at oz.net Wed Sep 4 15:15:42 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2002 19:15:42 GMT Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <4pid9.5883$e5.1033514@newsb.telia.net> Message-ID: On Wed, 04 Sep 2002 07:14:08 GMT, "Fredrik Lundh" wrote: >Bengt Richter wrote: > >> I agree about new syntax, but I wouldn't mind having a re.help(regexp) function >> for interactive use that would just explain in 'English' what the regexp expression >> stands for. > >you can ask SRE to dump the internal parse tree >to stdout: > >>>> sre.compile("[a-z]\d*", sre.DEBUG) >in > range (97, 122) >max_repeat 0 65535 > in > category category_digit > >turning this into 'English' is left as an exercise etc. > Interesting, thanks. Does the above mean that sre can't fully match 'a'+'9'*65537 ? Regards, Bengt Richter From pyth at devel.trillke.net Sat Sep 28 16:46:45 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sat, 28 Sep 2002 22:46:45 +0200 Subject: Best way to create a class dynamically on the fly? In-Reply-To: ; from Oschler@earthlink.net on Sat, Sep 28, 2002 at 06:37:13PM +0000 References: Message-ID: <20020928224645.T30315@prim.han.de> Robert Oschler wrote: > What is the best way to create a Python class dynamically at runtime? A > sample or doc would be great. I'm a veteran C++ programmer so this concept > is very alien to me as you can imagine (dynamically created classes). An > example that would show the creation of a descendant (sub-class), and a > another example showing the creation of an ancestor class would be perfect. Chances are you don't need dynamically generated classes. python is naturally dynamical. When i came from C++ to python i came up with using 'exec' followed by a dynamically generated string defining the function. Another way is to use the new - module, e.g. >>> c = new.classobj('myclass', (),{}) >>> c >>> >>> c() <__main__.myclass instance at 0x82e8b2c> >>> exec "def f(self): return 15" # dynamically create the string >>> setattr(c,'func',f) >>> c().func() 15 If you describe the actual problem we might be able to give you a better solution than "compilation at runtime". regards, holger From pedronis at bluewin.ch Thu Sep 5 06:09:17 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Thu, 5 Sep 2002 12:09:17 +0200 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> <3d765ce6_4@news.bluewin.ch> <3d767c4a$1_1@news.bluewin.ch> Message-ID: <3d772e4c_3@news.bluewin.ch> Robin Becker wrote in message YWyHyIAJKyd9EwHA at jessikat.demon.co.uk... > In article <3d767c4a$1_1 at news.bluewin.ch>, Samuele Pedroni > writes > > > >Robin Becker wrote in message > >zzKd7KAqhnd9EwxT at jessikat.fsnet.co.uk... > >> ..... > >> it, test_pdfbase_ttfonts.py doesn't look as though it's doing anything > >> particularly odd, certainly I see no references to system/spawn in > >> there. > >> -- > > > >have you tried my little program with your JVM. > > > >If my program work as for me, that means that your py plus jython trigger a > >bug of the JVM, because anyway and in any case the JVM ought to scream "out > >of memory" well before eating a 1GB of memory. > > > >regards. > > > > > OK here's the results with outofmem > > C:\jython-2.1\reportlab\test>javac outofmem.java > > C:\jython-2.1\reportlab\test>java outofmem > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > 10 > 11 > Exception in thread "main" java.lang.OutOfMemoryError > > > Is it possible I'm using a wrong java engine somewhere? At this point I'm really puzzled. To double check for the java engine you are using you can you can use something like this in the test code you are running (Jython code): import sys print sys.registry.getProperty('java.version') print sys.registry.getProperty('java.vm.vendor','???'),sys.registry.getProperty('j ava.vm.version','???') From spam at ob_scure.dk Fri Sep 6 06:04:05 2002 From: spam at ob_scure.dk (Thomas Jensen) Date: Fri, 06 Sep 2002 12:04:05 +0200 Subject: Using Python to call a DCOM server - "'Class not registered" Message-ID: <3D787D95.9000907@ob_scure.dk> Hi, I'm sorry if this post is somewhat OT, please direct me to the correct group if it is. I'm having some trouble using win32all to call a DCOM server. win32all includes a file called testDCOM.py which contain the lines: clsctx = pythoncom.CLSCTX_SERVER & ~pythoncom.CLSCTX_INPROC_SERVER ob = win32com.client.DispatchEx("Python.Interpreter", serverName, clsctx=clsctx) substituting serverName with "localhost" works fine and I get the extepcted "error": Error: The object created on server 'localhost' reported its name as 'MJOELNER' However when I substitute "Python.Interpreter" with my own component, I get a "Class not registered" error. Code that works: batch = win32com.client.Dispatch("IGBatchNGBackend.IGBatch") Code that doesn't work: clsctx = pythoncom.CLSCTX_SERVER & ~pythoncom.CLSCTX_INPROC_SERVER batch = win32com.client.DispatchEx("IGBatchNGBackend.IGBatch", 'localhost', clsctx=clsctx) The traceback is: Traceback (most recent call last): File "test01.py", line 30, in ? test() File "test01.py", line 15, in test batch = win32com.client.DispatchEx("IGBatchNGBackend.IGBatch", 'localhost', clsctx=clsctx) File "C:\PROGRA~1\PYTHON22\lib\site-packages\win32com\client\__init__.py", lin e 109, in DispatchEx dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, serverInfo, (py thoncom.IID_IDispatch,))[0] pywintypes.com_error: (-2147221164, 'Class not registered', None, None) Thanks in advance -- Best Regards Thomas Jensen (remove underscore in email address to mail me) From martin at v.loewis.de Thu Sep 19 02:46:27 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 19 Sep 2002 08:46:27 +0200 Subject: Python as shared library on Unix References: Message-ID: "Rolf Kalbermatter" writes: > There is probably little chance that this will be officially backported > to the 2.2.1 branch of Python? No, there is no such chance. Regards, Martin From max at alcyone.com Sun Sep 1 17:43:11 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 01 Sep 2002 14:43:11 -0700 Subject: del(instance.attr) -- no attribute References: Message-ID: <3D7289EF.CE162C2D@alcyone.com> Lee Harr wrote: > Is this a bug? > > >>> class C: > ... a = 1 > ... > >>> c = C() > >>> c.a > 1 > >>> del(c.a) > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: C instance has no attribute 'a' > >>> hasattr(c, 'a') > 1 > >>> > > I can see that maybe del(c.a) should not be allowed to delete > the attribute, but I think the error message is misleading. Well, to its credit, it _does_ say that the _instance_ doesn't have the attribute, which is precisely what the problem is. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From wayne at tbnets.com Sun Sep 8 07:52:56 2002 From: wayne at tbnets.com (Wayne R) Date: Sun, 8 Sep 2002 07:52:56 -0400 Subject: python program to watch a file - example. In-Reply-To: <3d7b3437$0$12727@echo-01.iinet.net.au> Message-ID: <004701c2572e$5738af40$02010a0a@hackncodexp> Sorry for the html, I forgot to turn it off (as I usually turn it off as soon as I install a new system, forgot this time). The platform is Gentoo Linux, I am writing a piece of code for the Twiggi project to patch in adduser support. |-> > >I am trying to write a python program that will run as a deamon and |-> > >watch a file for data to arrive and then wake up and perform duties |-> on |-> > >that data. I found ways to make a python program run as a deamon |-> but I |-> > >am at a loss to find anything related to watching a file for data so |-> > >that it can then process the data. I didn't really want to do a |-> sleep |-> > >loop or something like, I am sure there is a better way. |-> > > |-> > >Any ideas or links to more info? |-> > > |-> > Don't annoy people you want help from, for starters. |-> > What system are you targeting? (Outlook in the headers says you're on |-> windows |-> > generating this abominable mix of actual message and useless cruft). |-> > [Wayne R] From duncan at NOSPAMrcp.co.uk Mon Sep 16 06:22:38 2002 From: duncan at NOSPAMrcp.co.uk (Duncan Booth) Date: Mon, 16 Sep 2002 10:22:38 +0000 (UTC) Subject: representing a literal single slash References: <3D84E9F9.8090101@linux.ie> <3D84FEE6.90600@linux.ie> Message-ID: Padraig Brady wrote in news:xZhh9.4239$cP3.10322 at news.iol.ie: >> Specifically, a raw string cannot end in a single backslash (since > > the backslash would escape the following quote character) > > But there is no escaping when the prefix r is used? > I guess there is a good reason for this inconsitency? There is escaping with the prefix r: backslash followed by a quote escapes the quote into the string, but leaves the backslash in the string. Whether this is a good reason depends on your viewpoint. Whether there is good reason for raw strings is also arguable: raw strings do not permit you to do anything that you could not do with non-raw strings, they violate the 'one way to do it' rule, and they are confusing. They do make it easier to write regular expressions, and a regular expression couldn't end in a single backslash anyway. If you only ever use raw strings for regular expressions then you are unlikely to have problems[1]. They are often misused to write DOS pathnames, which may end in a backslash. [1] Unlikely to have problems with the raw strings that is. Problems with regular expressions are likely. -- Duncan Booth duncan at rcp.co.uk int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? From wganz at texoma.net Sat Sep 7 10:00:28 2002 From: wganz at texoma.net (Will Ganz) Date: Sat, 7 Sep 2002 09:00:28 -0500 Subject: (slightly OT): Python and linux - very cool In-Reply-To: Message-ID: <012b01c25676$ebe9e860$0202a8c0@WorkGroup> > them first. That does serve to make badly coded Perl look *absolutely* > awful, but it is also a great benefit. > And you throw into the mix the fact that the 'Perl poet' has zero experience in design, you will have a mess that no one can figure out. Couple that with the desire to reach Perl Wizard status by playing Perl golf to cram as much as possible into one line of code as if any optimizing compiler wouldn't do that anyway. Jeepers, I don't have enough digital ink in my cursor to write all the horror stories that I could tell about that. The company that I work for has Perl modules that are 5 years old that no one dares to touch. They are stuck using Perl 5.04 since that is the latest version that it will run. That is why I rebeled and use Python for my projects. No more unmaintainable code. I still use Perl, but only when it will fit in under 100 lines of code. Just my view from the bottom of the fishbowl. Will "We never gave up, and we never will. In the end, if that's all they can say about us, it'll do." From sschwarzer at sschwarzer.net Sun Sep 1 17:32:13 2002 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Sun, 01 Sep 2002 23:32:13 +0200 Subject: Add methods to a class at runtime? References: <9pqc9.30220$vY2.574504@e3500-atl2.usenetserver.com> Message-ID: <3D72875D.9040308@sschwarzer.net> Hello Robert Robert Oschler wrote: > Thanks but I need a little bit more detail. Suppose I want to do it from > within code? For example, I create a function called > AddBarToFoo(FooObject), that given a object of type Foo (FooObject) adds the > Bar method to it dynamically, what would be the syntax then? Would I have > to put the method declaration code, which you show being typed in to the > interpreter, in a string and then eval/exec it? Is there a more convenient > way than that? There was a thread on this some time ago: http://groups.google.de/groups?hl=de&lr=&ie=UTF-8&oe=UTF-8&th=9a6dcf6380b7afe0&seekm=Xns91D662196C970duncanrcpcouk%40127.0.0.1&frame=off Maybe that is helpful. :) Stefan From fredrik at pythonware.com Thu Sep 5 02:41:14 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Sep 2002 06:41:14 GMT Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <4pid9.5883$e5.1033514@newsb.telia.net> Message-ID: Bengt Richter wrote: > >you can ask SRE to dump the internal parse tree > >to stdout: > > > >>>> sre.compile("[a-z]\d*", sre.DEBUG) > >in > > range (97, 122) > >max_repeat 0 65535 > > in > > category category_digit > > > >turning this into 'English' is left as an exercise etc. > > Interesting, thanks. Does the above mean that sre can't fully match > 'a'+'9'*65537 > ? in this context, 65535 represents any number: >>> import re >>> p = re.compile("[a-z]\d*") >>> s = "a"+"9"*65537 >>> len(s) 65538 >>> m = p.match(s) >>> len(m.group(0)) 65538 From mhammond at skippinet.com.au Tue Sep 17 23:00:03 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 18 Sep 2002 03:00:03 GMT Subject: COM object registration References: Message-ID: dsavitsk wrote: > if the module below is run from the command line, it registers and works > fine. if, however, it is imported and the register() method is executed it > does not work (giving a 'localserver' error). What doesn't work? Registration or subsequent use of the object? Can you be more specific about the error you got, or else attach code I can run without modification to see the error. Thanks, Mark. From creyes at ea.com Fri Sep 13 12:44:22 2002 From: creyes at ea.com (Christian Reyes) Date: Fri, 13 Sep 2002 09:44:22 -0700 Subject: Problem with HTTPS request References: Message-ID: I'm on Win 98. i don't have a development env in which to build the python socket module. was hopoing someone could point me to somewhere i could find a premade one. Thanks though, if you could point me to a site or two, that'd be great' Jeremy Hylton wrote in message news:b0f083db.0209130558.2aa60398 at posting.google.com... > "Christian Reyes" wrote in message news:... > > I got the following response when trying to make an HTTPS request. > > > >

SSL required to access this page

> > > > Then I read in the documentation the following > > > > Note: HTTPS support is only available if the socket module was compiled with > > SSL support. > > > > Does anyone know where i can get my hands on a socket module that was > > compiles with SSL support? > > What platform are you running? Many people compile such a socket > module themselves. If that isn't an option, you'll have to look at > binary packages for your platform. > > Jeremy From tjreedy at udel.edu Tue Sep 10 16:40:46 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 10 Sep 2002 20:40:46 GMT Subject: Reset a generator function? References: <%Lrf9.30107$w51.7961593@news2.news.adelphia.net> Message-ID: "Robert Oschler" wrote in message news:%Lrf9.30107$w51.7961593 at news2.news.adelphia.net... > How can I reset a generator function so that it begins yielding values as it > did when first called? The generator function does not really yield values. It returns an iterator that yields values. This is handled transparently by the for loop mechanism. The iterator cannot be reset. The generator can be called again, with either the same or different arguments, to return a new iterator that will yield the same or different sequence. It can even be called again before you use the first iterator to get any values. Terry J. Reedy From huaiyu at gauss.almadan.ibm.com Wed Sep 4 14:16:07 2002 From: huaiyu at gauss.almadan.ibm.com (Huaiyu Zhu) Date: Wed, 4 Sep 2002 18:16:07 +0000 (UTC) Subject: default tuple unpacking? References: <3d758180$1@news.sentex.net> <3d7584d2$1@news.sentex.net> Message-ID: Peter Hansen wrote: >Peter Hansen wrote: >> Huaiyu Zhu wrote: >> >>> It is often very convenient to have default arguments such as >>> >>> def func(a, b, *c): ... >>> >>> Is there a way to use this in statements too? Examples: >>> >>> a, (b, *c), *d = e > >Hmm... I think there might be an inconsistency or an unexpected >result in this. What if e already contains a tuple? Bengt Richter and Bernhard Herzog have already given two different answers to this question. Both are consistent in themselves. I feel that Bengt's answer is more elegant, but it runs againt the Python syntax rule that tuples are made from commas instead of parentheses. Bernhard's answer can easily fit in the current syntax. I'll expand it in more detail to make sure there is no ambiguity. Consider def func0(*a): return *a def func1(a, *b): return a, *b def func2(a, b, *c): return a, b, *c For func in [func0, func1, func2], the following are equivelant x, y, *z = func(a, b, *c) x, y, *z = a, b, *c For func in [func0, func1], the following are equivelant x, *y = func(a, *b) x, *y = a, *b For func in [func0, func1], the following are equivelant x, = func(a) x, = a, The following are always equivelant *x = func0(*a) *x = *a x = tuple(a) Let's see if this works for all your examples: > > e = (1, 2, 3) > *a = e # a is ((1, 2, 3), ) This is equivalent to a = e # a = 1,2,3 This equivalence may look disturbing, but I can't think of any trouble it might cause. Following are more equivelences of this sort a = *e *a = *e a = 1, 2, 3 *a = 1, 2, 3 a = *(1, 2, 3) *a = *(1, 2, 3) > >That seems sensible, and it's just what happens if you pass >"e" in to a function defined as "def func(*a)". This is equiv to *a = e, # a = (1,2,3), > >Now what about this: > > a, *b = e # a is 1, b is (2, 3) > Yes. >That's one possible result, and presumably the one you want with >this syntax, but it's not what you'd get with the function syntax: > > def func(a, *b): > print a > print b > > func(e) That's a, *b = e, # a = 1, 2, 3; b=() > >Here of course you get (1, 2, 3) in "a" and () in b. To get the >same as the proposed syntax above, you can't pass in a tuple, but >have to pass the parameters separately: > > func(1, 2, 3) # now a is 1, b is (2, 3) That's a, *b = 1, 2, 3 # a = 1; b = 2,3 > >The problem is that in function calling, you can pass in a single >tuple, which is one argument, or you can pass the elements separately >as multiple arguments, which is when the special * syntax kicks in. Always think of function arguments as a tuple. If the argument is a single tuple, then the args is simply a single-element tuple whole element happens to be a tuple. Huaiyu From hellprout at yahoo.com Fri Sep 20 18:12:32 2002 From: hellprout at yahoo.com (hellprout) Date: 20 Sep 2002 15:12:32 -0700 Subject: pyrhon and oracle Message-ID: <5b8834c2.0209201412.50e77861@posting.google.com> hi , i just want to have some detail about python and oracle what ca i use to query oracle with python ? i jsut want a little exemple thanks From lbrannma at cablespeed.com Sun Sep 22 20:57:17 2002 From: lbrannma at cablespeed.com (Lance) Date: Sun, 22 Sep 2002 17:57:17 -0700 Subject: more on weak typing.. Message-ID: I found this on the Dive Into Python site: statically typed language A language in which types are fixed at compile time. Most statically typed languages enforce this by requiring you to declare all variables with their datatypes before using them. Java and C are statically typed languages. dynamically typed language A language in which types are discovered at execution time; the opposite of statically typed. VBScript and Python are dynamically typed, because they figure out what type a variable is when you first assign it a value. strongly typed language A language in which types are always enforced. Java and Python are strongly typed. If you have an integer, you can't treat it like a string without explicitly converting it (more on how to do this later in this chapter). weakly typed language A language in which types may be ignored; the opposite of strongly typed. VBScript is weakly typed. In VBScript, you can concatenate the string '12' and the integer 3 to get the string '123', then treat that as the integer 123, all without any explicit conversion. So Python is both dynamically typed (because it doesn't use explicit datatype declarations) and strongly typed (because once a variable has a datatype, it actually matters). From barry at python.org Fri Sep 13 11:48:40 2002 From: barry at python.org (Barry A. Warsaw) Date: Fri, 13 Sep 2002 11:48:40 -0400 Subject: RELEASED email package version 2.3 References: <15742.47445.811488.515719@anthem.wooz.org> Message-ID: <15746.2264.790325.57188@anthem.wooz.org> >>>>> "BAW" == Barry A Warsaw writes: BAW> I've just released the (standalone) email package version BAW> 2.3. This is identical to the version that is in the current BAW> cvs development tree for Python 2.3. It is made available as BAW> a distutils package for installing in earlier versions of BAW> Python. It is compatible with Python 2.1.3 and Python 2.2.1. BAW> email-2.3.tar.gz is available from the mimelib project on BAW> SourceForge: BAW> http://sf.net/projects/mimelib/ Sorry folks, the email-2.3.tar.gz package was missing one of the test suite files. You'll notice this if you ran "python testall.py" and saw failures due to the missing file msg_31.txt. I've just released email-2.3.1.tar.gz which contains the missing file. There are no other substantive changes in this micro release so if you don't care about the test suite, there's no need to update. -Barry From whisper at oz.net Thu Sep 12 05:31:44 2002 From: whisper at oz.net (David LeBlanc) Date: Thu, 12 Sep 2002 02:31:44 -0700 Subject: [FEEDBACK] Is this script efficient...is there a better way? In-Reply-To: <20020912074400.GA22578@hishome.net> Message-ID: > Have you actually tested this? I used to believe that larger buffers are > always better for performance. > > Wrong. > > I ran some test on Linux for the effect of buffer size on file reading > speed and the results were very interesting. I started with a buffer size > of 32 bytes, tested file I/O throughput and increased it > logarithmically by > about 2% for each step. As expected, the time to read 1mb improved as the > buffer size increased until it hit a minimum for a buffer size of around > 4-8k (the graph is very noisy so it's hard to tell) and then rose back up > to a value that is 10-20% worse for buffer sizes of 32-64k and remained > more-or-less constant for anything higher. > > This performance curve may be a result of the CPU cache or the OS > architecture. > > The chunk size used by xreadlines is 8k which is about the optimum > value (at least for linux). > > Oren Disk cluster size? Fragmentation? Dave LeBlanc Seattle, WA USA From apederse at hotmail.com Fri Sep 27 04:09:48 2002 From: apederse at hotmail.com (Asle) Date: 27 Sep 2002 01:09:48 -0700 Subject: imap handler for urllib Message-ID: Has anyone out there made an imap handler for urllib?? There is an IMAP url scheme described in RFC 2192. regards, Asle From gregory.p.green at boeing.com Fri Sep 20 12:57:07 2002 From: gregory.p.green at boeing.com (Greg Green) Date: Fri, 20 Sep 2002 16:57:07 GMT Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> Message-ID: "A.M. Kuchling" writes: > In article <3d88fd1e at news.ivm.net>, Nenad Propadovic wrote: > > -I assume the simplest way to present a graph/chart kind of graphic is to > > create a jpg/giff/tiff on the server side, and just show it on the client? > > Yes. PIL, the Python Imaging Library, would be one possibility; so is > the gd module. For example, the pricing charts on the pages at > http://www.mems-exchange.org/catalog/ are generated from Quixote using > gd. PDF likely isn't helpful, because browsers won't display PDF > images inlined in a web page, though it's certainly well-suited for > multi-page reports that need to be printed. Another possibility, which I have used, is gnuplot. This has an option of creating image files as output instead of the dedicated window. Works very well. -- Greg Green From jepler at unpythonic.net Mon Sep 16 21:01:30 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Mon, 16 Sep 2002 20:01:30 -0500 Subject: pickle magically not working In-Reply-To: <3d865dac@nntp.server.uni-frankfurt.de> References: <3d865dac@nntp.server.uni-frankfurt.de> Message-ID: <20020916200130.A2484@unpythonic.net> On Tue, Sep 17, 2002 at 12:39:40AM +0200, Michael Janssen wrote: > Hello > > at least i've solved it (as a workaround), but it's pretty annoying. > Maybe someone has an answere :-) It's a bug, apparently. It's fixed in Python 2.3's CVS versions. The tuple returned from time.localtime() is newly a 'time.struct_time' (since version 2.2), not actually a tuple. pickle can't handle this. So much for the addition of named fields to tuples being "zero impact"! If I had to guess, I'd say the "fix" was in Pickle itself, you might turn something up by investigating Python's CVS tree. Or somebody else might be able to immediately indicate the relevant code... Until then, slicing the value will work -- slicing returns a pure tuple. Jeff From noreply at sourceforge.net Wed Sep 4 21:31:27 2002 From: noreply at sourceforge.net (Bruce Dodson) Date: Wed, 4 Sep 2002 22:31:27 -0300 Subject: Jython and .NET? Message-ID: I'm thinking about Python.NET. Then I'm thinking about Jython, and also about the J#.Net compiler that arrived at work recently. Can someone from the Jython camp comment whether it would be feasible to port Jython to J#? That is, how closely tied is Jython to the Java virtual machine and class format? (In interpreted mode, vs. in compiled mode.) Thanks, bruce From 2002 at weholt.org Mon Sep 23 05:09:52 2002 From: 2002 at weholt.org (Thomas Weholt) Date: Mon, 23 Sep 2002 09:09:52 GMT Subject: UpToDate SOAP-module ?? Message-ID: I've looked around for a SOAP-module to use in a WebService-based project, but the SOAP-implementations in python seem to be a bit ... unstable ?? Some of them haven't been updated for a while etc. so I wondered what people think is the most up to date and "best" module for providing SOAP-based WebServices which includes client-side code too. Any opinions, hints or ideas are welcome. Thoughts on ease of use, list of features, comparisons etc. are also interesting. Best regards, Thomas From aleax at aleax.it Thu Sep 26 09:36:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 13:36:16 GMT Subject: Is there a way to find the name of the method currently being executed? References: Message-ID: Craeg K Strong wrote: > Hello: > > class a: > > def func1(self): > print "func1 being called" > > def func2(self): > print "func2 being called" > > In the code sample above, I would like to replace the "func1" > and "func2" strings with constants so the same code could > be copied verbatim into multiple functions and do the right > thing. > > Is there a way to do this in Python? For example, maybe you could > get your hands on the call stack and print out stack[0].__name__ > or something.... Right, that's exactly what I did in: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 except that sys._getframe (gets one frame of the call stack, not all of the stack at once) is what the recipe uses (as usual, the version in the printed Cookbook, published by O'Reilly, has better discussion, &c). Alex From brueckd at tbye.com Mon Sep 9 22:45:38 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Mon, 9 Sep 2002 19:45:38 -0700 (PDT) Subject: IDLE In-Reply-To: Message-ID: On Tue, 10 Sep 2002, Ali K wrote: > Why won't my IDLE work? I just tried it on your machine and it works fine. Thanks, Dave From max at alcyone.com Tue Sep 17 17:21:37 2002 From: max at alcyone.com (Erik Max Francis) Date: Tue, 17 Sep 2002 14:21:37 -0700 Subject: subclassing tuple References: Message-ID: <3D879CE1.EDB15467@alcyone.com> Douglas Zongker wrote: > Is there any way to create a subclass of 'tuple' that has a customized > constructor? You want to use the .__new__ method: http://www.python.org/2.2/descrintro.html#__new__ -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ It's like being on a diving board that you know is too high. \__/ Sade Adu Kepler's laws / http://www.alcyone.com/max/physics/kepler/ A proof of Kepler's laws. From sismex01 at hebmex.com Fri Sep 6 10:08:57 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Fri, 6 Sep 2002 09:08:57 -0500 Subject: Difference between static method and a function as a class at tribute? Message-ID: > > Hi, > > What are the differences, if any, between 1 and 2? > > 1. > def funtest(*args): > pass > > class test(object): > method = funtest > > 2. > class test(object): > def funtest(*args): > pass > > method = staticmethod(funtest) > > > And if there are any differences do they really matter, that is, does > anybody has any test cases where 1 and 2 are not interchangeable? > > TIA and all the best, > Gon?alo Rodrigues Take a look at this: >>> class testclass: ... pass ... >>> >>> def functest(*args): ... print args ... >>> >>> testclass.testmethod = functest >>> >>> inst = testclass() >>> dir(inst) ['__doc__', '__module__', 'testmethod'] >>> >>> inst.testmethod() (<__main__.testclass instance at 0x013A5020>,) >>> Any "plain" executable found as an attribute of a class object, upon creating an instance of that class, is bound to the instance as a method. If not, then calling "inst.testmethod()" should display an empty tuple. I suspect that staticmethod(func) and classmethod(func) wrap the function in a proxy which first extracts some info from the actuall call (say, the instance's class) and pass *whose* arguments to the real function. Neat. A tribute to Python's true power, that you can do that and not pollute the language with wierd "special cases" and such. -gus -- Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From DennisR at dair.com Thu Sep 26 18:40:14 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Thu, 26 Sep 2002 22:40:14 GMT Subject: distributing apps w/embedded python & missing modules References: Message-ID: > My question: Is there an easy way > to compile all of Python's modules into the app so that the user does not > need to separately download the core python package? At http://www.autorunning.com/arpyexe.cgi I have pre-compiled 24 modules plus the core executables in a 432 K Windows package. The user can specify 3 more modules. Now I could have included all 167 of the lib modules but the total library size is 1.92 Mb (pre-compression). So, I think the answer is "yes, it is easy". It is not clear to me where you have gotten so far and what is roadblock you are facing. Let me describe what I do. Perhaps this will help. I compress the files described on my web page above into a self-extracting executable. This executable is then embedded in non-Python code and extracted into a temp file at run time. Control is now turned over to Python. hth. -- Dennis Reinhardt http://www.dair.com From tjreedy at udel.edu Sat Sep 7 18:05:49 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 07 Sep 2002 22:05:49 GMT Subject: None or 0 References: Message-ID: <0Lue9.503203$2p2.20193233@bin4.nnrp.aus1.giganews.com> To summarize Tim's thorough answer: the language reference guarantees (specifies) the short-circuit behavior that you discovered. It also guarantees that > a = a or b is *not* equivalent to > if a is None: a = b unless *you* can guarantee that 'a' will never have a null value other than None. I add: as far as I know, both have been true since the beginning and will remain true thru the 2.x series. I would be extremely surprised if anything changed thereafter. Terry J. Reedy From bokr at oz.net Mon Sep 2 00:58:46 2002 From: bokr at oz.net (Bengt Richter) Date: 2 Sep 2002 04:58:46 GMT Subject: stylistic question -- optional return value References: <20020828145828.19131.h014.c001.wm@mail.dougfort.net.criticalpath.net> Message-ID: On Thu, 29 Aug 2002 13:37:26 GMT, Andrew Koenig wrote: >Roy> It's also virtually always true that the real way to speed up a >Roy> program is not code tweaking, but using better algorithms. > >Like most generalizations, this one is not always true. > >Remember, we're talking here about an interface decision, which >means that changing it after the fact is difficult. Moreover, >this particular program is going to involve a large number of recursive >function calls, every one of which will use this mechanism to pass >information back to its caller. In this case, therefore, the choice >of interface will have a substantial effect on the execution speed >of the whole program, and it will be difficult to change it later. > >In such circumstances, a factor of three is too much to ignore. I am >not saying that the faster interface is always the right one, but I am >saying that when there's a large speed difference, and the decision >will be difficult to change later, then there had better be a >substantial argument in favor of the slower alternative. Which >I don't think there is in this case. > If added information is the exception (;-) rather than the rule, you might want to consider using an exception to return the unusual bag of data. try: is supposed to be low overhead, and the payoff is a clean main path of excution, using the retval as-is normally, without having to test or index into a tuple etc., and without having to pack a tuple for a normal return value from the routine. You can define your own exception and raise it with an arbitrary set of args, e.g., >>> class MyExceptionalData(Exception): ... pass ... >>> try: ... raise MyExceptionalData('x value', 'optional y') ... except MyExceptionalData, mxd: ... print mxd ... ('x value', 'optional y') >>> mxd <__main__.MyExceptionalData instance at 0x007A2460> >>> dir(mxd) ['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args'] >>> mxd.args ('x value', 'optional y') >>> mxd[0] 'x value' >>> mxd[1] 'optional y' You could also give your exception class an __init__ function to set instance attributes and whatever else you'd like. Anyway, your code might look something like try: # try overhead only x = foo() # use x knowing single return value assumption is ok except MyExceptionalData, e: x, y = e.args # use x and y according to the exceptional situation or alternatively try: # try overhead only x = foo() # use x knowing single return value assumption is ok except MyExceptionalData, e: x, y = e.args # use y here according to the exceptional situation # use x here either way as opposed to something like x = foo() if x[1] is not sentinel: # big index + test overhead in normal path x = x[0] # indexing overhead in normal path # use single value else: x, y = x # same overhead as with e.args less .args attribute lookup # use the unusual combo Regards, Bengt Richter From bokr at oz.net Mon Sep 9 21:40:08 2002 From: bokr at oz.net (Bengt Richter) Date: 10 Sep 2002 01:40:08 GMT Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> <4pid9.5883$e5.1033514@newsb.telia.net> <8vvdnucccqp2och24gigcmmc91njbjkhhk@4ax.com> Message-ID: On Thu, 05 Sep 2002 06:56:24 GMT, Ben Wolfson wrote: >On Thu, 05 Sep 2002 06:41:14 GMT, "Fredrik Lundh" >wrote: > >>Bengt Richter wrote: >> >>> >you can ask SRE to dump the internal parse tree >>> >to stdout: >>> > >>> >>>> sre.compile("[a-z]\d*", sre.DEBUG) >>> >in >>> > range (97, 122) >>> >max_repeat 0 65535 >>> > in >>> > category category_digit >>> > >>> >turning this into 'English' is left as an exercise etc. >>> >>> Interesting, thanks. Does the above mean that sre can't fully match >>> 'a'+'9'*65537 >>> ? >> >>in this context, 65535 represents any number: > >Doesn't that cause problems for something like this? > >>>> m=re.compile(r'\d{0,65535}a').match(('9'*1000000)+'a') >>>> len(m.group(0)) >1000001 > Looks like a bug to me if {0,65535} acts like {0,} BTW, a search for \d{0,65534} seems to mean it, and compiles so slowly that I lost patience waiting. Not very optimized, I guess. >>> import re >>> m=re.compile(r'\d{0,65535}a').search(('9'*1000000)+'a') >>> len(m.group(0)) 1000001 That went reasonably in time(though it's wrong), but this snoozed. It must be brute forcing something. >>> m=re.compile(r'\d{0,65534}a').search(('9'*1000000)+'a') ^C [18:50] C:\pywk\junk> Regards, Bengt Richter From gerhard.haering at gmx.de Fri Sep 13 16:04:02 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 13 Sep 2002 20:04:02 GMT Subject: Problem with HTTPS request References: Message-ID: Steve Holden wrote in comp.lang.python: > "Gerhard H?ring" wrote ... > [complaints about crappy looking posts because of people using OE] > Gerhard: > > You're showing distinct signs of having too much time on your hands :-) Unlikely. > Can't you fix your brain instead so it will let you ignore other > people's mailer problems? Problems don't go away by ignoring them. People are so used to the postings in crappy form (I'm only talking about form, not content) offloaded by people like you that they need to be alerted to this from time to time. > an-unreconstructed-OE-user-myself-ly y'rs - steve I wonder why some programmers who insist on proper form of source code don't care at all about the email/news messages they send to the public, even though they know better. And sorry, the Microsoft way of defining crap as standard won't work with me. -- Gerhard From ianb at colorstudy.com Tue Sep 17 15:18:34 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 17 Sep 2002 14:18:34 -0500 Subject: CGI question In-Reply-To: References: Message-ID: <1032290315.8037.145.camel@dsl-65-184-205-5.telocity.com> On Tue, 2002-09-17 at 13:04, John D. Boy wrote: > Now, my problem is to find out what follows behind the question mark in > my CGI script. Unless the key has a value > (http://my.domain.name/?key=value), it is not in the cgi.FieldStorage > dictionary. Is it simply impossible, or am I not using the right > function calls? Look at cgi.FieldStorage. Something like: f = cgi.FieldStorage(keep_blank_values=1) Will save these values. (I don't know why it isn't set by default... by default you shouldn't throw information away, but FieldStorage does in this case) Ian From jwpennin at bellsouth.net Wed Sep 25 23:39:36 2002 From: jwpennin at bellsouth.net (Jonathan Pennington) Date: Wed, 25 Sep 2002 23:39:36 -0400 Subject: Creating daily/monthly averages from datafiles Message-ID: <20020926033935.GA2018@fiddlersnest.org> Hello all, I've got a rather complex description/request. I'm building a program to parse and analyze data for a watershed hydrological database and am looking for some methods to steal so I don't re-code what's already been done. ################## ## Description I have some classes that iterate over text files with formats similiar to this: date,time,float,float,int,float,int,int # values every 15 minutes for # entire year, multiple years. The data often has arbitrarily length header, and non-standard delimiters. I've build a wxPython GUI to allow the user to delete header lines, then a class that builds a table with a user selected delimiter used to separate the lines into a wxGrid interface. All pretty nice. Now separate from this, I have a class that will iterate over a delimited text file and create a dictionary with keys of month number, each of which is a dictionary with keys as day, each of which is a list of readings from that day. Pretty basic. I then hacked up methods (rough, not elegant at all- and not very efficient) that will create a dictionary of values such that I can parse a datafile by the following: >>> parser = DataParser(filename) <...long wait as everything is done in __init__() method automagically...> >>> parser.DailyAverages[9][16] [43, 29, 84] >>> parser.MonthlyAverages[4] [35, 20, 76] These are fields that are static to this file (ie. the class is not very flexible as it was created to fit a specific file layout). The actual parsing methods are also very rough, iterating over an entire file to find all instances in a specific month, that sort of thing. Again, not very elegant. ################# ## Request Basically, I don't want to re-hack these average/cumtotal methods to fit working with my wxGrid-ed data. I'm looking to see if anyone has done any similiar work so that I don't have to reinvent the wheel. What I need are classes/methods that can take data from a list/grid/table and manipulate sections of that data by date/time. For instance, take all values in column 2 and perform daily averages, take all values in column 3 and perform monthly totals, take all values in column 4 and perform cumulative totals by average. Now, of course, the individual methods (ave, cumtotal, etc.) are easy. What I'd like to find is code that someone has to easily seek out all of the data by hour/day/month and return it to my manipulation method, etc. Of course, just knowing that the data is in a wxGrid is not necessarily very helpful, the underlying data structure is what would probably have to be manipulated. Is the wxGrid built from a dictionary, etc. Right now, I've just dumped the values into a subclassed wxPyGridTableBase class from the datafile, so there's no underlying dictionary or other data structure. Ideally, I'd manipulate the wxGrid directly, but don't know if that's possible/economical. I'm very open to suggestions. Does anyone know of some appropriate code, or has anyone built similiar methods for time-constrained data mining? I've searched the vaults and assorted other repositories, but nothing- on initial perusal- seems too promising. Just a couple of methods would do it really. Otherwise, I'll probably have to build a date-constrained mining class and perhaps dump that onto the Vaults for others to use for similiar tasks. Thanks all, -J From bwucew at yahoo.com Tue Sep 17 02:46:20 2002 From: bwucew at yahoo.com (Bwuce_Wee) Date: 16 Sep 2002 23:46:20 -0700 Subject: Extending a C++ App References: <996eade8.0209120912.3a653d7@posting.google.com> <996eade8.0209122352.45721938@posting.google.com> Message-ID: <996eade8.0209162246.7a281291@posting.google.com> Thanks for all your help I've been offline for a few days :) Ive been doing some more investigations, and I thought you guys might be interested in it. Firstly - like you indicated - I found the shadow class code that SWIG generates (Duh I feel stoopid) As for the DLL thing, apparently, I just need to do this: Py_Initialize(); SWIG_init(); ... Whatever I need to do (eg. PyRun_SimpleString / File) ... Py_Finalize(); The python code I run in there can then import from whatever I called my module Another thing I found was the nebula source code (nebula is a 3D game engine by radon labs - who released the source code) Nebula gave me lots to think about (Once I had gotten over my headaches from figuring out the code) PS: get ready for a long description :) Nebula opens the possibility of having one of multiple scripting languages - and easy remote scripting and serialisation. The way nebula works with python is by having a 'root' class that handles Cmd objects - which are simply wrappers for a function call (with ins and outs) Aside from this, 'root' also handles RTTI and serialisation Each child class (inheriting root) indicates which command prototypes it accepts - with ulong ID's for speed,etc. eg. AddCmd("v_MyMethod_s", 'MM ', PointerToFunction); The 'v_' indidates void and the '_s' indicates string meaning that MyMethod returns nothing and accepts a string parameter Unfortunately this *does* mean writing separate static functions for the commands the class accepts. The ScriptingServer class - this is the base class - runs/parses script commands, converts (where necessary) to Cmd objects and hands the Cmd objects to the appropriate object instances that need to handle them. So.. for instance, you could have a PythonScriptingServer and a TCLScriptingServer - each capable of converting the language into Cmd objects and handing the Cmd objects to the application. I would envisage rather having shadow classes created automatically based on a classes' list of Cmd prototypes. Those shadow classes could simply be passing Cmd commands to the scripting server to hand over to the rest of the application. In these situations, you only really need a handful of functions extended to python (eg. SendCmdMessage(ObjectID, Arguments) - ObjectID would differ according to how one identifies an object instance (void* or long ID or name,etc) This method potentially allows for remote scripting (which nebula DOES seem to allow) but Im still deciphering exactly how they did that (eg. identification of object instances is still not clear to me) Another nice side effect is serialisation Nebula uses Cmd commands to serialise and deserialise. When an object needs to be saved - it simply generates Cmd objects describing the commands necessary to reconstruct the object, and passes them to the application to save to file To deserialise, those Cmd objects simple need to be read in and passed to a newly created object to reconstitute it For a while I was brainstorming how to allow my app to optionally not use Python at all (or any scripting), but still serialise easily (eg. Pickle). However, I could not find a reasonable way of doing this - and nebula's method looks like a fair alternative as Cmd commmands could still be used outside of scripting. If you read this far - good going :) Thanks for the help and effort From grabiller at 3dvf.net Thu Sep 26 01:05:05 2002 From: grabiller at 3dvf.net (Guy Rabiller) Date: Thu, 26 Sep 2002 07:05:05 +0200 Subject: Newbie References Question References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> Message-ID: <3d929578$0$5921$79c14f64@nan-newsreader-01.noos.net> Yes you are totaly right. I'm walking toward this way anyway, but I was just confuse about this 'reference thing' ( wich was my mystake as I forgot that my 'p' was a nested list of coordinate ). Thanks for the example Frank. -- guy rabiller 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net Frank Sonnenburg wrote: > "Guy Rabiller" schrieb im Newsbeitrag > news:3d91c72f$0$8558$79c14f64 at nan-newsreader-02.noos.net... >> Hi, >> >> let say I have: >> i1 = 1 >> i2 = 2 >> and >> p = [i1,i2] >> >> How can I have: >> p=[*i1,*i2] >> rather than >> p=[**i1,**i2] as it is curently ? >> >> ( Sorry for this nasty hybrid syntax ) >> >> Textualy, how if I want that p[0] refere to the 'i1' container, and >> not to the refererence it contains ? >> >> What I want is that if now I set: >> i1 = 4 >> that automaticaly: >> p -> [4,2] >> and not keeping [1,2] > > My proposal: THINK OO! > > In my opinion, this is an excellent example to use the full power of > object oriented programming. Of course, this is a lot of overhead and > maybe you just wanted a very short approach. But since you told, you > are a newbie, maybe you are not quite used to this style of > programming. Just try out and experiment a little. > > =============================================================== > > # Module point.py > > > class Point: > def __init__(self, x=0, y=0): > self._x = x > self._y = y > > def __repr__(self): > return 'Point (%d,%d)' % (self._x, self._y) > > def short_repr(self): > return '(%d,%d)' % (self._x, self._y) > > def set(self, x, y): > self._x = x > self._y = y > > class Figure: > def __init__(self, *points): > self._points = [] > for p in points: > if not isinstance(p, Point): > raise TypeError > self._points.append(p) > > def __repr__(self): > s = 'Figure' > # Derived class instance? > classname = self.__class__.__name__ > if classname != 'Figure': > s = s + ' (%s)' % classname > if self._points: > s = s + ', def. by' > for p in self._points: > s = s + ' '+p.short_repr() > else: > s = s + ', no points defined' > > return s > > > # > # Now it's your turn ;-) > # > > # def set, get, remove, ...... > # ... > > > class Quad(Figure): > def __init__(self, p0=Point(0,0), p1=Point(0,1), > p2=Point(1,0), p3=Point(1,1)): > Figure.__init__(self, p0, p1, p2, p3) > > def set_point(self, index, point): > if type(index) != type(0) or index < 0 or index > 3: > raise ValueError > if not isinstance(point, Point): > raise TypeError > > self._points[index] = point > > =============================================================== > >>>> from point import * >>>> q = Quad() >>>> q > Figure (Quad), def. by (0,0) (0,1) (1,0) (1,1) >>>> q.set_point(1,Point(555,888)) >>>> q > Figure (Quad), def. by (0,0) (555,888) (1,0) (1,1) > >>>> p = Point(1,2) >>>> p.set(4,2) >>>> p > Point (4,2) > > =============================================================== > > > Frank From itsmikeytime at hotmail.com Wed Sep 25 15:34:29 2002 From: itsmikeytime at hotmail.com (Mikey at Work) Date: Wed, 25 Sep 2002 15:34:29 -0400 Subject: Dynamic Event Handling in wxPython Message-ID: I'm trying to design a menu in wxPython that connects to an SQL server to get its menu commands. So far, I've been able to display the records from the SQL server in the menu. The problem, however, occurs when I try to connect event handlers to the menu items. I know how to connect the event handlers (I'm either going to use EVT_MENU_RANGE or assign a EVT_MENU to each menu item when the items refresh from the server), but the function called by the event handler has no way of determining the id of the menu item (at least as far as I know). If I use... EVT_MENU_RANGE(lowID, highID, OnMenuSelection) ... OnMenuSelection doesn't know which menu item was selected. Is there a way to pass the menu item's id to the function OnMenuSelection or retrieve the id in the function? Thanks for your help. I'm sorry if some of my terminology is off -- I'm kinda new to Python and programming in general. From wlfraed at ix.netcom.com Sun Sep 29 19:24:56 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sun, 29 Sep 2002 16:24:56 -0700 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <874rc8d9c9.fsf@nospam.eml.cc> <3d976fbc$0$23666$91cee783@newsreader02.highway.telekom.at> Message-ID: <8428na.7vj.ln@ix.netcom.com> Jurie Horneman fed this fish to the penguins on Sunday 29 September 2002 02:26 pm: > Actually, I just tried this in a DOS shell under Windows 98: > > python -v script.py >output.txt > > It lists the verbose output straight to the DOS shell, not to > output.txt. The output is useless, I can't scroll back. > I suspect -v output uses stderr, not stdout. >output.txt redirects stdout Don't know if MS-DOS supports redirecting stderr. On linux you'd use python -v script.py 2>output.txt However, for this situation -- ie, trying to debug your import statement -- don't specify the full script on the command line. Do it interactively with the output going to the screen. Oh, BTW... you NEED TWO "v"... python -vv >>> import tmp.some #does not exist # trying tmp.so # trying tmpmodule.so # trying tmp.py # trying tmp.pyc # trying /usr/lib/python2.2/tmp.so # trying /usr/lib/python2.2/tmpmodule.so # trying /usr/lib/python2.2/tmp.py # trying /usr/lib/python2.2/tmp.pyc # trying /usr/lib/python2.2/plat-linux-i386/tmp.so # trying /usr/lib/python2.2/plat-linux-i386/tmpmodule.so # trying /usr/lib/python2.2/plat-linux-i386/tmp.py # trying /usr/lib/python2.2/plat-linux-i386/tmp.pyc # trying /usr/lib/python2.2/lib-tk/tmp.so # trying /usr/lib/python2.2/lib-tk/tmpmodule.so # trying /usr/lib/python2.2/lib-tk/tmp.py # trying /usr/lib/python2.2/lib-tk/tmp.pyc # trying /usr/lib/python2.2/lib-dynload/tmp.so # trying /usr/lib/python2.2/lib-dynload/tmpmodule.so # trying /usr/lib/python2.2/lib-dynload/tmp.py # trying /usr/lib/python2.2/lib-dynload/tmp.pyc # trying /usr/lib/python2.2/site-packages/tmp.so # trying /usr/lib/python2.2/site-packages/tmpmodule.so # trying /usr/lib/python2.2/site-packages/tmp.py # trying /usr/lib/python2.2/site-packages/tmp.pyc # trying /usr/lib/python2.2/site-packages/Numeric/tmp.so # trying /usr/lib/python2.2/site-packages/Numeric/tmpmodule.so # trying /usr/lib/python2.2/site-packages/Numeric/tmp.py # trying /usr/lib/python2.2/site-packages/Numeric/tmp.pyc Traceback (most recent call last): File "", line 1, in ? ImportError: No module named tmp.some -- -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From KBASS1 at nc.rr.com Mon Sep 2 06:07:21 2002 From: KBASS1 at nc.rr.com (Kevin Bass) Date: Mon, 02 Sep 2002 10:07:21 GMT Subject: Newby Question: os.rename References: Message-ID: "Kevin Bass" wrote in message news:AcGc9.68214$Xa.3523883 at twister.southeast.rr.com... > I am attempting to create an archive function within my program. This > function should create a directory with a timestamp name (such as > /home/oracle/data/20020831) on the fly, list the contents of a current > directory then place the contain from the previous directory into the newly > created directory. > > The newly created directory with the timestamp name is being created and the > list of files from the current directory has been retrieved but my problem > comes when moving the files to the newly created directory. I am trying to > achieve this tasks with os.rename but find it difficult to get the command > to recognize the new directory and place the files into it. > > I have attempted to get os.rename to recognize the 'archloc' variable that > contains the name of the newly created directory but that did not work. I > also tried to join the newly created directory with the file names then send > it through os.rename and that did not work either. > What am I doing wrong? Thanks!! (My code is listed below) > > > def archive_data(archive): > > the_date = strftime("%Y%m%d") > archloc = ('/home/oracle/data/' + the_date) > os.mkdir(archloc) > > if archive == 'yes': > for file in os.listdir('/home/oracle/data'): > file2 = os.path.join(archloc, file) > #print file2 > os.rename(r'/home/oracle/data/' + file, file2) > > Kevin > > > > I have figured it out. Thanks! From jwilson at intravative.com Fri Sep 13 23:24:22 2002 From: jwilson at intravative.com (Demi Vitalis) Date: Fri, 13 Sep 2002 20:24:22 -0700 Subject: Part Time Help Needed Message-ID: Part Time Work at Home: PHP Programmers First let me open by saying this; I am a very seasoned programmer but have no friends or associates that program, so I am forced to ask the general programming community online for programming help with this project. My name is Jeremy Wilson and I reside in Los Angeles California. This email is open to everyone no matter what country you live in. The Gist; I am seeking qualified individuals to assist in the development and programming for a new software product that will enter the marketplace in the coming months and is being considered to be sold outright to another software company. I am looking for dedicated individuals with the same passion and energy necessary to launch proprietary new software in exchange for points (percentages) of revenues and sales of the software once it is finished and released. I am short handed and am fast approaching the project deadline I have set upon myself, so I am offering you the chance to receive a residual income for assisting in finishing the development of this application. Before you start sending me responses like "is this a scam" or whatever, please know that I am just a guy trying to get something done and offering a piece of what I have accomplished thus far to people who want to be involved. I will be providing my phone number and etc at the end of this email for you to talk to me. We will draft an agreement and everything so you will now you are not working just on spec. and on trust. And yes, I know that there are other ways of doing this like securing funding and etc to hire people, but I don't want to go through all of that. it takes way too long and you have to give up way too much. Basically I am looking for some team mates and partners to help me with this thing so I can make a lot of money selling it. And if I am making a lot of money that means you will be too. I am about 6 weeks away from finishing this software application and need help to make that deadline. If I don't get help it will take another 3 months probably for me to finish it by myself. Just so you know, the software is expected to be sold outright for around 3 million dollars. You do the math. I have no overhead and have one partner who takes care of all the business. I have set aside a total of 4% of the ownership of the software to those who are contracted to finish this project with me. This 4% will be distributed according to the amount of contributions made and your experience level. Basically if you are the bomb ass programmer, I have no problem giving you the full 4%. If I have to hire multiple people to get the job done, I will be splitting up that 4% according to the skill sets and contributions made. Please take this as a serious offer and if you have a bunch of spare time on your hands, you can help to finish this software and make a bunch of money. Please feel free to contact me via an of the mediums below Jeremy Wilson Fax: 1-818-505-0198 Phone: 1-818-623-9850 jwilson at intravative.com www.intravative.com MSN Messenger: shaka0070 at hotmail.com AOL Instant Messenger: shaka0070 From gmuller at worldonline.nl Fri Sep 13 16:48:06 2002 From: gmuller at worldonline.nl (GerritM) Date: Fri, 13 Sep 2002 22:48:06 +0200 Subject: ANN: Thinking in Tkinter References: <1a3a9ffa.0209120856.1de06f57@posting.google.com> Message-ID: "Stephen Ferg" schreef in bericht news:b16e4ef7.0209130432.7fb3ee61 at posting.google.com... > > I can't really say WHY using a class structure is desirable. > > It is coming back to me now. > > As I was working on easygui.py (http://www.ferg.org/easygui/), I > noticed two things. (1) I was using global variables a lot. (2) I had > several GUI "chunks" in one Python program, and when they were all at > the same level, the code was really unstructured. Very hard to > understand. > > Granted, a lot of my confusion was simply newbie confusion. But I > thought that the next Tkinter development I did, I would see if > structuring the GUI component into classes would help with these > problems. Even in the limited development I've been doing for > "Thinking in Tkinter", it seems to me that: (1) being able to refer to > "self." variables removes the need to make so many variables global. > (2) Grouping the GUI material into classes really helps bring some > structure to the program that it didn't have before. I suspect that > the importance of this (which may not be that obvious in small > programs) will become overwhelmingly obvious in larger and more > elaborate GUIs. One of my "to do" items is to test this hypothesis by > re-writing easygui.py using a class structure. > > So right now, my hypothesis is that -- although Tkinter technology > does not *require* you to structure your GUI as class -- doing so is > probably desirable simply from the standpoint of making a large > program more manageable. I do recognize this evolution. In the beginning a simple script is used and global variables start to appear. My experience is that globals are always suspect. So when the problem and solution is reasonably understood it is time for refactoring, where structuring in classes frequently is the natural pattern to use. I would recommend to follow this logic in your stepwise introduction as well. So start with very simple "scripts" which have globals, which are structured in classes when the problem and solution grows and globals become really dangerous. Starting with classes up front is not always preferred, simply because you don't have sufficient insight in problem and solution structure. The result of too early classes is a lot of self induced additional statements/structure, which only clobber up the understanding and require more refactoring than the more pragmatic beginning with globals. regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From duduca007 at yahoo.com Tue Sep 24 17:35:28 2002 From: duduca007 at yahoo.com (Carlos Moreira) Date: Tue, 24 Sep 2002 14:35:28 -0700 (PDT) Subject: PyBrenda Updates and some Problems Message-ID: <20020924213528.79691.qmail@web11403.mail.yahoo.com> Hi, I did some updates in PyBrenda for my particular use: Brenda.py old: sock.connect(host, port) new: sock.connect(host, port) old: sock.bind(host, port) new: sock.bind((host, port)) old: command = ('rsh ' + self._nodelist[self._nodeIndex] + ' python ' + tmpFile) new: command = ('ssh ' + self._nodelist[self._nodeIndex] + ' $PYTHON/python ' + tmpFile) Well, I need real parallelism (as you can see), so, first of all, I performed tests/test3.py, that result in a "error message" below: :ts got conn from ('10.16.165.38', 34043) :tcr: command is ssh glover /home/pgs/carlos/py /home/pgs/carlos/.PyBrenda.tmp/@13190.0 :ts: pend (in) ('workerDone',) carlos at glover's password: Traceback (most recent call last): File "/home/pgs/carlos/.PyBrenda.tmp/@13190.0", line 14, in ? c = Brenda.TupleClientRsh('isere', 2012) File "/home/pgs/carlos/python/Python-2.2/lib/python2.2/site-packages/Brenda.py", line 387, in __init__ TupleClientCds.__init__(self, host, port) File "/home/pgs/carlos/python/Python-2.2/lib/python2.2/site-packages/Brenda.py", line 297, in __init__ self._conn = self._connectTo(host, port) File "/home/pgs/carlos/python/Python-2.2/lib/python2.2/site-packages/Brenda.py", line 313, in _connectTo sock.connect((host, port)) socket.gaierror: (-2, 'Name or service not known') I need your help. Do I some mistake? What I can do for repare this and configure PyBrenda correctly? []'s Cadu Moreira KaduSoft President ----------------------- [......] __________________________________________________ Do you Yahoo!? New DSL Internet Access from SBC & Yahoo! http://sbc.yahoo.com From tjreedy at udel.edu Fri Sep 6 08:53:14 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 06 Sep 2002 12:53:14 GMT Subject: .py to .pyc References: Message-ID: <_y1e9.459481$m91.17838026@bin5.nnrp.aus1.giganews.com> wrote in message news:mailman.1031300768.16629.python-list at python.org... > Traceback (most recent call last): > File "File.py", line 18, in ? > import Globals, StructuredText, string, utils, re > ImportError: No module named Globals > > Can anybody help me to find the problem? I think it's a problem of > $PYTHONPATH and $PYTHONHOME but i'm not sure. Do the following: >>> import sys >>> sys.path ['', 'C:\\Python22\\Lib\\site-packages\\win32', 'C:\\Python22\\Lib\\site-package s\\win32\\lib', 'C:\\Python22\\Lib\\site-packages', 'C:\\Python22\\Lib\\site-pac kages\\Pythonwin', 'C:\\PYTHON22\\DLLs', 'C:\\PYTHON22\\lib', 'C:\\PYTHON22\\lib \\lib-tk', 'C:\\PYTHON22', 'C:\\PYTHON22\\lib\\site-packages\\Numeric'] to find out what is and is not being searched. Terry J. Reedy From theller at python.net Thu Sep 26 10:49:37 2002 From: theller at python.net (Thomas Heller) Date: Thu, 26 Sep 2002 16:49:37 +0200 Subject: Getting started References: <00a801c26511$4e084750$df7e4e18@brianspiv1700> <%PEk9.146154$ub2.3217944@news1.tin.it> Message-ID: Alex Martelli wrote: > Thomas Heller wrote: > ... > >>Hidden fields in a union by the discretion of the compiler? >>Don't think that would be allowed by any C standard. > > > Could you help me out by pointing to chapter and verse that would > make it disallowed, please? No, sorry. I just find the idea so strange (at least for C, may be different from C++, never really used that). Thomas From anton at vredegoor.doge.nl Sun Sep 15 05:17:08 2002 From: anton at vredegoor.doge.nl (Anton Vredegoor) Date: Sun, 15 Sep 2002 11:17:08 +0200 Subject: How to represent sets References: Message-ID: On Sun, 15 Sep 2002 00:31:48 -0700, "James J. Besemer" wrote: >For dense sets isomorphic with integers, the long integer implementation >probably will be superior. > >For other, more general applications the dictionary approach may be better. My script is not yet fully optimized, I just made some minor tweaks (the new version is at the same adress as before) and there's some test output below. For somewhat longer strings Set loads faster but if there are a lot of operations on the sets, set is faster. For some other cases see below. Could someone please check these results? It could be a programming error since I am still tweaking the script. from sets import Set from universe import set from time import time def test(): n = 100 k = 10000 r1 = [(i,j) for i in range(n) for j in range(n)] r2 = [(i,j) for i in range(n) for j in range(n-1,-1,-1)] t = time() S1 = Set(r1) S2 = Set(r2) for i in range(k): S3 = S1-S2 print time()-t print "S finished" t = time() s1 = set(r1) s2 = set(r2) for i in range(k): s3 = s1-s2 print time()-t print "s finished" print if __name__=='__main__': test() >d:\python22\pythonw -u test.py 92.5499999523 S finished 0.44000005722 s finished from sets import Set from universe import set from time import time def test(): n = 100000 k = 1000 r1 = [i for i in range(n)] r2 = [i for i in range(0,n,2)] t = time() S1 = Set(r1) S2 = Set(r2) for i in range(k): S3 = S1-S2 print time()-t print "S finished" t = time() s1 = set(r1) s2 = set(r2) for i in range(k): s3 = s1-s2 print time()-t print "s finished" print if __name__=='__main__': test() >d:\python22\pythonw -u test2.py 104.090000033 S finished 2.58000004292 s finished From zopestoller at thomas-guettler.de Thu Sep 19 06:43:26 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Thu, 19 Sep 2002 12:43:26 +0200 Subject: ZCatalog without Zope Message-ID: Hi! Has anyone used ZCatalog from Zope with a standalone ZODB (without Zope)? Background: I am thinking about moving away from Zope to quixote or just simple cgi. If you are intereseted in the reason way I don't want to use zope: http://lists.zope.org/pipermail/zope/2002-August/119965.html thomas From a-steinhoff at web.de Sun Sep 1 12:36:05 2002 From: a-steinhoff at web.de (Armin Steinhoff) Date: 1 Sep 2002 09:36:05 -0700 Subject: Python IPC options References: <1030829572.943495@irys.nyx.net> Message-ID: fburton at nyx10.nyx.net (Francis Burton) wrote in message news:<1030829572.943495 at irys.nyx.net>... [ clipp ..] > It would be nice if Python could provide the same kind of > communication mechanisms. Unfortunately, while Glish is > freely available, it is heavily C++ biased and runs only on > some Unix systems. In theory, something similar could be > implemented on a much wider range of platforms using > sockets and Python. > > Can anyone tell me: has an interprocess communication > mechanism specifically with a bus architecture been > implemented in/for Python? Corba 2.2 -> http://www.fnorb.org Python remote objects -> http://www.sf.net/projects/pyro SOAP -> http://www.pythonware.com/products/soap/ SPREAD -> http://www.python.org/other/spread/ Send/Receive/Reply for QNX6 message passing -> http://www.sf.net/projects/pyqnx ... also PyPVM, PyMPI a.s.o. Hope this is enough :) Armin From lothar at kki.net.pl Wed Sep 4 08:52:37 2002 From: lothar at kki.net.pl (Lothar) Date: Wed, 4 Sep 2002 14:52:37 +0200 Subject: Matching a string up to a word References: Message-ID: <3d7601ef@news.inet.com.pl> Best library for operating on text is re (Regular Expressions) import re log = open("filename.log") for line in log: re.match(r"^\d+ (.*)(\s\w+){4}$",line).group(1) > I have a string that contains an ID number a file path and a date, kind > of like this: > > 23545 /this/is a/path/to/a file Sun Sep 7 2002. > > I want to extract the file name. If I could be sure that the file path > had no spaces or if it would be quited it would be easy. Unfortunatly > many files will have spaces and changing the format of the output I'm > dealing with isn't possible. I do however know that the file name starts > after the first whitspace and that it's always followed by a three letter > day name (like Mon, Tue etc.) Given this is there an easy way to extract > the whole file path from the string. > > Dag > From jepler at unpythonic.net Sat Sep 7 11:23:00 2002 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sat, 7 Sep 2002 10:23:00 -0500 Subject: Larry Wall's comment on python... In-Reply-To: References: <3D7958DB.50903@nospam.free.fr> Message-ID: <20020907102252.A15633@unpythonic.net> On Sat, Sep 07, 2002 at 04:46:07PM +0200, Thorsten Kampe wrote: > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*BEGINS*_! > def fun(args): > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*BEGINS*_! > if ceci or cela: > do_this(with_that) > [snip a lot of code] > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*ENDS*_! > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*ENDS*_! But my name's not Larry....! Why don't you write code that's readable by *me*? Jeff From whisper at oz.net Wed Sep 18 15:14:26 2002 From: whisper at oz.net (David LeBlanc) Date: Wed, 18 Sep 2002 12:14:26 -0700 Subject: Earing money with Python software (was: More on Protecting Source Code) In-Reply-To: Message-ID: In my experience, the reason big corps don't buy low-priced software is that it's... low priced! The big boys expect to pay big prices. They also generally expect big priced levels of support too. I think some of this stems from them knowing what it would cost them to build rather then buy and they don't consider the lower overhead of little companies that allows them to offer lower prices. Thus, they question the quality of "cheap". Another reason why big companies/the government don't buy from little companies in general is based on concerns that 'little company' won't be around in the future. This is especially true if 'big company' preceives some degree of mission criticality in the software they're considering. What dreams are made of: GE buying a 55,000 seat license at $20/seat! :) David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of brueckd at tbye.com > Sent: Wednesday, September 18, 2002 9:32 > To: python-list at python.org > Subject: Re: Earing money with Python software (was: More on Protecting > Source Code) > > > On Wed, 18 Sep 2002, Michael Str?der wrote: > > > brueckd at tbye.com wrote: > > > free-for-personal-use-but-companies-must-pay approach when possible. > > > > The problem with getting some bucks from a company is the > amount of time > > spent during decision taking and ordering process. For you to earn 300 > > bucks for your software the company spends another 500+ bucks for > > working time until the money gets out. > > Well, it really varies by company of course. Most places I've worked only > require that much bureaucracy for larger purchases. For small > stuff (under > a few hundred dollars) it usually amounts to me informing a superior that > tool X is needed and worthwhile. After that I just buy it myself and turn > in a simple expense report. > > > IMHO that's why it's so hard to > > sell small packages of rather cheap software to big companies. > > That's why you don't sell it for $300. Seriously: if it's a small and > cheap package then $300 (I'm assuming US$300) is often too high for small > businesses and many individuals anyway, and for large companies it might > be expensive enough to trigger more purchasing overhead (at my current job > that price could go either way). So... you sell your product with a single > seat license for, say, $100 and then offer a site license for e.g. $500 > as well as a renewable support package for $1000 a year or whatever. You > also give 'em discounts when you release a new version next year. > > -Dave > > > -- > http://mail.python.org/mailman/listinfo/python-list From eugene1977 at hotmail.com Wed Sep 4 08:10:21 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Wed, 04 Sep 2002 12:10:21 +0000 Subject: Makefile.pre.in ?? installing postgresql --with-python Message-ID: ./configure --with-python gives me this error (postgresql7.1.3 config) configure: error: The Python extension makefile was expected at `/usr/local/lib/python2.2/config/Makefile.pre.in\' i searched with "python extension makefile" "Makefile.pre.in" in groups.google.com first time i can't find a clue for the problem.. i installed python2.2.1 tgz file thanks From Michael.Sparks at rd.bbc.co.uk Fri Sep 13 06:17:40 2002 From: Michael.Sparks at rd.bbc.co.uk (Michael Sparks) Date: Fri, 13 Sep 2002 11:17:40 +0100 Subject: wrapping yield ? References: Message-ID: "Duncan Booth" wrote in message news:Xns92885F082A21Cduncanrcpcouk at 127.0.0.1... ... > So something like this should work: > > def my_generator(arg): > dostuff.... > for item in waitForSomethingCheckingPeriodically(): > if item is None: > yield None > else: > processit(item) Whereas if I could wrap up yield, I simply have to do: item = waitForSomethingCheckingPeriodically() process(item) Which if I have lots of this sort of thing going on, results in much clearer (and hence maintainable) code. If it can't (putting yield in a function, and not turning the function into a generator) be done, and AFAICT it can't, and this is a suggested work around - many thanks :-) Best Regards, Michael. From gerhard.haering at gmx.de Fri Sep 6 19:44:21 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 6 Sep 2002 23:44:21 GMT Subject: Python from C/SDL References: <3D793B29.3198AB0E@ihug.co.nz> Message-ID: Gib Bogle wrote in comp.lang.python: > Hi, > > I am a complete beginner with Python. My interest in it is focussed > on a great piece of open-source software called pymol, a system for > visualization of molecules that uses Python and OpenGL. I'd like to > get access to pymol's graphical functions from my own program, which > is built from C, SDL and OpenGL. > > I'm wondering if (with a bit of surgery) I'd be able to get access > to the lower-level functionality of pymol, by which I mean the file > I/O and rendering functions. You'll have to embed Python (http://www.python.org/doc/current/ext/embedding.html), load the pymol modules and call functions or classes in it from C. This means you'll have to get familiar with the Python/C API. The good thing is that this is relatively easy. You should be able to find documentation and examples on embedding Python. If you have any particular questions on how to use the Python/C API, just ask here. HTH, Gerhard From spam at melkor.dnp.fmph.uniba.sk Thu Sep 26 09:18:52 2002 From: spam at melkor.dnp.fmph.uniba.sk (Radovan Garabik) Date: Thu, 26 Sep 2002 15:18:52 +0200 Subject: unicode woes References: <3d92d120$0$76313$e4fe514c@dreader4.news.xs4all.nl> Message-ID: Ulli Stein wrote: : But nevertheless you would have to use everywhere the Python unicode() : function. : Or how would you do this (nonsense string): : str = str + "bla??" + str[:5] + "???" : Would you write then: : str = str + unicode("bla??") + str[:5] + unicode("???")? I ran into the same problem and find out that python2.3 handles this. Just add the line # -*- coding: UTF-8 -*- as the second line of your python script and then you can use all your strings in UTF-8 encoding (or any other, whatever fits you) -- ----------------------------------------------------------- | Radovan Garab??k http://melkor.dnp.fmph.uniba.sk/~garabik | | __..--^^^--..__ garabik @ fmph . uniba . sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From claird at starbase.neosoft.com Wed Sep 18 10:50:33 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 18 Sep 2002 09:50:33 -0500 Subject: minimizing Tk programs to the taskbar References: <3D8872F1.87850856@optushome.com.au> <656913E3D19D40D2.0831BD5165F06A87.FDA870F87AEF2207@lp.airnews.net> Message-ID: In article , Alex Martelli wrote: >Cameron Laird wrote: > >> In article , >> >> Alex Martelli wrote: >> >Richard Tardif wrote: >> >> Is there any way to minimize programs to the taskbar? I'm talking about >> >> windows here. By taskbar I mean the area down in the bottom right >> >> corner, near the clock, that shows icons for what proggies you've got > ... >> ? Alex and Richard, I think you'll want to experiment with >> root = Tkinter.Tk() >> ... >> Tkinter.Wm.iconify(root) > >Nope: this (at least on Win/98 -- I have no other Win release at hand to >try, >but I don't think the difference matters here) minimizes the window in the >normal way, NOT to the system-tray, which Richard described as "the >area down in the bottom right" and (probably mis-)named "taskbar". > >> Alex' intuition that a lot of the operations people say they >> want are platform- or window-manager-specific is certainly >> apt. > >Sure, but Richard did say he meant Windows (though he probably should >have uppercased that) -- that's pretty much an acknowledgment of >being platform-specific. On Win in particular, crowding the system tray >with a zillion icons was all the rage once -- so many programs did it, >particularly device drivers and various daemons, as to make things more >or less unusable. Win/XP now tries to help by hiding most of the system >tray except icons used recently, unless one specifically 'opens' the tray. >It's still somewhat of a mess (and becomes worse, the more programmers >learn to use Shell_NotifyIcon:-), but that's another issue. . . . I applaud Alex (a non-native English speaker, moreover!) for his careful reading. He's accurate in all he writes here, and, more than that, he's well informed--his are exactly the comments that should be made. I apologize for confusing matters. Many people who ask questions of the sort Mr. Tardif asked find Tkinter's iconify() at least partially satisfying; that's my experience, at least. Those who want to pursue Tkinter management of the system tray more will probably find interesting. winico is a rather popular small Tk extension to manage Windows icons. At the very least, its source code should be instructive. Do properly-coded Tk extensions benefit Tkinter users directly? Is there a way to load them? I doubt it, but I haven't thought long about it ... -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From tismer at tismer.com Mon Sep 30 15:41:39 2002 From: tismer at tismer.com (Christian Tismer) Date: Mon, 30 Sep 2002 12:41:39 -0700 Subject: Stackless Python Howto References: <1033385295.69247@charme.kabsi.at> Message-ID: <3D98A8F3.6020609@tismer.com> Johann H?chtl wrote: > Hello! > > Can someone give me a short briefing how to use stackless python? I thought > it's all about a replacement of python.dll, and as long as you don't use > stackless threading and continuations, at least arbitrary, lightweight > recursion will be available. > > However, the famous ackermann function with parameters ack (3, 7) and > onwards still failes because of stack constraints. > > What else do i have to specify to be go stackless? You need to enable stack saving by sys.enable_stackless. If you are going to use this on a regular basis, I suggest to put this into site.py. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From mcherm at destiny.com Wed Sep 11 09:27:46 2002 From: mcherm at destiny.com (Michael Chermside) Date: Wed, 11 Sep 2002 09:27:46 -0400 Subject: dynamism References: <66715c02.0209091923.265fe77e@posting.google.com> <3d7e209a_1@news.iprimus.com.au> Message-ID: Duncan Booth wrote: > Oh, and the -O flag on > the CVS build has no measurable effect. There's a reason for that. Effectively, some clever tricks (and core loop rewrites) have been added which puts Python into (the equivilant of) -O mode all the time, by calculating line numbers seperately when needed instead of generating SET_LINENO bytecodes. At least, that's what I thought I understood it to be doing. Anything that speeds up essentially all Python programs iss OK by me! -- Michael Chermside From gmuller at worldonline.nl Sun Sep 22 12:03:17 2002 From: gmuller at worldonline.nl (GerritM) Date: Sun, 22 Sep 2002 18:03:17 +0200 Subject: How to get memory usage on Windows? References: Message-ID: Searching in books , documentation (a.o. win32api) and net did not yet help I found this article on the net: http://www.developeriq.com/Magazinestories/02jul29memory.php3 but how to call this function from Python? The module GC is mentioned with respect to memory leaks, but as far a I could find, no status information can be obtained. I would expect that in the run time information the size information is present. Can this be accessed from Python itself? regards Gerrit "GerritM" schreef in bericht news:amilhk$bi8$1 at reader1.tiscali.nl... > I am building an access log analyzer. For the first version I did not worry > about performance or memory use, the first exploration was about what is > practical information to extract and how to present. For current result see > http://www.extra.research.philips.com/natlab/sysarch/GaudiStatistics.html > and > http://www.extra.research.philips.com/natlab/sysarch/weblog/index2002.over.h > tml > > For the second version memory use becomes an issue. The brute force version > keeps all information simultaneously in memory, without any size > optimization. This results now in memory use of about 250 MByte (measured > via very coarse windows resource tool), which scales linear with the amount > of (ever increasing) input. I would like to be able to measure more specific > how much memory is used per phase and/or per function. Is there any function > returning this information. I noted that on Unix the resource module gives > access to this kind of information, but I could not find any Windows > alternative. > > regards Gerrit -- www.extra.research.philips.com/natlab/sysarch/ From oliver.smith at removethisbit.baesystems.com Thu Sep 5 07:01:32 2002 From: oliver.smith at removethisbit.baesystems.com (Olly Smith) Date: Thu, 5 Sep 2002 12:01:32 +0100 Subject: Returning lists from python COM servers References: <3d7731f5$1@pull.gecm.com> Message-ID: <3d7738f5$1@pull.gecm.com> uhmmmmm, strangely enough, changing it to == return [tags,vals] == on the server side fixed it! Now the question is: WHY!? "Olly Smith" wrote in message news:3d7731f5$1 at pull.gecm.com... > Using this snippet on the server side: > > == > return (tags,vals) > == > > Where tags and vals are equal length lists (actually a dict that maps > strings to strings split up so it can be returned from the COM object) > > This snippet on the client side: > > == > tags,vals = self.prodcat.getPDF(id) > == > > I get this error (mildly snipped cgitb output): > > == > 547 tag,val = self.prodcat.getPDF(id) > > ValueError: unpack tuple of wrong size > __doc__ = 'Inappropriate argument value (of correct type).' > __getitem__ = > > __init__ = instance at 0x00849670>> > __module__ = 'exceptions' > __str__ = instance at 0x00849670>> > args = ('unpack tuple of wrong size',) > == > > Any ideas on where I'm going wrong? I'm pulling my hair out trying to work > this one out. > > Thanks > > Olly > > > From eric.brunel at pragmadev.com Tue Sep 3 08:54:25 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 3 Sep 2002 14:54:25 +0200 Subject: hackicon, tkicon References: <3D749F85.962D8D39@ipm.fhg.de> Message-ID: Markus von Ehr wrote: > Hi, > > is there already a hackicon or tkicon module for > python 2.2 ? > The modules are useful for changing the window icon on win32. > > Thanks for any hints, > > Markus IIRC, this is no more needed with Tcl/Tk 8.4: the standard methods iconbitmap and/or iconwindow should work on Windows. See: http://www.tcl.tk/man/tcl8.4/TkCmd/wm.htm#M18 But I haven't actually tested it... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From blarson at crary.com Wed Sep 18 12:59:18 2002 From: blarson at crary.com (Bradley D. Larson) Date: Wed, 18 Sep 2002 11:59:18 -0500 Subject: Source code References: Message-ID: <3D88B0E6.AC08EC27@crary.com> I might have missed it... (I read most of the posts on this subject). Why not just use a significant info registration key. The registration key would be sensative to date, registered name and/or some other piece of information that would be required to get the software to work. At least then (if the person buying the pirated software) would have to: 1. Set their computer date BACK to the DATE of the original reg key use. 2. Enter the name of the original owner. 3. Enter the other information (ie. version, address -- if they move they get a new regkey). This would do several things. 1. Become pretty obvious to the purchaser that the software is pirated. 2. The pirater and/or purchaser would have to know all items relating to the reg key. You could have the reg key checked periodically during the program run time. Hide the checking routine in some unsuspecting code (create a dummy function like syncMufflerBelt() in a linked c module that gets called periodically. If you do come accross an illegal copy you would be able to know the original owner and possible trace the path to the current user (take 'em all down!). Terje Johan Abrahamsen wrote: > If I would like to write some code that would not be possible for others to > read, after I distribute the program, would Python be suitable? I know that > there are a few programs like Py2Exe, that creates .exe files. But, I also > saw this: > > -------------------- > A zip-compatible archive is built, containing all files from this > directory as well as your script, and appended to a custom python > interpreter supplied with py2exe. > -------------------- > > Doesn't sound like it is protected very well. Is there some alternative to > Py2Exe that can do the job, or should I look for a compiled language > instead? > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: blarson.vcf Type: text/x-vcard Size: 400 bytes Desc: Card for Bradley D. Larson URL: From grisha at modpython.org Thu Sep 12 18:25:45 2002 From: grisha at modpython.org (Gregory (Grisha) Trubetskoy) Date: Thu, 12 Sep 2002 18:25:45 -0400 (EDT) Subject: ANNOUNCE: Mod_Python donated to ASF Message-ID: It is my pleasure to announce that Mod_Python has been donated to the Apache Software Foundation, and is now a subproject of the httpd server project (see http://httpd.apache.org/). I am grateful to ASF for accepting this donation and committing resources to further the support of Mod_Python. I believe that this action will advance the development of Mod_Python, resulting in an ultimately better and more popular tool for Python developers. I also believe it will serve to better position Python as a language of choice for web development, a need that has been expressed by many. There are no implications to the current Mod_Python users - the license is the same with the sole difference in that the copyright belongs to ASF now. As a consequense of the donation, the CVS repository is now hosted on cvs.apache.org. Do not use the SourceForge repository anymore, it will soon be removed. There will also be website and mailing changes, but the details are still being finalized and will be announced when ready. Regards, Grisha Trubetskoy From wodyk at ouray.cudenver.edu Tue Sep 17 12:38:16 2002 From: wodyk at ouray.cudenver.edu (Wesley Dyk) Date: Tue, 17 Sep 2002 09:38:16 -0700 Subject: Good book choice? References: <05k9ou4o2m9e41puce9ni3953b5hbhn8c0@4ax.com> Message-ID: <3D875A77.6FD89AF3@ouray.cudenver.edu> robin at execulink.com wrote: > eva_ag at eresmas.com (Eva) wrote: > > >I am new to Python but an experienced programmer in Fortran95 (not too > >object > >oriented). I am looking for a suited Python book. I'd like it to have > >clear ideas about OO, as well as an straight pointing into the core > >language. > > > >It seems that 'Python Essential Reference (2nd Edition)' is a good > >choice. There is also the book 'Making use of Python' (by Rashi > >Gupta). Is there any user that bought both? Is it good the treatment > >of OO in the former? Is there a lack of applications point of view in > >the former? Could anybody compare them? pros/cons? > > Can't help you with those, but have had luck with Learning Python > (Mark Lutz & David Ascher, pub. O'Reilly), a great introduction to the > language that doesn't pad out its length with stuff you can read in > the reference documentation. I think it's the single-best Python book > out there. So do the other developers I work with. > > Then you'll want to get the Python Cookbook (edited by Alex Martelli & > David Ascher, pub. O'Reilly) for in-depth analysis of common tasks and > thoughtful solutions. This is more advanced than your typical > Cookbook. It's going to be by my side a long time! > > Start here: http://python.oreilly.com > > -- robin I would have to agree with you on _Learning_Python_. It has good instruction on OOP with Pyhton. I have also heard that Guido himself likes this book the best. I have not read the _Python_Cookbook_. I would start with _Learning_Python_ and move on to a reference book after that. Aus From tjlavoie at mb.sympatico.ca Fri Sep 27 12:34:06 2002 From: tjlavoie at mb.sympatico.ca (Tim Lavoie) Date: 27 Sep 2002 11:34:06 -0500 Subject: How do I set-up Multiple socket connections References: Message-ID: <87n0q3qtmp.fsf@theasylum.dyndns.org> >>>>> "Kat" == Kat Kathuw Huw writes: Kat> Ok, I want to iterate through a server IP list and establish Kat> multiple socket connections to the various IP address' in the Kat> list. Well, what would you like to do with your conversations? It can be as simple as putting them all in a list, or each instance of some class has its own. If you want to create them all and then poll them sequentially, then your job is fairly simple. It is somewhat trickier if you are doing more arbitrary things within say, a GUI event loop. Can you elaborate a bit? Tim From thorsten at thorstenkampe.de Sun Sep 15 03:56:25 2002 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 15 Sep 2002 09:56:25 +0200 Subject: IDLE References: <3D7D4F84.318CDB0F@bellatlantic.net> Message-ID: * syver-en at online.no >"Ali K" writes: >> Hardware: 386 enhanced, 75MHz, 32MB RAM. >> OS: Win98 >> Copied files from other computer to mine. >> It doesn't open when I click on ide.pyw or when I choose to edit a py >> file >> >> with it. > > I suggest you install the python distro from www.python.org. You think this will work on medieval computers? Thorsten From alanmk at hotmail.com Mon Sep 23 16:11:21 2002 From: alanmk at hotmail.com (Alan Kennedy) Date: 23 Sep 2002 13:11:21 -0700 Subject: Sessionhandling References: Message-ID: storedmails at gmx.net wrote: > I'm trying to program a web application with python. This tool has to > provide diffrent languages. The user has to choose the language at the > beginning. So i have to save the information which language the user > chooses. I think this is a perfect example for using sessions. The following is not related to sessions. Are you aware that a users language preference is encoded in every request that they make to a web server, through the "Accept-Language" HTTP header? Example formats for this header are (from my server logs) Accept-Language: de Accept-Language: en,fr-CA Accept-Language: en-us, en;q=0.50 Accept-Language: en-us,de;q=0.7,fr;q=0.3 Accept-Language: en-us,fr-be;q=0.5 Accept-Language: en-us,zh-tw;q=0.5 Accept-Language: es-mx, en;q=0.5 Accept-Language: fr So if you access the Accept-Language header (code below), and do some simple string manipulation, you may be able to solve your problem without sessions and without making the user explicitly select a language (they've already done this in their browser). Sample code----------------------------------- #! /path/to/python import os import string try: langpref = os.environ['HTTP_ACCEPT_LANGUAGE'] langs = string.split(langpref, ',') firstpref = langs[0] secondpref = langs[1] thirdpref = langs[2] # Dealing with quality values (e.g. 'q=0.3') is left as an exercise for the reader :-) except: firstpref = 'en-ie' ----------------------------------------------- Maybe might make your life a little simpler.... HTH, Alan. From loewis at informatik.hu-berlin.de Sun Sep 15 14:08:48 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 15 Sep 2002 20:08:48 +0200 Subject: Stackless Python, eventual merge? References: Message-ID: "David Abrahams" writes: > I think it still matters. You don't want people who need stackless' > capabilities to have to use a non-standard Python forever, do you? Unfortunately, the current implementation is processor-dependent; it supports x86, SPARC, and PPC only (not really sure about PPC). It also limits extensions: if they call back to Python, they must not keep "global" variables on the stack (global in the sense that their address is known outside their function). These limitations require Stackless users to be more aware of the inner workings of Python, or they risk crashes - something that would be considered a bug in standard Python. Regards, Martin From manuel at hendel.net Wed Sep 11 08:00:34 2002 From: manuel at hendel.net (Manuel Hendel) Date: Wed, 11 Sep 2002 14:00:34 +0200 Subject: deleting the first and the last character of a string In-Reply-To: <20020911115118.GE2054@partagas.as.de.cw.net> References: <3D7F2960.20507@Linux.ie> <20020911115118.GE2054@partagas.as.de.cw.net> Message-ID: <20020911120034.GF2054@partagas.as.de.cw.net> On Wed, Sep 11, 2002 at 01:51:18PM +0200, Manuel Hendel wrote: > This worked quite good, but I found another problem. There seams to be > trailing whitespaces. I tried to strip(s) to get rid of them, but this > doesn't work, I get the following error message: > > Traceback (most recent call last): > File "./pop3create.py", line 9, in ? > print strip(line) > NameError: name 'strip' is not defined > > What's wrong here? Sorry for that mail, I already found the problem, I simply forgot to put string. in front of strip. This happens when a programming beginner tries to solve a problem for several hours. Thanks, Manuel -- What goes up must come down. Ask any system administrator. From llothar at web.de Sun Sep 15 21:31:12 2002 From: llothar at web.de (Lothar Scholz) Date: Mon, 16 Sep 2002 03:31:12 +0200 Subject: can wxpython do this? References: <737aefee.0209151702.3f735252@posting.google.com> Message-ID: On 15 Sep 2002 18:02:17 -0700, erick_papadakis at yahoo.com (Erick Papadakis) wrote: >hi, i am considering learning wxpython and have a few questions before >i >get into it to make sure it is worth it. > >1. what does it give me that java or c++ dont? It is not java. It is a competitor to FOX and QT if you use the c++ version. It's unique when you use the Python version (QT and FOX bindings are not so perfect at the moment). >is it cross-platform >too? Yes >2. is it a good platform to develop desktop application in, given that >it >is a GUI app? how will i distribute it? is there any easy installer >that >will allow me to install python first on a layman user's computer >first, >then wxpython, then my own application? is this the concept of >wxpython >or am i missing something? There is no problem to setup an installer easily that takes Python,WXPysthon and whatever you need. It simply blowes up the installer package size. >3. does it allow me access to windows (or linux x-windows) native >APIs? >for instance, can i minimize my application to a user's desktop's >taskbar and have a right-click context menu on that taskbar entry? I think its not comfortable but possible. Look at the API to find out. >4. do i have something like a browser control built in? i want my >desktop app to interact with my web server and display the response >just as if it was a browser (BUT with some more client-side richness >in features, hence the app to begin with). is this possible? There is a really simple WxHTML Widget and at least a C++ version of a wrapped IExplorer control. But having something like this would remove the cross platform compatibility. Perhaps someone is working on a mozilla widget ? > >thanks very much for any ideas/resources that i can use to decide. Try it and then decide - don't decide on posted answers. From mhammond at skippinet.com.au Wed Sep 11 18:59:27 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Wed, 11 Sep 2002 22:59:27 GMT Subject: COM, Outlook, and constants References: Message-ID: Ken Seehof wrote: > I just upgraded my windows box to XP, and resumed working on a Outlook > COM project > that I haven't touched for a few weeks. For some reason it doesn't work > anymore. > Anyway, the symptom I am trying to resolve now is that > win32com.client.constants > doesn't seem to work anymore. It's supposed to acquire attributes for > all constants > defined in loaded COM servers through its __dicts__ attribute. > > The following is typical of python COM client code. Any hints? > > >>> import win32com.client > >>> ol = win32com.client.Dispatch("Outlook.Application") > >>> ns = ol.GetNamespace("MAPI") > >>> oc = win32com.client.constants > >>> oc.olFolderInbox > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python22\lib\site-packages\win32com\client\__init__.py", line > 131, in __getattr__ > raise AttributeError, a > AttributeError: olFolderInbox > >>> oc.__dicts__ > [] > >>> makepy has not been run for this object library. Your code should use gencache.EnsureDispatch() to ensure makepy support exists. Mark. From pedro_rodriguez at club-internet.fr Fri Sep 27 05:30:22 2002 From: pedro_rodriguez at club-internet.fr (Pedro RODRIGUEZ) Date: Fri, 27 Sep 2002 11:30:22 +0200 Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> <7nHk9.172208$pX1.6117207@news2.tin.it> <12Uk9.175615$pX1.6212603@news2.tin.it> Message-ID: On Fri, 27 Sep 2002 09:47:09 +0200, Alex Martelli wrote: > Pedro RODRIGUEZ wrote: > ... >> The first one isn't possible in a Python expression AFAIK, > > Of course it is -- you seem to keep ignoring the semantics of Python's > "and" and "or" operators, which ARE short-circuiting (and return one of > the operands, differently from C/C++'s short-circuiting && and ||, which > return 0 or 1 whatever operands they're given). > >From now on, I will know them :/ (even read ref manual on boolean operations as a punition ;) Always thought an expression was completely evaluated prior computation, like in Ada - execept for and then/or else, I was wrong. >>> def a(): print 1 ... >>> def b(): print 2 ... >>> def c(): print 3 ... >>> if a() and b() and c(): pass ... 1 >>> Sorry for the noise Pedro From jdavis at empires.org Thu Sep 19 00:42:48 2002 From: jdavis at empires.org (Jeff Davis) Date: Thu, 19 Sep 2002 04:42:48 GMT Subject: linux python ideas References: <3D88E578.6010001@diespammerdieuselesspython.com> Message-ID: I think python's strength (for me) is in it's versatility and consistency. That combination is very powerful. When I say python is consistent, I mean that there are very few special cases, and few special character sequences to remember. That means you generally only have to reference the docs for functions, and not language issues. It's also versatile, because (a) it has a good standard library (b) the library is easily extended with python, C, or Java (if you're into jython). That gives python access to the vast standard libraries, and extended libraries (like APIs to virtually anything in existence), of C & Java. I use it for: * simple task automation, kind of like a shell script but easier to write. * starting to use it for web programming * practical extraction and report, text/binary data processing or reformatting, whatever you want to call it. * methematics, such as statistics, but also really simple stuff when I have a shell more handy than a calculator :) * embedded scripting (because it integrates so easily with C) * small daemons and other small applications Regards, Jeff Rob Andrews wrote: > I'll be giving a presentation on Python to my local LUG > (http://lugoj.org) in a few weeks, and would like to point out at least > a few things that would be of particular interest to linux users. > > The idea is not "how to program in Python", which would take more than > one quick presentation, but a one-off demonstration of ways in which > Python is particularly useful for such a group. > > Any suggestions would be appreciated, since my notes are pretty generic > so far. > > regards, > Rob Andrews From owen at nospam.invalid Thu Sep 12 13:29:48 2002 From: owen at nospam.invalid (Russell E. Owen) Date: Thu, 12 Sep 2002 10:29:48 -0700 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> <3D7FFC43.10002@something.invalid> Message-ID: In article , steve at ferg.org (Stephen Ferg) wrote: >... >This explains why "command" binding doesn't automatically pass an >event object the way that event binding does. The standard behavior >of a widget might be defined across multiple kinds of events (e.g. >Button's standard behavior is defined across both a button-press and a >button-release), so there is no *single* event that could be passed. True. It would help if the command callback sent an arguement that identified the widget (making it look a bit more like an event binding). In any event, it doesn't and command is unfortunately still the best way to handle button widgets. In general Tkinter has several useful callback mechanisms, each of which is especially easy to use for a particular type of problem and may be a headache for other sorts of problems (e.g. events to simulate button command). Examples (aside from Button command): Event binding examples: - Use mouse button events to do useful things in the Canvas widget. For instance you can easily drag objects around by binding to and . Or show information when the pointer is near an object on a Canvas using . - Use keyboard events to modify the behavior of Entry widgets, for example bind to the return keyto accept the data and use it somehow, or bind to up-arrow and down-arrow to implement a history mechanism. Variable trace: - To implement input validation in Entry widgets, specify a textvar and put a trace on the variable. In your callback beep and restore the old value of the variable if the proposed new value is invalid. There are others. My Tkinter Summary section "Events and Callbacks" has what I believe is a complete set though without examples. I'm should take another look at it and expand it a bit. -- Russell From klausman-un090902 at tuts.net Mon Sep 9 13:08:22 2002 From: klausman-un090902 at tuts.net (Tobias Klausmann) Date: 9 Sep 2002 17:08:22 GMT Subject: Python plugins References: <3D7C13B3.2070606@nospam.free.fr> Message-ID: Christian Tismer wrote: > If you executed a proper __import__, all modules and funcs should > be accessible in the normal way. > There is no need to exec. This is what I overlooked: the lowlevel interface to __import__ Thanks a lot for your help (to laotseu, too). Greets, Tobias From sa at hogia.net Mon Sep 16 12:04:08 2002 From: sa at hogia.net (Sebastian Andersson) Date: Mon, 16 Sep 2002 16:04:08 +0000 (UTC) Subject: Py_CompileString and line numbers? Message-ID: I'm parsing a config file and from there I get embedded python code which I send to Py_CompileString, with the config file's filename given as filename argument to Py_CompileString. Later, when errors are found in the python code, the wrong line numbers are reported. Is there a way to tell Py_CompileString an offset for the first line that I give to it? /Sebastian From aleax at aleax.it Mon Sep 16 16:13:44 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 16 Sep 2002 20:13:44 GMT Subject: Alex Martelli -> search re and put in a list?? References: Message-ID: jubafre at brturbo.com wrote: ... > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Documents and Settings\jubafre\Desktop\teste.py", line 27, in ? > final = [ big_re.sub(x, replacer)for x in S ] > TypeError: expected string or buffer > > what happened???? Exchange the arguments to big_re.sub -- it's final = [ big_re.sub(replacer, x) for x in S ] Alex From bokr at oz.net Tue Sep 3 18:32:30 2002 From: bokr at oz.net (Bengt Richter) Date: 3 Sep 2002 22:32:30 GMT Subject: efficient list merging References: Message-ID: On Tue, 3 Sep 2002 13:27:53 -0700, "Ken Seehof" wrote: >> [Peter Saffrey] >> >> > I have two lists of lists of strings which I would like to merge >> > efficiently without repeats. [...] Or is there a better way? >> >> I am not sure about the relative speed of everything, but I would be >> tempted to try: >> >> dict(zip(list1 + list2, [None] * (len(list1) + len(list2)))).keys() >> >> It seems to work: >> >> >>> list1 =3D list('abcdebxyz') >> >>> list2 =3D list('pqqr') >> >>> list1 >> ['a', 'b', 'c', 'd', 'e', 'b', 'x', 'y', 'z'] >> >>> list2 >> ['p', 'q', 'q', 'r'] >> >>> dict(zip(list1 + list2, [None] * (len(list1) + len(list2)))).keys() >> ['a', 'c', 'b', 'e', 'd', 'q', 'p', 'r', 'y', 'x', 'z'] >> >> -- >> Fran=E7ois Pinard http://www.iro.umontreal.ca/~pinard > >This is a bit faster, but assumes that the first list does not initially >contain duplicates. It eliminates duplicates that would be introduced by >merging items from list2. Also, this maintains the original list order >(i.e. list1+list2 without adding duplicates). > >def merge(list1,list2): > d1 =3D dict(zip(list1,list1)) If you don't care about a throwaway list of None's (and why should you, if you don't care about a throwaway list of tuples ;-), you could also write instead of the above line: d1={}; map(d1.setdefault, list1) > return list1+[s for s in list2 if s not in d1] > I think you all missed "lists of lists" of strings in the original problem statement, just as I did. But adding my 2 cents' worth of solution to the wrong problem, I'd want to avoid generating a lot of temp lists in case the imput was really large. E.g., >>> list1 = list('abcdebxyz') >>> list2 = list('pqqr') >>> d={} >>> d=reduce(lambda d,item: d.setdefault(item) or d,list1,d) >>> d=reduce(lambda d,item: d.setdefault(item) or d,list2,d) >>> d.keys() ['a', 'c', 'b', 'e', 'd', 'q', 'p', 'r', 'y', 'x', 'z'] Or, for a one-liner, >>> dict(map(None,list1+list2,[None])).keys() ['a', 'c', 'b', 'e', 'd', 'q', 'p', 'r', 'y', 'x', 'z'] Regards, Bengt Richter From joe.sixpack at whoopie.com Wed Sep 18 16:45:58 2002 From: joe.sixpack at whoopie.com (Joe Sixpack) Date: Wed, 18 Sep 2002 20:45:58 GMT Subject: Is there a list comprehension to do this? Message-ID: Is there a list comprehension or other 'cleaner' or 'prettier' way to do the following: >>> xx = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) >>> ww = [] >>> for i in range(0, len(xx), 2): ww.append((xx[i+1],xx[i])) >>> ww [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)] >>> Thanks in advance... From hellen at claggetts.net Sat Sep 14 22:28:02 2002 From: hellen at claggetts.net (Jonathan Claggett) Date: 14 Sep 2002 19:28:02 -0700 Subject: representing a literal single slash Message-ID: Here is an easy question (I'm hoping). I'm trying to process a string so that all doubled up backslashes (\\) are replaced with a single backslash (\). The obvious approach doesn't work since a single backslash can't end a string: str = str.replace('\\', '\') # broken So, how does one represent a literal single slash? unicode or hex values perhaps? Thanks, Jonathan From Oschler at earthlink.net Wed Sep 4 08:57:01 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Wed, 4 Sep 2002 08:57:01 -0400 Subject: Why Python? References: Message-ID: <2Knd9.87$2L.4549@e3500-atl2.usenetserver.com> "RPM1" wrote in message news:unbp765rbsn809 at corp.supernews.com... > > > I think you should try coding in C. It's used everywhere for > everything. It's faster than about any other language. > Most other languages are written in C. Including Python. :) thx From tjreedy at udel.edu Thu Sep 5 09:24:03 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 05 Sep 2002 13:24:03 GMT Subject: Why read-only nested scopes? References: Message-ID: "Duncan Booth" wrote in message > And don't forget that when the nested function is called the frame object > may no longer exist: nested scope variables can continue to exist after the > frame in which they were created has been destroyed. Example: >>> def adder(x): ... def _(y): ... return x+y ... return _ ... >>> a5=adder(5) >>> a5(7) 12 Here, adder is a factory that turns out callable instances. It could instead be written >>> class adder: ... def __init__(self,x): ... self.x = x ... def __call__(self,y): ... return self.x + y ... >>> a5=adder(5) >>> a5(7) 12 If one want writable persistent variables, one can use the class syntax, which also allows for writable class rather than instance variables. Terry J. Reedy From hancock at anansispaceworks.com Fri Sep 6 16:50:05 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 06 Sep 2002 13:50:05 -0700 Subject: Python class ( Prolog ) ??? References: <20020905234600.11264.60328.Mailman@mail.python.org> Message-ID: <3D7914FD.5D713A48@anansispaceworks.com> From: Christophe Delord > On Thu, 05 Sep 2002 21:57:20 GMT > "Joseph A. Knapka" wrote: > > > Luis wrote: > > > Does anyone have a class that provides the functionality of prolog ??? > > > There's a SourceForge project that enables you to call > > GNUProlog from Python: > > > > I have written a module in Python to mix Prolog and Python. It was just a funny > exercise. It is not complete and rather slow but if you are curious you can download > it: http://christophe.delord.free.fr/en/pylog/ You may also be interested in the "unofficial" python-logic SIG: http://www.logilab.org/python-logic/ Which was recently mentioned on the edu-sig at python.org list. Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From sholden at holdenweb.com Mon Sep 9 16:07:34 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 9 Sep 2002 16:07:34 -0400 Subject: web crawler help? References: <668b76ce.0209090652.4b074a1b@posting.google.com> Message-ID: "Carl" wrote in message news:668b76ce.0209090652.4b074a1b at posting.google.com... > I just wanted to say also that a lot of sites have a robots.txt file > in the root directory with a list of pages the crawler shouldn't troll > through. it's polite to honor it if you're grabbing tons of pages from > a server. Probably fine to ignore if you're not using a lot of server > time and only doing a few simple tasks. Good point. I didn't mention it because I know that webchecker (with which I am much more familiar) does honour the robots.txt file, while for some reason (probably completeness?) websucker doesn't. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From henrik.motakef at web.de Mon Sep 23 07:45:40 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 23 Sep 2002 13:45:40 +0200 Subject: UpToDate SOAP-module ?? References: Message-ID: <87elbllyjf.fsf@pokey.henrik-motakef.de> "Thomas Weholt" <2002 at weholt.org> writes: > Anyway, if you want to provide more information about why I safely can > ignore SOAP feel free. It would make my project a bit less complicated so > I'd be glad to skip it. :-) Try a Google search including the term "REST" (or Representational State Transfer in full length) for an alternative view on how web services could work. xml.com also has some articles about it. Regards Henrik From magnus at thinkware.se Tue Sep 17 09:43:38 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Tue, 17 Sep 2002 15:43:38 +0200 Subject: Larry Wall's comment on python... References: <20020913020740.2dae5bb6.rm@no-mail.com> Message-ID: <3D87318A.4020405@thinkware.se> > Well... it reminds me when I was young, and we had to program using > ABACUS. It was really somewhat different outlook on programming. That's nothing. We had to program in a cardboard box in the middle of the motorway, our manager sliced us to pieces every morning, and we had to eat rocks! Phew, these kids these day... When you tell them how we had it, they hardly believe us... From DGustafson at attbi.com Fri Sep 20 13:22:36 2002 From: DGustafson at attbi.com (Dave Gustafson) Date: Fri, 20 Sep 2002 17:22:36 GMT Subject: IDL help? Message-ID: I'm still trying to get a COM server written in Python to be accessable from .NET. So far, I understand that I need to create a .idl file for the server and compile that using MIDL to a .tlb type library so that the COM server can be registered. I *think* that the insides of this .idl file actually needs to use the ODL syntax? I've tried inspecting the type definitions exposed by the ITypeInfo Viewer in the OLE/COM Object Viewer for a COM executable, but am having a hard time translating the interface definitions into something I can use for my Python library. Can anyone help by pointing me to a Python based COM server that works so that I could install it and inspect the type info as an example? Or could someone help with the syntax required to create the .idl for a simple example like the one in Mark H's book... (included below...) # SimpleCOMServer.py - A sample COM server - almost as small as they come! # # We simply expose a single method in a Python COM object. class PythonUtilities: _public_methods_ = [ 'SplitString' ] _reg_progid_ = "PythonDemos.Utilities" # NEVER copy the following ID # Use "print pythoncom.CreateGuid()" to make a new one. _reg_clsid_ = "{65C3A684-9077-4911-A58D-833A85B8C096}" def SplitString(self, val, item=None): import string if item != None: item = str(item) return string.split(str(val), item) # Add code so that when this script is run by # Python.exe, it self-registers. if __name__=='__main__': print "Registering COM server..." import win32com.server.register win32com.server.register.UseCommandLine(PythonUtilities) Thanks in advance! Regards, Dave From gerhard.haering at gmx.de Mon Sep 16 00:53:06 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Mon, 16 Sep 2002 06:53:06 +0200 Subject: Source code In-Reply-To: References: Message-ID: <20020916045306.GA2250@lilith.ghaering.test> * Terje Johan Abrahamsen [2002-09-15 23:31 -0500]: > If I would like to write some code that would not be possible for > others to read, after I distribute the program, would Python be > suitable? I know that there are a few programs like Py2Exe, that > creates .exe files. But, I also saw this: > > -------------------- > A zip-compatible archive is built, containing all files from this > directory as well as your script, and appended to a custom python > interpreter supplied with py2exe. > -------------------- py2exe contains Python byte code. Python byte code can be transformed into Python source code, but all comments are lost. > Doesn't sound like it is protected very well. Is there some > alternative to Py2Exe that can do the job, or should I look for a > compiled language instead? You should perhaps reconsider if and why you need to hide your source code. -- Gerhard From whisper at oz.net Mon Sep 9 19:17:08 2002 From: whisper at oz.net (David LeBlanc) Date: Mon, 9 Sep 2002 16:17:08 -0700 Subject: Windows/DOS: double clicking a .py file In-Reply-To: Message-ID: cmd.exe will accept a flag telling it to stay open after something is run. You can create a shortcut along the lines of: cmd /K python myscript.py You could also add this to the cmd shortcut itself if you have one, but that generally turns out to be a major pain since all dos-window based apps will then leave their windows open. A nice aspect of using a custom cmd shortcut is that you can set colors and fonts and window size just for this app which might help distinguish it if you have a lot of dos windows open. You can set the screen buffer height to a high number so you can scroll really far back (not a good idea to make the screen buffer width greater then the window width though). you can type 'help cmd' in a dos window for more info on cmd switches. HTH, David LeBlanc Seattle, WA USA > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Just > Sent: Monday, September 09, 2002 15:47 > To: python-list at python.org > Subject: Re: Windows/DOS: double clicking a .py file > > > [Just] > > > impossible to actually see the exception... Is there a way > > > to keep the dos prompt window in this case? > > [Bjorn Pettersen] > > Try something like the following... We've had much success with > > automatically emailing the traceback back to the developer using the > > cgitb module -- you can never trust users to give you good error reports > > besides the cgitb module provides much more context than the > > standard exceptions... Let me know if you'd like the code... > > > > try: > > your code here > > except: > > import msvcrt, traceback > > traceback.print exc() > > print 'Hit a key to exit' > > while not msvcrt.kbhit(): > > pass > > Ah, that looks like a good trick, I will try that. > > Thanks for your code offer, but in most cases I will have to ask for the > input data anyway, so a simple traceback is good enough for now. > > Just > -- > http://mail.python.org/mailman/listinfo/python-list From jwbaxter at spamcop.net Sat Sep 7 18:24:18 2002 From: jwbaxter at spamcop.net (John Baxter) Date: Sat, 07 Sep 2002 15:24:18 -0700 Subject: None or 0 References: <3d7a2b6b.92959728@news.cybermesa.com> Message-ID: In article <3d7a2b6b.92959728 at news.cybermesa.com>, joconnor at cybermesa.com (Jay O'Connor) wrote: > >Go into (English-speaking) classrooms, and you're going to hear chants > >of "5 and 1 is 6" not "5 and 1 is 1". > > Because in that contexts "and" means "plus" and in this context "and" > means "logical and" Agreed and understood. But not helpful to the programming for everyone cause. --John From bokr at oz.net Sat Sep 28 14:03:57 2002 From: bokr at oz.net (Bengt Richter) Date: 28 Sep 2002 18:03:57 GMT Subject: Python threading? References: Message-ID: On Thu, 26 Sep 2002 11:39:04 -0400, Tim Peters wrote: >[Robert Oschler] >> Having written _many_ state machines in my life, which async programming >> boils down to in one form or another, I feel it depends on the task. >> ... >> Contrast this with a simple procedure call where a linear series of >> function calls are made, each with appropriate error handling and status >> adjustment, in a pleasant centrally located manner. > >[Thomas Heller] >> I wonder if generators can come to a rescue here? > >Absolutely. Read the start of PEP 255. > >> Still trying to get them into my head... > >Think of them as resumable functions. You're familiar with functions that >remember their own data state across calls, via abusing globals, or via >declaring private static vrbls, in C. Methods on objects often do the same >by stuffing their state into instance attributes between calls. A generator >remembers its data state across resumptions simply by virtue of that its >local variables don't vanish, and also remembers its control-flow state >across resumptions. Remembering local data state by magic is a real >convenience, but can be simulated in many other ways with reasonable effort; >it's the ability to remember and restore control-flow state by magic that >can make generators more than merely convenient. > Any thoughts on defining the next method with a generic *args optional arg list and making it visible to an executing generator function g as g.__args__ ? g.__args__ would then just be () for current usage, and could be backwards-compatibly ignored as desired. I'm thinking it would, e.g., provide a channel to pass messages etc to a running task-implemented-as-generator. Or you could pass control info to a tokenizer, e.g. telling it to back up one and switch to profuse-info mode before yielding again, or whatever. Another thought is to pass optional return args in the args tuple attribute of the StopException object. This could be used variously, but might be used to return a final result from a child task, where ordinary yields might be reserved for control info for a dispatcher. Or it could be used to distinguish exceptional return conditions without using other exceptions. Etc., etc. This could also be reverse-compatibly ignored, but I think the two thoughts above could open up a lot of possiblilities. Perhaps they have both been discussed before? Regards, Bengt Richter From jb at cascade-sys.com Tue Sep 17 01:26:30 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Mon, 16 Sep 2002 22:26:30 -0700 Subject: Source code References: <3d868ccc$1@news.sentex.net> Message-ID: <3D86BD06.3050106@cascade-sys.com> Peter Hansen wrote: > Copyright is actually a passive thing now, as opposed to active. > That is, you don't have "to copyright your work", because unless > you explicitly disclaim the copyright, you automatically get it. True. > As I recall, this was not always the case in at least the U.S., > but has been the case for a number of years now. True. Furthermore, even if you formally assign the copyright to somebody else, I understand ownership eventually reverts to the original author after a lengthy period (45 years or something). Evidently it preserves the copyright for the heirs of the author. --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From jarober at gosmalltalk.com Sun Sep 22 15:07:55 2002 From: jarober at gosmalltalk.com (James A. Robertson) Date: Sun, 22 Sep 2002 19:07:55 GMT Subject: Smalltalk vs. Python and COM was Re: Byte Magazine and Smalltalk References: <3d87a686@tobjects.> <3d87dd7c$1@tobjects.> <20020918.115128.1605894428.1527@cybermesa.com> Message-ID: On Sun, 22 Sep 2002 20:29:27 +0200, "GerritM" wrote: >"Pino Gargiulo" schreef in bericht >news:amkup0$qtb$1 at fe2.cs.interbusiness.it... ><...snip...> >> >What is VWNC? What end level application do you want to support and/or >build? > VWNC is VisualWorks non-commercial. To download it and try it out, visit http://www.cincom.com/smalltalk, and follow the download links >The ActiveState distribution I suggested is a Python distribution >("batteries included") which allow you to do nearly everything. Additional >packages can be found at many places a.o. in the vaults of Parnassus. > >regards Gerrit James Robertson Product Manager, Cincom Smalltalk From andrewm at object-craft.com.au Sun Sep 15 22:48:23 2002 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Mon, 16 Sep 2002 12:48:23 +1000 Subject: Pickling slotted instances In-Reply-To: Message from loewis@informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) of "12 Sep 2002 12:12:45 +0200." References: Message-ID: <20020916024823.B64683C8FF@coffee.object-craft.com.au> >> Instances using __slots__ can't be pickled - is there a fundamental reason >> why this is so, or is it simply yet to be implemented? > >See python.org/sf/520644 for a longer discussion. I'd actually already found several discussions like that while googling and reading python-dev archives. But I'm still no wiser - the closest I can come to an answer is "it's not quite trivial and therefore hasn't been done yet". Guido says: The solution space is large, and I don't want to rush it, hence the decision to make it fail cleanly in 2.2.1 -- that's the best I can do. Fair enough (I'm using the CVS 2.3, btw - it can't pickle slots either). I'm really just wondering what makes the solution space large: my superficial understanding suggests all the necessary information is readily available for serialising the object's state (but I can see metaclasses make it complex). The SF bug you quote suggests to me that one problem is that internal machinery that uses slots assumes that slots are not pickled, and would get upset if slotted attributes suddenly resumed their old values. >> At first glance, a __getstate__ for a slotted class could be as simple as: >> >> def __getstate__(self): >> attrs = [getattr(self, attr, None) for attr in self.__slots__] >> return self.__slots__, attrs >> >> What am I missing? > >That won't work: it won't access the slots of the base type. Also, you >are missing a __setstate__ implementation. Indeed. The code snippet was intended as a discussion point, rather than a serious implementation... 8-) -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From jb at yahoo.de Tue Sep 10 06:34:56 2002 From: jb at yahoo.de (JB) Date: Tue, 10 Sep 2002 12:34:56 +0200 Subject: Python 2.3 References: <3d7cfc19_5@news.newsgroups.com> <5t0qnu0dfbebm1uvk1v93msk4tespgp6bn@4ax.com> Message-ID: <3d7dc8cd_1@news.newsgroups.com> Gon?alo Rodrigues wrote: > There are no plans to implement rationals. There is > however a Rat class in the demo dir, implementing > rationals in pure Python. Thx. But there is probably no way to write a function f Rat x Rat --> Rat and then at the input prompt write f(2/3,-3/2). -- Janos Blazi -----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World! -----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =----- From max at malva.com.uaREMOVE.IT Tue Sep 24 07:36:03 2002 From: max at malva.com.uaREMOVE.IT (Max Ischenko) Date: Tue, 24 Sep 2002 14:36:03 +0300 Subject: Reloading code without shutting down the app Message-ID: <3nipma.itu.ln@cvs> Hello. I have an application which processes some incoming data (recv. as UDP packets). Currently it is implemented as two threads: first is recieving data and "put" it into Queue.Queue while second thread "get" data from the queue and process it. The problem is when I restart my application to load new changes some packets could be lost due to unreliable nature of the UDP protocol. The solution could be to use TCP-link instead of Queue to bind the producer and the consumer programs. Then, if the consumer is down the producer would accumulate data and send it when the link would be restored. While workable, this solution seems too complex to me. Changing UDP transport to TCP is outside of my scope either. Does python have some ways to reload source code of already running modules? For example, when consumer recv. a SIGHUP it would delete currently used objects/classes/modules, import all again, creates objects and continues to process the data from the Queue. Is it possible? And how? -- Real Programmers Don't Use Pascal! From Hobbes2176 at yahoo.com Wed Sep 18 22:54:33 2002 From: Hobbes2176 at yahoo.com (Mark) Date: Thu, 19 Sep 2002 02:54:33 GMT Subject: Minimal debug/rep functionality Message-ID: Hello all, In a nutshell, what I'd like to do is develop a utility that would print out every line in a python program as the program executes (I may even just want to print line numbers). I can see hints of how to do this in pdb (and more directly in the underlying bdb class) and also in the code module. So, 1) Should I try and inherit a class and override some methods or should I just pull out the relevant code and hand spin a small interpreter. 2) Anyone have a 20 liner solution for this? Thanks. Regards, Mark From sholden at holdenweb.com Wed Sep 25 07:35:05 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 25 Sep 2002 07:35:05 -0400 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> Message-ID: "Stuart D. Gathman" wrote in ... > On Sat, 21 Sep 2002 23:10:09 -0400, Christian Tismer wrote: > > > Dan Bishop wrote: > > > > Please name one other real-world situation in which decimal > > > arithmetic is actually *needed*. > > > > There is no reason to argue about that. Decimal arithmetic is exact for > > most of the operations bankers require. They have been demanding for it > > since decades, and they will not drop it. > Strangely enough, my experience has been somewhat different. You can perform the arithmetic by mixing chickens' blood with short sticks if you want, the thing that interests the financial guys is *correct answers*. > Let me add a horror story of what happens when financial > applications do *not* demand fixed point/decimal arithmetic. > > We took on a client whose accounting system used binary floats for all > dollar amounts. And I mean *dollar* amounts, not penney amounts. Since > all pennies were approximate, the total due at the bottom of the invoices > would rarely match what the customer would get adding up the line items > on a calculator. It was only off by a few cents, but it tended to make > customers lose faith in the system. Statements also did not add up, and > the Balance Sheet didn't balance. > In point of fact it is perfectly possible to use floating-point for such purposes. The important thing is not to allow rounding errors to accumulate, which effectively means rounding to 2DP or whatever is required for each figure that will be presented as part of any total. > We converted their system to use fixed point, and now everything balances > and totals to the penney. Unfortunately, their CPA keeps his own version > of their General Ledger on Excel with binary floating point. The CPA > balance sheets do not balance. The CPA General Journal transactions do > not balance. I demonstrated with a calculator that the CPA figures did > not balance, but they insisted that we had to go with the CPA figures > because he is a CPA, and I'm just a programmer. > This is tricky since their new General ledger does not accept unbalanced > transactions. > Although Excel will use binary floating point, the problem is precisely its failure to round the figures it's presenting, which *will* allow rounding errors to creep in. Excel has a calculation option to use "precision as displayed", shich will help a lot. Unfortunately you are pissing in the wind trying to get a CPA to admit there may be things they don't understand about arithmetic. Make sure that if you *can* get him(?) to try this option he uses a copy iof his spreadsheet, since it will change the precision of constants permanently. > My solution was to create a 'CPA adjustment' account to contain > all the discrepancies, and manually decide how to allocate the > extra/missing pennies for the CPA transactions. > I remember having to explain why it was never going to be possible to reconcile a multi-currency sales ledger when daily rate changes meant that a payment arrived having a different value than it had when it set off. At the same time the accountant educated me as to why columns of figures such as invoices really must "add up". I discovered the funniest thing when a few years later I worked with a bunch of five CPAs to build a combined sales/purchase/general ledger with integrated job costing, job pricing and payroll. Obviously we had several interesting discussions about what signs should have which meaning in every possible context. I discovered that even experienced accountants frequently use soem rule relating back to the physical circumstances of their training, like "debits go in the column nearest the window". So they don't actually think all the time in abstract concepts. > There ought to be severe penalties for idiots that use floating point > dollars for financial applications. If forced to use floating point > (e.g. because customer demands BASIC), then keep money amounts in > whole pennies (or whatever the smallest currency unit for the country > is), and divide by 100 (or whatever) for printing only (or just add the > decimal point yourself). > I disagree. The penalties should be reserved for those who undertake this kind of work without understanding what they are getting into. The methods used must satisfy the customer, but the customer isn't usually bothered how the results are achieved. In my particular case everything was done in BASIC Plus, so any kind of decimal computation was right out. Floats (appropriately rounded at every step) were perfectly acceptable. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From jeff at sasmor.com Sat Sep 14 15:57:17 2002 From: jeff at sasmor.com (Jeff Sasmor) Date: Sat, 14 Sep 2002 19:57:17 GMT Subject: Python11 Message-ID: Is there any definitive information on the next Python conference, Python 11? I've read the conferences-discuss archive on Python.org (http://mail.python.org/pipermail/conferences-discuss/) and the discussion seems to be tapering off. IIRC, by last year at this time there was already a call for papers. It would be a shame not to have a forum for things Pythonic in 2003. Just my 2 cents, but Python needs more visibility and not less! #-------------------------------- Jeff Sasmor jeff at sasmor.com From SBrunning at trisystems.co.uk Wed Sep 18 10:34:26 2002 From: SBrunning at trisystems.co.uk (Simon Brunning) Date: Wed, 18 Sep 2002 15:34:26 +0100 Subject: monetary applications [was: Python GUI app to impress the bos s?] Message-ID: <31575A892FF6D1118F5800600846864DCBD817@intrepid> > From: Alex Martelli [SMTP:aleax at aleax.it] > > Perhaps the lack of a FixedPoint type? > > http://starship.python.net/crew/aahz/FixedPoint.py A candidate for the standard library, perhaps? I use it all the time, and if nothing else, it would be nice for DB-API modules to know that it was there, so that they could return instances of it for NUMERIC and DECIMAL values. Cheers, Simon Brunning TriSystems Ltd. sbrunning at trisystems.co.uk ----------------------------------------------------------------------- The information in this email is confidential and may be legally privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot accept liability for statements made which are clearly the senders own. From peter at engcorp.com Fri Sep 6 08:52:18 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Sep 2002 08:52:18 -0400 Subject: how could we know which module is imported already ? References: <7153651c.0209060233.2a72caaa@posting.google.com> Message-ID: <3d78a4e8$1@news.sentex.net> black wrote: > want to know how many and what the module is imported~ If you would explain why you want to do this, you might get some even better suggestions than just "sys.modules". -Peter From lac at strakt.com Thu Sep 26 10:07:06 2002 From: lac at strakt.com (Laura Creighton) Date: Thu, 26 Sep 2002 16:07:06 +0200 Subject: off topic -- spam assassin Message-ID: <200209261407.g8QE76Wo028975@ratthing-b246.strakt.com> On the advice of several of you here, I installed spam assassin, and had a pleasant six months of nearly spam free mail. Thank you, each and every one of you who recommmended it. Alas, the spammers have got smarter, and I am now getting 25+ pieces of spam that aren't caught by spam assassin every day again. :-( What's new for our side of the arms race? Laura Creighton From tjreedy at udel.edu Thu Sep 19 11:01:37 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Sep 2002 15:01:37 GMT Subject: Nokia 3310 SMS Application, done:connecting to serial port(linux/win), done:reading some hex like \x00 . . ., problem:write/send command! noresponse References: <52facf1d.0209190533.3048e62c@posting.google.com> Message-ID: "Polerio Babao Jr.II" wrote in message news:52facf1d.0209190533.3048e62c at posting.google.com... > Greetings: Python Masters > > I wanted to create an SMS application using Nokia 3310 with > DAU-9P(data cable), > When I connect to the port for the first time I get the ser.read() > output like this \x00\x0c I think. But that's two response is what I > get on my first connect. After that when I envoke ser.read() again, I > get nothing. I know nothing about Nokia but have had experience (and battle scars) programming serial i/o. Two suggestions. First: make *sure* you have serial protocol set right -- baud rate, data bits, stop bits, parity, handshaking? Also make sure you have proper pins active and properly connected. It is easy to be off. Second: if you do not have one, get a breakout box that lets you see activity at the port. Its the equivalent of having a volt-ohm-ammeter. You plug cable into box and run another cable from box to port. A simple one just has lights that flash when a signal passes thru. More complicated one allows some signal patching. I got mine long ago from Inmac. Would check google for source now. That you *seem* to be getting response from Nokia and then not is puzzling. Breakout box would give you better idea of what is happening when. Terry J. Reedy From sholden at holdenweb.com Thu Sep 12 11:49:19 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 12 Sep 2002 11:49:19 -0400 Subject: "str.contains(part)" or alternatives? References: <6g2g9.295995$aA.51455@sccrnsc02> Message-ID: "Pete Shinners" wrote > Delaney, Timothy wrote: > > In fact, this was the deciding factor in Guido changing his position on 'if > > s1 in s2'. A string has sequence-like behaviour (e.g. it is iterable, > > individual characters can be indexed), but also has its own behaviour (e.g. > > substring containment, all elements are single-character strings). > > does this mean we can also now do this? if so, nifty > > >>> 1,2,3 in range(10) > 1 > >>> 3,2,1 in range(10) > 0 > No, you can't. 1,2,3 is in [1, (1, 2, 3), 2, 3] but it won't be in [1, 2, 3, 4] - strings are a less general structure than lists or tuples, and the "subsequence" implementation will apply to strings *only*. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From info at voidhobo.de Tue Sep 17 19:24:31 2002 From: info at voidhobo.de (John D. Boy) Date: 17 Sep 2002 23:24:31 GMT Subject: CGI question References: Message-ID: Thanks to everyone who responded; this was more than I had even hoped for! I will probably do what you recommended, Ian. I didn't think it would be as easy as that. It is the most elegant and (even) more aesthetically pleasing than my initial idea. Unfortunately, I do not have access to my webserver's configuration to use the rewrite module, but I will see what I can do within my .htaccess. Thanks again, and all the best, --John In article , Ian Bicking wrote: > On Tue, 2002-09-17 at 13:04, John D. Boy wrote: >> I am working on a simple CGI script to use as a framework for a website >> of mine. Basically, I want it to work as follows: When somebody accesses >> the site, a CGI (called e.g. index.py) is run. It takes an html-template >> and fills it with content from another file, called e.g. index.dat, and >> returns the completed html-document. When I want to present another >> page, I want the url to look like this: http://my.domain.name/?page. In >> that case, index.py would fill the same template with the content of a >> file called e.g. page.dat. > > BTW, I wouldn't recommend doing it this way. If you have a cgi script > at, say, /page.py, you can access URLs like /page.py/path/to/something > -- "/path/to/something" will be stored in os.environ['PATH_INFO']. > > Then your URLs will look like real URLs, and not like queries. And for > mod_rewrite people, if you want to serve the root of your domain off > that script, I believe this will work: > > RewriteEngine On > RewriteRule ^/(.*)$ /path/to/page.py/$1 > > (I don't think you can use Alias in this case, but I might be wrong) > > Ian -- John D. Boy "Information Superhighway" is email just an anagram for "I'm on hypertext a huge wispy rhino fart." From bokr at oz.net Wed Sep 4 00:38:34 2002 From: bokr at oz.net (Bengt Richter) Date: 4 Sep 2002 04:38:34 GMT Subject: default tuple unpacking? References: <3d758180$1@news.sentex.net> <3d7584d2$1@news.sentex.net> Message-ID: On Tue, 03 Sep 2002 23:58:39 -0400, Peter Hansen wrote: >Peter Hansen wrote: >> Huaiyu Zhu wrote: >> >>> It is often very convenient to have default arguments such as >>> >>> def func(a, b, *c): ... >>> >>> Is there a way to use this in statements too? Examples: >>> >>> a, (b, *c), *d = e > >Hmm... I think there might be an inconsistency or an unexpected >result in this. What if e already contains a tuple? > > e = (1, 2, 3) > *a = e # a is ((1, 2, 3), ) > >That seems sensible, and it's just what happens if you pass >"e" in to a function defined as "def func(*a)". > >Now what about this: > > a, *b = e # a is 1, b is (2, 3) > >That's one possible result, and presumably the one you want with No, I think you'd want it to match the function effect >this syntax, but it's not what you'd get with the function syntax: > > def func(a, *b): > print a > print b > > func(e) > >Here of course you get (1, 2, 3) in "a" and () in b. To get the Fine >same as the proposed syntax above, you can't pass in a tuple, but >have to pass the parameters separately: but you can separate them by unpacking with '*' > > func(1, 2, 3) # now a is 1, b is (2, 3) > You can write the call as func(*e) >The problem is that in function calling, you can pass in a single >tuple, which is one argument, or you can pass the elements separately >as multiple arguments, which is when the special * syntax kicks in. > Kick it in on the calling side if that's what you want. >When doing assignment with tuples you don't have the same two options: > > a, *b = 1, 2, 3 > >is the same as > > a, *b = (1, 2, 3) > >So maybe this won't fly. Comments? > With function calling, '*' gets you packing or unpacking depending on context. Why not also for the above? I.e., a, *b = 1, 2, 3 # => a is 1, b is (2, 3) and a, *b = (1, 2, 3) # => a is (1, 2, 3), b is () but a, *b = *(1, 2, 3) # => a is 1, b is (2, 3) much as in >>> def foo(a,*b): print 'a is %s, b is %s' % (a,b) ... >>> foo(1,2,3) a is 1, b is (2, 3) >>> foo((1,2,3)) a is (1, 2, 3), b is () >>> foo(*(1,2,3)) a is 1, b is (2, 3) and >>> e=(1,2,3) >>> foo(e) a is (1, 2, 3), b is () >>> foo(*e) a is 1, b is (2, 3) but >>> f=(1,2) >>> foo(f,3,4) a is (1, 2), b is (3, 4) >>> foo(*f,3,4) File "", line 1 foo(*f,3,4) ^ SyntaxError: invalid syntax >>> foo(3,4,*f) a is 3, b is (4, 1, 2) Hm. Why no unpacking at the front? (Ok, it's easier not to ;-) Regards, Bengt Richter From peter at engcorp.com Sat Sep 14 02:39:50 2002 From: peter at engcorp.com (Peter Hansen) Date: Sat, 14 Sep 2002 02:39:50 -0400 Subject: Part Time Help Needed References: Message-ID: <3d82d9a5@news.sentex.net> (Cross-posting removed.) Demi Vitalis wrote: > Part Time Work at Home: PHP Programmers > > First let me open by saying this; > > I am a very seasoned programmer but have no friends or associates ... Yeah. Well. In case it isn't obvious to someone here in comp.lang.python, this is not likely a legitimate proposal. I strongly advise against anyone doing more than what Gerhard has already done. -Peter From gua81 at XXXyahoo.com Mon Sep 23 05:34:21 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Mon, 23 Sep 2002 19:34:21 +1000 Subject: Python and cgi and problem! Message-ID: Hi Im currently making a cgi script in python which list all the files&directory in a directory and list them into an html file with all the files linked to the actual file. ..... did what I just said make any sense? Currently I can list all the files and directories and print it out in the html file. my problem now is how to add the anchor tag ??? here is the line which prints the files&directories in the html file: print crap , where crap is a filename such as colour.txt From tjreedy at udel.edu Fri Sep 27 15:53:06 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Sep 2002 19:53:06 GMT Subject: Is Boost Python version 2 ready? References: Message-ID: "Robert Oschler" wrote in message news:MvZk9.12124$Lg2.3584877 at news2.news.adelphia.net... > Is Boost Python version 2 ready for primetime yet? Not to exactly answer... from post on PyDev list, I believe they want to test it with Python 2.2.2 (due in about 10 days?) before calling it finished. TJR From jdavis at empires.org Thu Sep 19 03:03:53 2002 From: jdavis at empires.org (Jeff Davis) Date: Thu, 19 Sep 2002 07:03:53 GMT Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> <3d89121f@news.ivm.net> Message-ID: The advice I was about to give you followed what Steve had to say, so I have included my comments here. > Whenever I read "CGI" I also read "a pain to maintain" some words > later... ? It's a project with a (modest) possibility to turn into a > product, so both portability and maintanability are issues. Well, CGI isn't considered the best development environment. It isn't horrible though (unless performance is an issue...).The main advantage to CGI is that it's portable, and you don't want to go rewrite your app. One thing you might do is write your program in python, and use libraries to handle everything. That way if you do need to put it on something unexpected, you can just rewrite a few lines. > On the other hand, Mark also meant CGI/Apache, writting Python/Apache, > right? Not necessarily. If you think you'll at least be able to install some software on the target webserver, you could use mod_python. Use the publisher handler, and read the simple docs on the publisher handler (a part of mod_python) and the cgi module (thats a python module with routines that are useful for any web programming, not just CGI). Or, you might want to stick with python CGIs. CGIs seem safer, because I don't see as many possible problems or stumbling blocks.If it get's turned into some other software later, it will be easy to change it from CGI to something else if you code defensively. Regards, Jeff From joconnor at cybermesa.com Thu Sep 5 11:34:30 2002 From: joconnor at cybermesa.com (Fearless Freep) Date: 5 Sep 2002 08:34:30 -0700 Subject: Getting parameters in a walkback Message-ID: <7d3dc526.0209050734.65a0e85d@posting.google.com> I was banging around with traceback and trying to drill down into frame objects and such and I'm kinda stuck. What I'd like to do is find out if, when an Exeption is raised in a method or function, is it possible to get the values of the parameters that were passed in? Something like... def divide (x,y): return x / y def divideTwoNumbers (a,b): return divide (a,b) try: divideTwoNumbers (1,0) except: # now what? This is kinda a contrived example just to show calling a function that calls a function that will raise an exception back out to the top level. I can determine in the except: block that a divide by zero error was raised in devide(), but can I determine what the values for the two parameters (x and y) were? Like I said, a contrived example, but it could help in debugging larger systems if, for example, I tried to write to a file and the file didn't exist or something Thanks Take care, Jay From aleax at aleax.it Fri Sep 20 03:08:53 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 07:08:53 GMT Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <23891c90.0209190014.26c5bb9@posting.google.com> <7xk7lhb943.fsf@ruckus.brouhaha.com> Message-ID: <9Qzi9.117104$ub2.2497933@news1.tin.it> Paul Rubin wrote: ... > I'm finding it hard to imagine how any real-world financial > calculation using IEEE doubles could be off by as much as a penny. I suggest: http://www2.hursley.ibm.com/decimal/decifaq.html and other material involving M. Cowlishaw's long campaign for decimal arithmetic, including debates in the IEEE committee. E.g.: """ A more typical example is applying a 5% sales tax on an item (such as a $0.70 telephone call), rounded to the nearest cent. Using double binary floating-point, the result of 0.70 x 1.05 is 0.73499999999999998667732370449812151491641998291015625; the result should have been 0.735 (which would be rounded up to $0.74) but instead the rounded result would be $0.73. """ That's typical Python behavior today, btw (of course, since it uses the underlying floating binary representation): >>> 0.70 * 1.05 0.73499999999999999 >>> Should your business get tax-audited, inspectors may take a dim view of your shaving a cent off the sales tax due on each and every item you sell to the public at $0.70 -- "I found it hard to imagine" how rounding effects might affect the result (when the law specifies rounding to the nearest cent and always rounding half cents up) may not be an acceptable defense. Alex From pyth at devel.trillke.net Sun Sep 1 12:11:55 2002 From: pyth at devel.trillke.net (holger krekel) Date: Sun, 1 Sep 2002 18:11:55 +0200 Subject: yield keyword reserved In-Reply-To: <770604FC-BDC3-11D6-8A4A-00039351FE6A@mac.com>; from erikprice@mac.com on Sun, Sep 01, 2002 at 11:57:06AM -0400 References: <770604FC-BDC3-11D6-8A4A-00039351FE6A@mac.com> Message-ID: <20020901181155.D3893@prim.han.de> Erik Price wrote: > I'm sorry if this is an easily answered-question. I have Python2.2 > running on my system (it is installed on Darwin by default in Mac OS X > 10.2), and am learning about iterators from > , but the keyword > doesn't appear to be present on my system: > > Python 2.2 (#1, 07/14/02, 23:25:09) > [GCC Apple cpp-precomp 6.14] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> def generate_ints(N): > ... for i in range(N): > ... yield i > :3: Warning: 'yield' will become a reserved keyword in the > future > File "", line 3 > yield i > ^ > SyntaxError: invalid syntax > >>> With python2.2 you have to explicitely enable generators. put a from __future__ import generators at the beginning of a script or in an interactive session. With the future python2.3 you don't need this. holger From loewis at informatik.hu-berlin.de Mon Sep 30 13:23:42 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 30 Sep 2002 19:23:42 +0200 Subject: XMLRPC calls don't work in threads, or rather, they don't play well with others ! (help) References: <3D97D190.9030003@bcm.tmc.edu> <3D9885AD.2030603@bcm.tmc.edu> Message-ID: Steve Ludtke writes: > Already did this. It definitely seems to be the xmlrpclib calls that > are preventing the thread switching. I'll have to see if I can > come up with a simple demonstration script to show the problem. No need to do this. Instead, I recommend that you find out which of the functions in xmlrpclib is blocking, and then put print statements into *this* function, and so on, until you cannot find Python code for a function being called anymore. Regards, Martin From python-list at hendel.net Wed Sep 25 05:53:49 2002 From: python-list at hendel.net (Manuel Hendel) Date: Wed, 25 Sep 2002 11:53:49 +0200 Subject: comparing all values of a list to regex Message-ID: <20020925095348.GG57911@partagas.as.de.cw.net> I have to compare all values of a list to a regex. If the regex matches all list items the list should be added to a new list. If the regex matches just one list item, the list should be added to another new list. And last but not least, if the regex doesn't mutch at all, the list should be added again to another new list. Can someone help me with this? This is driving me crazy. Thanks, Manuel -- For ages I thought life was like fishing in a swimming pool. Now the water's all drained out! From gerhard.haering at gmx.de Fri Sep 27 18:23:04 2002 From: gerhard.haering at gmx.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: Sat, 28 Sep 2002 00:23:04 +0200 Subject: windows xp command prompt In-Reply-To: <576c1752.0209271411.6d7bb4c4@posting.google.com> References: <576c1752.0209271411.6d7bb4c4@posting.google.com> Message-ID: <20020927222303.GC7781@lilith.ghaering.test> * mike henley [2002-09-27 15:11 -0700]: > i have installed the activestate perl, python, tcl, and pragmatic > programmer's ruby. when i go to the command prompt on windows xp and > type perl for example... (or python, ruby... etc) i get the following > message. > > 'perl' is not recognized as an internal or external command, > operable program or batch file. > > in the control panel| system | advanced | environment variables | Path > i have > > C:\ruby\bin;C:\Python22;C:\Perl\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem > > does anyone know what i should do to fix this problem? (apart from the > obvious of restarting the machine) Close the console window and open a new one. Only upon starting the shell, the environment is read. -- Gerhard From Bill.Scherer at VerizonWireless.com Fri Sep 6 13:36:48 2002 From: Bill.Scherer at VerizonWireless.com (Scherer, Bill) Date: Fri, 6 Sep 2002 13:36:48 -0400 (EDT) Subject: Interapp communication under Python[Linux]? In-Reply-To: Message-ID: On Fri, 6 Sep 2002, Robert Oschler wrote: > My Python app will talk to 3 or 4 modules written in Java and C/C++. > Fortunately I have the source for the Java and C/C++ modules and I have > experience in both languages. Currently the external modules have no > provision for being accessed outside of the process they are running as. So > I'm wondering what the best protocol would be used to "glue it all > together". There a dizzying array of possibilities: > > 1) Have everybody talk to each other via SOAP (web services). > 2) Have everybody talk to each other via XML-RPC (Don't know much about this > method). > 3) Use Boost's SWIG interface for C++ to link the C/C++ modules to Python. > How to link to Java in the same manner? > 4) Use "sockets" and my own custom protocol for everybody. > 5) Code in Jython instead and use various methods above to talk to C/C++ > modules from Jython app. > 6) CORBA? (yikes!) > > So as I said, a lot of ways to get things done. I'd like to hear from those > of you that have actually done a lot of cross-app communication with Python > on what your experiences have been, and the pros and cons you encountered. Robert - Have a serious look at Spread (http://www.spread.org). There's a Python module for it on python.org, and I believe the Java interface is included with the code from spread.org. I've not used Spread from Java, but I have a bunch of different Python processes on half a dozen or so machines (Both Linux and Win2k), all communicating via spread. It's quite simple to use. The spread server daemon has been up since I started it, way back when the first Python spread module came up. It's stability is, so far, as good as the linux box upon which it runs. HTH, Bill -- Bill.Scherer at Verizon Wireless RHCE 807101044903581 From aleax at aleax.it Thu Sep 19 02:26:22 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 06:26:22 GMT Subject: shared mem & semaphores module References: Message-ID: Thomas Guettler wrote: ... > AFAIK there is no module for shared memory. mmap comes reasonably close. Alex From peter at engcorp.com Sun Sep 8 08:54:27 2002 From: peter at engcorp.com (Peter Hansen) Date: Sun, 08 Sep 2002 08:54:27 -0400 Subject: python program to watch a file - example. References: <3d7b3437$0$12727@echo-01.iinet.net.au> Message-ID: <3d7b486c@news.sentex.net> Top-posting Rob Hall wrote: > Bengt Richter wrote in message > news:ales54$2un$0 at 216.39.172.122... >>On Sun, 8 Sep 2002 01:47:12 -0400, "Wayne R" wrote: >>>I am trying to write a python program that will run as a deamon and [snip] >>>Any ideas or links to more info? >> >>Don't annoy people you want help from, for starters. >>What system are you targeting? (Outlook in the headers says you're on >>windows generating this abominable mix of actual message and useless cruft). > Get a fucking life Bengt!!! He wasn't that far off, Rob. The OP asks a question in a way that suggests Linux ("daemon" is not a typical Windows term) but posts in HTML from Windows. Even if the HTML itself was not as annoying as, say, top-posting is, the OP still ought to provide a little background to help us give a useful answer. -Peter From aleax at aleax.it Thu Sep 26 08:35:26 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 12:35:26 GMT Subject: Getting started References: <00a801c26511$4e084750$df7e4e18@brianspiv1700> Message-ID: James J. Besemer wrote: ... > Types are otherwise pretty secure in C++ except the "cast" mechanism > "foils" the type system and thus allows type errors to occur. Actually, unions are at least as bad -- they're not often used for type-punning because casts are handier for that, but if you took cast aways, people would (ab-)use unions (just like they abuse EQUIVALENCE in Fortran for similar purposes). Technically I believe that in C++ (not sure about the two ISO C standards -- I'm more definite that this was the case in Fortran-77 and I believe in Fortran-IV too) storing one union's member then retrieving another one puts your program in undefined-behavior land. In practice, I know of no existing compiler that goes to the bother of checking (e.g. by storing a hidden tag when you store into a union and checking whenever you retrieve from it -- even harder if you consider _pointers_ to the various members of the union). Alex From bokr at oz.net Sun Sep 29 16:53:17 2002 From: bokr at oz.net (Bengt Richter) Date: 29 Sep 2002 20:53:17 GMT Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: Message-ID: On 29 Sep 2002 17:06:53 GMT, Christopher Browne wrote: >Quoth "Steve Holden" : >> wrote... >>> > >> [ ... ] >> OK, so don't use whole pennies (or smallest currency) as your >> base, use 10,000ths of a penny, but still use integer arithmetic >> for your calculations. >> >> Floating point has too many rounding errors to be trustworthy; >> or, looking at it from another angle, floating-point calculations >> cannot be 100% accurate because of the way it's implemented. Floating point IS EXACT over a large range of values and operations. The problem is that people who don't understand exactly what is happening want to be safe (fine) and substitute FUD or downright misinformation (not fine) for fact in talking about it. > >The problem with FP is that FP involves the use of binary >approximations, which commonly cannot exactly represent decimal >values. > >Notably, the decimal fraction 0.1, which is /exactly/ 1/10, does not >have any exact encoding in binary. Its representation in binary is a >repeating binary fraction. How is that a significantly different problem from repeating decimal fractions? (E.g., 1/3. or 1/7. or wxyz/9999. which will give you 0.wxyzwxzy..?) > >When the (not unreasonable!) expectation is that computers ought to be >able to deal /exactly/ with plain simple decimal values turns out to >be wrong, that ought to lead people to think. > >But all too often it doesn't, as we get the typical reaction "Well, >IEEE FP values can be sufficiently exact for this range of numbers; >just use them right!" > >There's thirty years of experience now of programmers being able to >use COBOL and PL/1 to manipulate decimal values without having to go >into the numerical analysis effort to "just use FP right!" There's thirty years of experience now of programmers being able to use cars and trains to manipulate bodily location values without having to go into the numerical analysis effort to "just use diesel compression ignition right!" Many/most of them don't understand the details of the mechanisms they depend on, and don't care whether they're using gas/sparks or steam/coal or diesel underneath. Thirty years of commuting doesn't automatically give the commuter insight into engine technology. > >The "FP way" is that once in a while, you've got to insert operations >to round things appropriately. The "old school" folks can >legitimately gripe that they had decimal types that never required any >of that nonsense, and that they had those types before many of the >modern developers were even born. I'm curious what those "old school" folks thought their programs did when they had to divide or multiply, and how they conceived of the general rules behind the results they got ;-) IMO the big point re use of any kind of arithmetic in a program is that the definitive rules come from the customer's requirements (whatever the process of determining those ;-), and should be recorded as an unambigous specification. Then it's either implemented correctly or not, and it doesn't matter if you are internally manipulating decimals with digits represented in bi-quinary or using floating point, other than optimization or real time issues (ok possibly also understandability issues for the lucky maintainers ;-) A customer who wants to convert between European currencies according to law will probably have references to those laws in his spec. A customer who wants to control machinery or compress music is going to give you other rules to get right (not unlikely among them to watch out for patent and copyright law ;-) Regards, Bengt Richter From Padraig at Linux.ie Fri Sep 6 09:52:46 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Fri, 06 Sep 2002 13:52:46 GMT Subject: tree data structure References: Message-ID: Duncan Booth wrote: > Padraig Brady wrote in > news:Us1e9.2865$cP3.6131 at news.iol.ie: > > >>>assert result==('L0', [('S2', [('S0', [('Q1', [])]), ('S1', [('Q2', >>>[])]), ('S3', [])])]) >>> >>> >> >>It certainly does! >>Just one thing...Why use lists instead of tuples? > > > Specifically because you can't append to tuples, but you can append to a > list. > > However, a general rule of thumb is to use tuples where you want a record > (but don't want the overhead of a full-blown class). So each node here is a > record with the fields name,children. Use a list where you want to store a > collection of unknown length: so a list is appropriate for the children. OK > Note that neither your original list, nor the code I used actually force > this to be a tree, you could equally well have a graph with or without > cycles. You will find it impossible to represent a graph containing cycles > if you use tuples throughout. True, but I am assured that the parts of the graph I'm interested in will not have cycles. thanks again, P?draig. From ludal at logilab.fr Wed Sep 11 13:59:28 2002 From: ludal at logilab.fr (Ludovic Aubry) Date: Wed, 11 Sep 2002 17:59:28 +0000 (UTC) Subject: Anyone working on a line level python profiler? Message-ID: It looks like it is possible to do a line level profiler with the new profiling API in python 2.2 Has anyone started to work on such a tool ? Ludovic From aahz at pythoncraft.com Mon Sep 16 11:25:09 2002 From: aahz at pythoncraft.com (Aahz) Date: 16 Sep 2002 11:25:09 -0400 Subject: Are generator functions thread-safe? References: Message-ID: In article , Robert Oschler wrote: > >I know that a call to a generator function actually returns an independent >iterator object (mea culpa if I'm wrong on this), but are there any hidden >gotchas that would cause the use of the same generator function from >multiple threads, to result in a sharing (especially local storage) or >memory collision issue? The same gotchas for any other function: you're screwed if you share mutable objects without locks. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From eppstein at ics.uci.edu Wed Sep 18 17:27:24 2002 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 18 Sep 2002 14:27:24 -0700 Subject: A list comprehension to do this?... References: <3D88E4F5.B443918@quartercase.com> Message-ID: In article <3D88E4F5.B443918 at quartercase.com>, joe sixpack wrote: > Is there a list comprehension or other 'cleaner' or 'prettier' way > to do the following: > > >>> xx = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) > >>> ww = [] > >>> for i in range(0, len(xx), 2): > ww.append((xx[i+1],xx[i])) > > >>> ww > [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)] > >>> > > Thanks in advance... It's not much different, but it can easily be done with a list comp: >>> xx = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) >>> ww = [(xx[i+1],xx[i]) for i in range(0,len(xx),2)] >>> ww [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)] -- David Eppstein UC Irvine Dept. of Information & Computer Science eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/ From tim.one at comcast.net Mon Sep 16 18:50:04 2002 From: tim.one at comcast.net (Tim Peters) Date: Mon, 16 Sep 2002 18:50:04 -0400 Subject: difflib optimization -- wow (tim peters?) In-Reply-To: <20020916152504.A7537@unpythonic.net> Message-ID: [jepler at unpythonic.net] > wow, what a speedup! thanks, whoever it was (tim?) Don't thank me yet -- it's in a semi-broken state now, although you won't notice that when comparing text files containing text . By default, it's dynamically deciding what constitutes a "junk line" now, instead of using the "this is junk" regexp argument that nobody bothers to set. Given C source input, for example, it's now likely to decide that lines consisting solely of } are junk. Trying to synch up on what are really noise lines costs an enormous amount of time, so getting a better idea of what *is* likely junk saves an enormous amount of time. OTOH, if you have two files consisting solely of repetitions of "A\n" and "B\n" lines, the current code is going to decide they're *all* junk lines. That's the sense in which it's currently broken. > $ time python2.3 -O ~/pyunidiff.py foo.c foo2.c > /tmp/pat > > real 0m5.457s > user 0m4.640s > sys 0m0.110s > $ time python2.2 -O ~/pyunidiff.py foo.c foo2.c > /tmp/pat > > real 3m14.042s > user 3m7.480s > sys 0m1.180s > > foo.c and foo2.c are ~300k long C files from different releases of a > piece of software. the diff produced is nearly 250k. > > pyunidiff is at http://unpythonic.net/~jepler/pyunidiff.py Three attempts to connect to that timed out for me, so I don't know what pyunidiff is doing. Since ndiff outputs the full text of both input files, I wouldn't consider it a good thing if it produced an output smaller than its inputs (or, if that is a good thing, I'm on to a great new compression scheme ). > tim, I only need another factor of 30x and it'll beat diff(1) -u in wall > time (or 5x to beat diff(1) -u -d). It already gives files about 5% > shorter on the files I've tried (or on par with diff -u -d). What is "it", and 5% shorter than what? > I notice that the diff produced from 2.2 is marginally smaller, another > 1.5% or so. See above. You *seem* to be saying that 2.3's output is both 5% shorter and about 1.5% longer than 2.2's output. > The price to pay for the optimization? The difflib algorithm couldn't care less how long the diffs it produces are. It's aiming at human comprehensibility, not at minimality. Tell me that the new output is 1.5% less intuitive than 2.2's and then I'd care -- provided you could convince me you had an objective way to measure intuitiveness to two significant digits . It would have been a pointless exercise to recode diff's algorithm in Python. if-you-want-diff-you-know-where-to-find-it-ly y'rs - tim From Oschler at earthlink.net Tue Sep 10 13:21:16 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Tue, 10 Sep 2002 17:21:16 GMT Subject: Trouble upgrading to 2.2.1 References: <_qpf9.29862$w51.7937790@news2.news.adelphia.net> Message-ID: "Gerhard H?ring" wrote in message news:slrnans9pd.jc.gerhard.haering at lilith.my-fqdn.de... > > Your newsreader is broken. Please fix it or use something better than > this crapware to post to usenet. Yes, it's Outlook Express and I'm not love with it. I'd like to switch out but currently I have a zillion folders and sub-folders all organized so I'm kind of stuck for the moment. Strange, I've made hundreds of posts to Usenet with OE and never received a complaint before. If you choose not to answer my posts in the future because of this I'll understand, you've been extremely helpful in the past and I appreciate that. > > $ ln -s /usr/lib/libcrypto.so.0.9.6 /usr/lib/libcrypto.so.2 > No I have the exact same versions as you. I tried making the same symlinks to no avail. I even tried moving the symlinks from /usr/lib to a different directory that I am sure is on the PATH (/sbin) and it still didn't work. Perhaps it's a "kpackage" thing. I'll try learning more about 'rpm'. thx From jingguoming at yahoo.com.cn Fri Sep 6 04:03:36 2002 From: jingguoming at yahoo.com.cn (jgm2163) Date: 6 Sep 2002 01:03:36 -0700 Subject: how can i make a executable program with a python2's script Message-ID: os :RedHat 7.2 Python :Python2.2.1 now,i had writen a python's script (extend with .py) how can i make a executable program on RedHat 7.2? From david at fielden.com.au Tue Sep 17 18:34:23 2002 From: david at fielden.com.au (DG) Date: Wed, 18 Sep 2002 08:34:23 +1000 Subject: Python equivalent to perldoc? In-Reply-To: <%Avh9.7933$Lg2.1392332@news2.news.adelphia.net> Message-ID: <002601c25e9a$5ff213b0$3101a8c0@borg.fielden.com.au> The contents of my f:\python22\pydoc.bat file: @f:\python22\python f:\python22\lib\pydoc.py %1 %2 %3 %4 %5 %6 %7 %8 %9 Rowdy > Well...I found "pydoc". However I have to explicitly tell python to > execute it on Windows XP. I cannot type "pydoc sys" nor "python pydoc > sys" but I have to type "c:\python22\libs\pydoc sys" to get > it to work. > Shouldn't Python know its own libs? Or at least put the "libs" in the > ENV variable? > > Bob From boiko at demogr.mpg.de Wed Sep 25 15:05:54 2002 From: boiko at demogr.mpg.de (Serge Boiko) Date: Wed, 25 Sep 2002 21:05:54 +0200 Subject: pyqt 3.4 -- libqtcmodule.so undefined symbol Message-ID: I've just compiled pyqt v.3.4 on Mandrake Linux 9.0 (rc3) and any pyqt applications I tried crashes with the message: Traceback (most recent call last): File "/usr/lib/python2.2/site-packages/eric/eric.py", line 6, in ? from qt import QApplication, QTranslator, QTextCodec File "/usr/lib/python2.2/site-packages/qt.py", line 39, in ? import libqtc ImportError: /usr/lib/python2.2/site-packages/libqtcmodule.so: undefined symbol: _ZNK9QSGIStyle9classNameEv I have python 2.2.1 and gcc version 3.2-1mdk. Compilation ran smoothly. What's wrong? -Serge From emile at fenx.com Tue Sep 3 21:36:39 2002 From: emile at fenx.com (Emile van Sebille) Date: Tue, 3 Sep 2002 18:36:39 -0700 Subject: efficient list merging References: Message-ID: "Peter Saffrey" wrote in message news:ced73313.0209031012.13624f3 at posting.google.com... > I have two lists of lists of strings which I would like to merge > efficiently without repeats. I like sets in current cvs: Python 2.3a0 (#29, Aug 31 2002, 19:16:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sets >>> s1 = sets.Set('abcdefg') >>> s2 = sets.Set('efghijk') >>> s1^s2 Set(['a', 'c', 'b', 'd', 'i', 'h', 'k', 'j']) >>> s1|s2 Set(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'j']) >>> s1&s2 Set(['e', 'g', 'f']) >>> Emile van Sebille emile at fenx.com From phr-n2002b at NOSPAMnightsong.com Fri Sep 20 06:30:21 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Sep 2002 03:30:21 -0700 Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <7xk7lhb943.fsf@ruckus.brouhaha.com> <9Qzi9.117104$ub2.2497933@news1.tin.it> <7xd6r9uj2i.fsf@ruckus.brouhaha.com> Message-ID: <7xd6r9kl6q.fsf@ruckus.brouhaha.com> Alex Martelli writes: > Say that you publish the erroneous information that each phone > call is $0.70 plus $0.03 sales tax for a total of $0.73. Sales > tax is actually $0.04. Now, a customer makes 100 calls. Do > you charge them $74 explaining that 100 times 73 cents is 74 > dollars? Or do you charge $73 and eat the dollar loss yourself? > And even then, your tax books won't balance without fiddling -- > even if the unbalance is against your interests, as in this case, > it's _still_ illegal (at least around here)... double-entry tax > book-keeping is supposed to balance to the last cent. Now that I think about it, the way it's done around here is you're supposed to look up the amount of tax in a table, not calculate it. I remember giving my local ice cream store a hard time when I was little. I used to go in for an ice cream and coke, and because of how the tax table worked, it was one cent cheaper to buy them in two separate transactions than in one transaction, so I did that. At the end of the day, though, I'm sure they just took the amount that the cash register said was collected pre-tax, multiplied by the tax rate and sent that amount to the state. If the amount actually collected was slightly lower or higher, they paid the difference or kept it themselves. > But what you said were that you had a hard time imagining any > commercially significant computation being off by a whole penny > (which, I imagine, means a whole cent) by using IEEE double > (binary floating point). Surely this one example IS enough to > jog your imagination? Yes, point taken. From timr at probo.com Fri Sep 20 00:30:05 2002 From: timr at probo.com (Tim Roberts) Date: Thu, 19 Sep 2002 21:30:05 -0700 Subject: wxPython i18n, help wanted References: Message-ID: Cedric Dutoit wrote: > >I'm trying to translate an application in Chinese with i18n, but >I don't know how to display Chinese characters in wxPython. > >Can anybody help me ? If you go here: http://www.wxpython.org/, you will find the mailing list for wxPython. That's the best place to ask wxPython-specific questions. I think you will be disappointed with the i18n support in wxPython. On the other hand, perhaps you would be willing to help make it better! What it really needs is someone with the experience. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From msanchez at grupoburke.com Fri Sep 6 11:15:21 2002 From: msanchez at grupoburke.com (Marcos =?ISO-8859-1?Q?S=E1nchez?= Provencio) Date: 06 Sep 2002 17:15:21 +0200 Subject: [DB-SIG] Re: What database should I use In-Reply-To: <1031323316.6785.9.camel@asimov> References: <1031323316.6785.9.camel@asimov> Message-ID: <1031325321.6371.3.camel@cynar> That's right, there are not enough arguments to judge. The next thing is: How many concurrent users are you going to have? If it is one I'd go for gadfly. Does it need to be portable? If it's Windows only, I'd say Access (Jet). And don't forget about a text file or a cPickle to be minimalistic... El vie, 06-09-2002 a las 16:41, Tom Jenkins escribi?: > On Fri, 2002-09-06 at 10:29, Leif Jensen wrote: > > > > PostgreSQL, no doubt, if you use Linux, WinNT or possible WinXP ! > > > > Leif > > > > I disagree. Don't get me wrong, we use PostgreSQL EXTENSIVELY. But for > 2-3k records? These "requirements" don't require anything that > powerful. > > I'd look at Access, pySQLite (which intrigues me), Gadfly. > > > > > > > On Thu, 5 Sep 2002, A wrote: > > > > > Hello, > > > I am going to program a small application (in Python and wxPython) which consists about > > > 2000 - 3000 records . Can you please recommend which database is the best for that. I > > > use Windows. > > > Maybe MS Access or FoxPro or MySQL or better? > > > I want to keep the program as small as possible. > > > Thanks > > > Ladislav > > > > > > > > > _______________________________________________ > > > wx-users mailing list > > > wx-users at lists.wxwindows.org > > > http://lists.wxwindows.org/mailman/listinfo/wx-users > > > > > > > > > _______________________________________________ > > DB-SIG maillist - DB-SIG at python.org > > http://mail.python.org/mailman/listinfo/db-sig > -- > > Tom Jenkins > Development InfoStructure > http://www.devis.com > > > > _______________________________________________ > DB-SIG maillist - DB-SIG at python.org > http://mail.python.org/mailman/listinfo/db-sig From see_reply_address at something.invalid Tue Sep 24 23:07:04 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 25 Sep 2002 15:07:04 +1200 Subject: Three dumb questions (ordered by dumbness descending) References: Message-ID: <3D912858.90104@something.invalid> Thorsten Kampe wrote: > 1. Why is 'zip(zip(x)) != x' (should be the same because it's the > transposed) zip(x) isn't the transpose of x. Try it and you'll see. However, zip(*x) IS the transpose of x (or apply(zip, x) in older Pythons). Therefore, zip(*zip(*x)) == x is true, provided you start with an x of the right type (a list of tuples, as opposed to a list of lists or tuple of tuples, etc.) > 2. Peter Norvig mentions in "Python for Lisp Programmers" some > "don'ts": "[x] + y" and "x[1:]". Are there more things to avoid > (especially in a loop)? The "for Lisp Programmers" is the important thing here. He's pointing out that these operations are not as efficient as the corresponding ones in Lisp, because Python lists aren't linked lists like Lisp lists, so these operations involve copying a whole list. > So: can I use random.shuffle or do I have to write my own - slower - > version to get a random list? It depends on how imporant it is to you that all possible permutations have equal probability. If you're writing a solitaire game, probably nobody will notice the difference. If it's a nuclear missile control system, you might have to take more care... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From aldo at nullcube.com Sat Sep 14 23:38:33 2002 From: aldo at nullcube.com (Aldo Cortesi) Date: Sun, 15 Sep 2002 13:38:33 +1000 Subject: confused with class inheritance In-Reply-To: <3d83fa2c$0$24041@echo-01.iinet.net.au> References: <3d83fa2c$0$24041@echo-01.iinet.net.au> Message-ID: <20020915033833.GA21366@nullcube.com> Thus spake Rob Hall (bloke at ii.net): > In a sample app, I have the following: > > >>> class a(sgmllib): > pass > > >>> a > > >>> dir(a) > [] > >>> dir(sgmllib) > ['SGMLParseError', 'SGMLParser', 'TestSGMLParser', '__all__', > '__builtins__', '__doc__', '__file__', '__name__', 'attrfind', 'charref', > 'commentclose', 'endbracket', 'entityref', 'incomplete', 'interesting', > 'markupbase', 'piclose', 're', 'shorttag', 'shorttagopen', 'starttagopen', > 'tagfind', 'test'] > >>> b=a > >>> dir(b) > [] > >>> > > Why doesn't dir(b) show the same as dir(sgmllib) ? sgmllib is a module, not a class. If you try to instantiate your "class" a, you will get an exception. This should act the way you expect it to: class Foo: def oink(self): pass class Bar(Foo): pass print dir(Foo) print dir(Bar) Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com From jslowery at hotmail.com Fri Sep 13 19:38:56 2002 From: jslowery at hotmail.com (Jeremy Lowery) Date: Fri, 13 Sep 2002 18:38:56 -0500 Subject: html template system? References: Message-ID: ":B nerdy" wrote in message news:btug9.688$Ee4.1090 at news-server.bigpond.net.au... > what are good templating systems avaliable for python? http://www.cheetahtemplate.org/ is the one I use. J Lowery From brueckd at tbye.com Wed Sep 18 17:05:17 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 18 Sep 2002 14:05:17 -0700 (PDT) Subject: Python GUI app to impress the boss? In-Reply-To: <96904b50.0209181128.63cd71f9@posting.google.com> Message-ID: On 18 Sep 2002, Lee Gray wrote: > Chris Liechti wrote in message news:... > > lpgray at uop.com (Lee Gray) wrote in > > news:96904b50.0209171305.6d65f574 at posting.google.com: > > > My boss is pretty open-minded, but also needs to see something working > > > to be convinced Python is even a viable platform (he had never heard > > > of it). Otherwise, .Net is a given, whether it's any good or not, > > > since corporate is MS all the way. > > > > with python you have to choice of diffrent GUI libs. if you consider > > wxWindows you can play around with the wxPython demo application that comes > > with the download. on the other hand when you support win32 only the > > win32all package has support for all the windows APIs and it has some > > samples that get installed. > > > > chris > > I've been playing with wxWindows and Boa Constructor. wxWindows is > pretty darn cool and will make a good demo for him. Boa looks good > but is still a bit rough (naturally, being alpha), but I'm looking > forward to future releases. wxDesigner is also pretty nice (http://www.roebling.de). -Dave From emile at fenx.com Mon Sep 9 17:26:01 2002 From: emile at fenx.com (Emile van Sebille) Date: Mon, 9 Sep 2002 14:26:01 -0700 Subject: Binary input into NumPy. References: Message-ID: Maurice van de Rijzen: > I just downloaded Numerical Python and I think it will be very usefull. > However I have one major broblem: > I don't know how to import binary data from a file on disk into an array! > Can onyone help me with this problem? > look into Numeric.fromstring(open('filename', 'br').read(), numpytype) HTH, Emile van Sebille emile at fenx.com From mstenner at phy.duke.edu Fri Sep 6 18:23:12 2002 From: mstenner at phy.duke.edu (Michael Stenner) Date: Fri, 6 Sep 2002 18:23:12 -0400 Subject: how can i make a executable program with a python2's script In-Reply-To: <3D7924BF.805@motorola.com>; from stephen.boulet@motorola.com on Fri, Sep 06, 2002 at 04:57:19PM -0500 References: <3D7924BF.805@motorola.com> Message-ID: <20020906182312.A15215@phy.duke.edu> On Fri, Sep 06, 2002 at 04:57:19PM -0500, Stephen Boulet wrote: > You can put > > #/usr/bin/env python > > at the top of the file and do a chmod +x file. Is this the answer to the > right question? Although since you're trying to use python 2.2.1 on a RHL 7.2 box, you may need to make that #!/usr/bin/env python2 Otherwise, you'll get python 1.5.2, which can lead to confusing errors. -Michael > jgm2163 wrote: > > os :RedHat 7.2 > > Python :Python2.2.1 > > > > now,i had writen a python's script (extend with .py) > > how can i make a executable program on RedHat 7.2? > > > -- > http://mail.python.org/mailman/listinfo/python-list -- Michael Stenner Office Phone: 919-660-2513 Duke University, Dept. of Physics mstenner at phy.duke.edu Box 90305, Durham N.C. 27708-0305 From bokr at oz.net Sun Sep 29 21:05:17 2002 From: bokr at oz.net (Bengt Richter) Date: 30 Sep 2002 01:05:17 GMT Subject: watching mutables? References: Message-ID: On Fri, 27 Sep 2002 16:12:05 +0200, anton at vredegoor.doge.nl (Anton Vredegoor) wrote: >Hello all, > >here's a function I would like to have: > > > >>>> m = [1,2] >>>> m >>>> [1,2] >>>> from watcher import watch >>>> watch(m) >>>> m.append(3) >>>> "hey, you changed variable m!, new value is [1,2,3]" > > > >Is this possible? How would this be called? > I suspect you may have to adjust your concept of "variable" to think about this in Python terms. I.e., m = [1, 2] doesn't result in a "variable" m with value [1,2]. It results in an object (a list instance [1, 2]) and a name "m" in a particular name space, and a relationship between the name and the object, called binding. This gives you several things that can change: the binding of "m" and the mutable features of the object it is bound to. Watching for a change in the binding of a name is possible, but you will somehow have to give the watching mechanism information about the actual name and name space (e.g., watch('m', vars()), not watch(m) ) and provide a trigger for the checking operation. If the name is an attribute of an object that you can mess with, you may be able to monitor all attribute name setting via __setattr__, but you might then miss changes made some other way like obj.__dict__['m'] = whatever, so you probably want to use some kind of tracing hook to get control for polling the status. Watching for a change in the object being referred to by m is a different thing. For that, you don't need to tell the watcher about the name per se ('m') unless you want the name in a message like the (somewhat misleading) one you specified. For change in the object, you also have to decide what "change" is supposed to mean. I.e., is it based on '==' or what? Also, you have to get control to the checking mechanism again, either by hooking into the object's mutation facilities, or an independent polling trigger. I'd be surprised if some solutions to your problem didn't already exist, and I expect someone will chime in. I mainly wanted to point out that the "variable" concept does not apply to Python the way it does to C or C++. Nevertheless, here's something that appears to track a single named binding. I use change in marshalled value as the criterion for change detection. (not tested beyond what you see ;-): ----< Watcher.py >----- class Watcher: from sys import settrace from marshal import dumps def __init__(self, name, namespace): self.name = name self.ns = namespace obj = namespace.get(name) self.objid = id(obj) self.objs = self.dumps(obj) self.settrace(self.watch) def watch(self, frame, event, arg): obj = self.ns.get(self.name) objid = id(obj) if objid != self.objid: self.objid = objid what = 'new' else: what = 'same but mutated' objs = self.dumps(obj) if self.objs != objs: print '"%s" is bound to %s object: %s' % (self.name, what, `obj`) self.objs = objs elif what=='new': what = 'new but equivalent' print '"%s" is bound to %s object: %s' % (self.name, what, `obj`) return self.watch def finished(self): self.settrace(None) ----------------------- >>> import Watcher >>> m=[1,2] >>> w = Watcher.Watcher('m',locals()) >>> m.append(3) "m" is bound to same but mutated object: [1, 2, 3] >>> m=4 "m" is bound to new object: 4 >>> m=5 "m" is bound to new object: 5 >>> m=5 >>> m=[6] "m" is bound to new object: [6] >>> m=[6] "m" is bound to new but equivalent object: [6] >>> m[0]=7 "m" is bound to same but mutated object: [7] >>> m = m >>> x = m >>> m = [7] "m" is bound to new but equivalent object: [7] >>> m = x "m" is bound to new but equivalent object: [7] >>> x.append(8) "m" is bound to same but mutated object: [7, 8] Notice that x.append(8) affected m's "value", but neither binding. Regards, Bengt Richter From mmoales at fluent.com Thu Sep 5 10:48:40 2002 From: mmoales at fluent.com (Mark Moales) Date: Thu, 05 Sep 2002 10:48:40 -0400 Subject: How to force built-in commands over imported. References: <3D761C39.4020802@akst.tn.tudelft.nl> Message-ID: <3D776EC8.F84C8EF0@fluent.com> Maurice, How did you import the os module? I'm guessing you did: from os import * If you just do: import os then when you invoke open, you'll be using the builtin function. Of course, all of your os function calls will need to be prefixed with "os.", but you won't have anymore name clashes. Mark Maurice van de Rijzen wrote: > > Dear all. > I'm a newbie on the field of python, therefore the answer to my question > may be simple. > There is a built-in commans called open(fileName). There is also a > open() command in the os-module open which needs more than the fileName. > Originally I didn't import the os-module and everything worked fine. > However, when I imported the os-module I received an error that open > needed more arguments. How can I force to take the built-in open() > instead of the open() in the os-module. > > Gr, > Maurice -------------- next part -------------- A non-text attachment was scrubbed... Name: mmoales.vcf Type: text/x-vcard Size: 281 bytes Desc: Card for Mark Moales URL: From aleax at aleax.it Fri Sep 20 05:07:16 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 09:07:16 GMT Subject: Avoiding referencing (was: Python sequences reference - problem?) References: Message-ID: <8zBi9.117743$ub2.2504724@news1.tin.it> Thorsten Kampe wrote: > * Alex Martelli >> Just remembed that EVERYTHING works by reference, and what >> could possibly be the problem...? > > The problem is that we newbies sometimes don't want referencing: Then you explicitly ask for a copy, just like an experienced programmer would. > #v+ > def part(seq, indices): > """ chop seq by indices """ > partition = [] > > for slice in indices: > partition.append(seq[:slice]) > del seq[:slice] > partition.append(seq) > return partition > #v- If you don't want your function to affect its argument seq, you start by making a copy. Since you'd also like to ensure you work with a list (whatever sequence or other iterable you may have been passed), as you need a mutable sequence for the "del seq[:slice]" statement to work, you can kill two birds with one stone -- change the start to: def part(seq, indices): """ chop seq by indices """ partition = [] seq = list(seq) and leave the rest unchanged. The function would be a little bit clearer if the names involved made it more obvious that the sequence you receive as an argument, and the local copy you slice up, are different things, though -- e.g.: def part(input_seq, chop_sizes): """ chop input_seq into a list of lists of given sizes """ partition = [] seq_copy = list(input_seq) for size in chop_sizes: partition.append(seq_copy[:size]) del seq_copy[:size] partition.append(seq_copy) return partition Choosing names of variables for maximum clarity and readability is always a delicate issue, of course -- here, I've tried to change things around a bit, and edit the docstring too, to make it clearer that the second argument is not about indices at all, but rather about sizes (lengths, if you will) of the sub-lists. A completely different approach would be: def part(input_seq, chop_sizes): """ chop input_seq into a list of lists of given sizes """ partition = [] next_start = 0 for size in chop_sizes: last_start, next_start = next_start, next_start + size partition.append(input_seq[last_start:next_start]) partition.append(input_seq[next_start:]) return partition It's hard to choose between the two approaches, but I like this second one a tiny little bit better, personally. I'm not sure why I do, to be honest. I hope it's not because of the slight possibility that its performance is superior (e.g., it's O(N), not O(N squared), when chop_sizes degrades to [1]*len(input_seq)...) -- I have not measured performance nor do I have the slightest indication that this function part has any need for optimization. No, I just find it more natural to avoid changing data structures except where such changes make things more obvious to me, I guess. Here, with the second approach, I can get a _slightly_ more "FP" feel (not all that much, since partition and the scalars do change:-), which may have something to do with my preferences!-) The second approach does lend itself to a slight optimization, should it be needed, by preallocating the result to its known final length rather than relying on append: def part(input_seq, chop_sizes): """ chop input_seq into a list of lists of given sizes """ partition = [None] * (1 + len(chop_sizes)] next_start = 0 for i in range(len(chop_sizes)): last_start, next_start = next_start, next_start + chop_sizes[i] partition[i] = input_seq[last_start:next_start] partition[-1] = input_seq[next_start:] return partition but this does seem to involve a tiny loss of clarity wrt the second one (as "for i in range(len(..." so often does, sigh), therefore I wouldn't use it unless performance WAS important (and, of course, after measuring the various alternatives!!!). A more FP alternative would involve building first a list of indices from the list of sizes, e.g. (dirty trick warning...): start = 0 chop_indices = [ start for x in [0]+chop_sizes for start in (start+x,)] + [None] and then just using it: return [input_seq[chop_indices[i]:chop_indices[i+1] for x in range(len(chop_sizes))] but this fails the base test -- it's not as obvious and simple and the others, mostly because Python lacks an "expand" function to get the chop indices from the chop sizes (whence the "for start in (start+x,)" dirty trick). But, back to your post...: > Obviously I did not pass 'foo' "by value" to function 'part' but by > reference and obviously not only local variable 'seq' was modified in > the function but "outer" variable 'foo', too. Rather, an OBJECT was modified -- and the two names are referring to the same object (as you didn't ask for a copy). > So how to deal with that? By asking for a copy. > 1. "Just don't call function 'part' by with a variable, call it by > value - part([11, 22, 33, 44, 55, 66, 77], [2, 3]) - and everything's > okay". > > Obviously no solution to me. Obviously! > 2. "If you don't want referencing, call it with a copy of 'foo' like: > part(foo[:], [2, 3])" > > Yes, but how do I know in advance that 'part' modifies 'foo'? I might > not be the author of 'part'. Indeed, part should not modify its arguments UNLESS it says it does in its docstring. Unless there are very good reasons for a function to modify its arguments (in which case the function should normally return None -- mixing arg modification and significant return values can be confusing!!!), avoiding such mods is the default case. > 3. "Rewrite function 'part' so that it works with a tuple as argument. > Thereby you're avoiding all possible modifying of existing objects." > > Yes, but I'm also losing the "extended" possibilities of lists: > "list.append", "list.reverse", "list.index" etc. My code will be twice > as long as it would be with list methods. I think it might be nice for part to accept as arguments sequences that are not lists -- as you see in the first version I propose, making a copy and ensuring you have a list can be fruitfully combined in a single call to 'list'. As you see in the second version, working directly with the argument, without modifying it, doesn't expand the code size AT ALL in this specific case, anyway -- but the first version is slightly more general, in that it will accept ANY argument that's acceptable to built-in 'list' (e.g., a file -- list(afileobject) is like afileobject.readlines()), while the second version does require a sequence (which must accept being sliced AND supply copies when sliced -- a Numeric array would accept being sliced, BUT would supply slices that are arrays sharing data with the original array... this MAY be a problem in some cases, although performance will surely be enhanced by avoiding copies, if the data be truly huge). > Is there a way to "bypass" referencing _without_ disadvantages? I'm Absolutely not. Making a copy takes time: there is absolutely no way around this! Therefore, there's no way to "bypass _without_" ANY disadvantages at all: as a minimum, the time and memory you spend for the copy are a disadvantage in some cases. But, of course, you DO pay those prices _whenever_ you use a language with copy semantics. That's part of why passing of array arguments doesn't use copy semantics in most languages -- in Fortran because all argument passing is by reference (while all assignment is by copy), in C because arrays in particular "decay" to pointers when mentioned. Implicitly copying huge gobs of data each and every time an array is passed as an argument would be an unmitigated performance disaster for most cases. > sure there is a "canonical" way to do this in Python! The canonical way to copy any object is function copy of module copy (assuming a shallow copy suffices, as is often the case). But often when you copy you ALSO want something else -- like here, for example, in the first version (turn any sequence into a list, as well as copying it). Thus, don't blindly follow the "canonical" way: THINK about what you want and how best to obtain it -- sometimes copy.copy is OK, sometimes an all-sequence slice x[:], but often calls to built-ins list or tuple, depending on what, exactly, you're trying to accomplish with your copy. Alex From aleax at aleax.it Thu Sep 19 03:31:47 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 19 Sep 2002 07:31:47 GMT Subject: monetary applications (et al) References: Message-ID: terry wrote: ... > I do admit to being OO inhibited, so maybe you could take it from this > short piece code and execution results, and, provide a brief > description of what you would put into this money class that would > eliminate this error message, while maintaining the code simplicity. > > ------------------------------------------------- > class money: > def __init__(self,name): > self.name = name It doesn't seem to me, from the example use below, that the argument to money's constructor has anything to do with a "name" -- rather, you seem to want to use it as an *amount*. Therefore, call it 'amount', NOT 'name'. Giving your variables (attributes, functions, classes, methods, whatever) names that are widely at variance with the variables' meaning is a horrible practice. I'm not sure what this has to do with your "being OO inhibited": it would be a practice just as despicable in '60s-vintage Cobol as in the spiffiest 21st-century language. Then, it seems the money class needs to participate in arithmetic as a number. Thus, it clearly needs to define the special methods that denote it's a number. All in all: class Money: def __init__(self, amount): self.amount = amount def __add__(self, other): return Money(self.amount + other) __radd__ = __add__ def __mul__(self, other): return Money(self.amount * other) __rmul__ = __mul__ So far, class Money is just a wrapper over an 'amount' of unknown type, simply delegating addition and multiplication to the 'amount' (other arithmetic aspects work much the same, except of course that they're not all commutative). It's not hard for it to supply extra functionality that you haven't requested but probably do want, e.g.: def __str__(self): return "$%.2f" % self.amount so that, e.g., print Money(100) * 0.5 would display $50.00 This still doesn't do anything particularly interesting (but the __str__ method would of course in fact use the locale settings to display monetary amounts in ways more appropriate to the locale - NOW we're starting to add some value, at last). One probably also wants a __repr__: def __repr__(self): return "Money(%.2f)" % self.amount More interesting may be doing something substantial about the underlying arithmetic. This class we're sketching does arithmetic just like the underlying type of amount -- it just pretties things up at output time to display exactly two decimal digits, but there is nothing about it that deals with the _accuracy_ of those digits. In any real financial application there are constraints, sometimes legal ones, about what kind of arithmetic must be computed when the true results would be a fraction of a cent (or Eurocent or whatever is the minimum legal fraction of money). This class doesn't _know_ what the legal restrictions are (as they'll no doubt differ from country to country, at least, and more often than not by application area too) -- but it makes it reasonably easy to insert such knowledge when you DO have it! For example, if you work in an application area and jurisdiction where the arithmetic must obey the standard rules of decimal computation, you could simply fix the constructor to: def __init__(self, amount): import Decimal self.amount = Decimal.Decimal(amount) and everything would fall in line as if by magic, thanks to polymorphism. It's pretty easy to customize class Money to accept the underlying numerical class as a parameter, too, e.g by inheritance: class FlexibleMoney: numberclass = float def __init__(self, amount): self.amount = self.numberclass(amount) # the rest is, again, unchanged so now you could have, depending on jurisdiction and application area, e.g.: import Decimal class Money(FlexibleMoney): numberclass = Decimal.Decimal or else, again for example: import gmpy class Money(FlexibleMoney): numberclass = gmpy.mpq (to respect the rules of unbounded-precision computation via rational numbers), and so on, and so forth. > unitprice = money(100) > qty = 2 > amount = qty * unitprice > > terry at terry:~> python money.py > Traceback (most recent call last): > File "money.py", line 7, in ? > amount = qty * unitprice > TypeError: unsupported operand type(s) for *: 'int' and 'instance' > ------------------------------------------------- Right -- your class Money didn't supply __rmul__, so the multiplication you tried to perform couldn't be performed. The above examples do supply __rmul__, so this will work fine. > Support for mixed number types in expressions involving this money > class must come from somewhere - where? And, it must be capable of That's the nice thing about polymorphism: it doesn't matter where the underlying arithmetic functionality is coming from, only that it respect the rules you want it to respect (depending on legal jurisdiction and application area). gmpy wraps the GMP library, so that's where the functionality comes from; Decimal is pure Python, and you should import it from Aahz's side and inspect it to gain some knowledge; and so on, and so forth. > determing and setting amount to be of class money to be consistent with > the rest of Python's complexity hierarchy for the handling of numbers. That's reasonably trivial -- particularly now that (thanks be) you don't NEED to support coercion any more (though gmpy's current version still does support it, because it's meant to work with older versions of Python too -- one day I'll do a "gmpy in a tie" release and clean it up enormously, I promise:0). > The rest of the problem is that the above is a trivial calculation. > What happens to your recommendation when faced with an additional > number type? Nothing strange, if your underlying code is sound. > taxrate = 0.06 > amount = qty * unitprice + (qty*unitprice)*taxrate Works fine with the trivial class I sketched here, of course. > As I see it, if Python had an intrinsic number type of 'money', the > logic for determing the results of the above calculation would be > easily determined and consistent with expectations, as in VB. You see it wrong. The law establishes what rules arithmetic must follow in a lot of hairy cases, and no single intrinsic type can follow all the rules for every jurisdiction and application, since the rules DO differ. In theory, you could go to jail in some places because of the way you round certain fractions of a cent (or whatever) in some application -- and the judge should not accept "but VB does it that way" as covering your responsibility: an application can be used to compute (e.g.) worker-compensation, or tax liability, or actual annualized interest rates to be posted as the law requires (in the EU), etc, etc, only if the application is certified and carries the needed forms of sworn affidavits about it. When you sign a piece of paper swearing that the application abides by whatever weirdness the law wants it to abide by, you have to KNOW that it does. In practice, white collar crims is generally dealt with very leniently by the courts -- though that might change in the current climate (but not in Italy, where the government's main political purpose is ensuring that nobody can possibly go to jail for financial shehanigans far darker than these, since the prime minister and his closest associates would be the prime candidates for any such jail terms if applicable... so, ME, being an Italian citizen and resident, I'm reasonably well covered in this regard... US citizens and residents should be far more wary these days:-). Note: my knowledge of such issues is second- and third-hand: the student in financial economics in the family is my son, I'm an engineer and the computation-constraining laws I know anything about are rather those about how you're allowed to compute tensile resistance of reinforced concrete and so forth. But it DOES make sense that the law should specify such issues, even though it may not seem so when you're *not legally allowed* to do arithmetic the same way for any of three different purposes. > Thanks for your time, You're welcome. Better to SPEND some time considering such issues in all needed detail, than to SERVE time later because one didn't, right?-) Alex From emile at fenx.com Mon Sep 16 22:58:48 2002 From: emile at fenx.com (Emile van Sebille) Date: Mon, 16 Sep 2002 19:58:48 -0700 Subject: Not sure how to phrase this question References: <000501c25dde$79a8be60$9865fea9@arthur> Message-ID: Arthur: > Something that I guess can be called a simple class factory. I have a > routine that will analyze *args sufficiently to provide information as to > which class to be called from the ClassFactory to which *args is > passed. > > In the end I want to create an instance of the called/returned class, not of > the ClassFactory class. I don't think you need __new__, or if you do, you'll want to read up on the existing documentation and prior discussions. Oh... I couldn't find the docs. There are some usage examples in the demo/newmetaclasses, but they only seem to exist in cvs. All this probably has a bit to do with the lack of response you mention. Anyway, it sounds like you want to create an interface to, eg, allow students to experiment with geometric properties. To support this, you want to create class instances that provide a flexible interface and do not require arguments passed in an expected sequence. ISTM a wrapper class could do this trick. class _Intersection: def __init__(self, plane=None, line=None): self.line = line self.plane = plane class Plane: def __init__(self): self.ima = 'plane' class Line: def __init__(self): self.ima = 'line' class Intersection(_Intersection): def __init__(self, *args, **kwargs): for ii in args: kwargs[ii.ima] = ii _Intersection.__init__(self, **kwargs) #test l = Line() p = Plane() ii = Intersection(l,p) jj = Intersection(p,l) print ii.line print jj.plane HTH, and if you keep trying metaclass stuff, keep us up on your progress and findings. ;-) -- Emile van Sebille emile at fenx.com --------- From see_reply_address at something.invalid Thu Sep 19 21:13:20 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 20 Sep 2002 13:13:20 +1200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: <3D8A7630.9090108@something.invalid> A.M. Kuchling wrote: > Note that the Parrot VM is already stackless, so a hypothetical Python > running on Parrot would be stackless from the start. How does it (or how is it envisaged that it will) handle callbacks from C to interpreted code? Will it remain stackless under those conditions? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From spam at fisher.forestry.uga.edu Sat Sep 7 15:22:16 2002 From: spam at fisher.forestry.uga.edu (Chris Fonnesbeck) Date: 7 Sep 2002 12:22:16 -0700 Subject: returning values from FORTRAN with f2py Message-ID: I am wondering how to persuade some fortran code that I have compiled with f2py to return its calculated values to me in python. I have some code that does gaussian elimination (mostly from Numerical Reciopes), and is supposed to return an inverted matrix so that I can solve a system of linear equations. However, when run in python, the function runs without error but returns no values: >>> a = [[2,1,3],[1,-1,1],[3,6,-1]] >>> b = [7,2,10] >>> import gauss >>> gauss.gauss(a,3,b,1) >>> Is there something that I have to change in my fortran code to make this work? Many thanks, cjf From ark at research.att.com Mon Sep 2 10:41:57 2002 From: ark at research.att.com (Andrew Koenig) Date: Mon, 2 Sep 2002 14:41:57 GMT Subject: stylistic question -- optional return value References: <30292041.0209012344.ab2d4@posting.google.com> Message-ID: Sebastian> Why not create an additional optional *argument* (say a list, or a Sebastian> function), to which you optionally provide your debug information? It's not debug information. I used that term only as an analogy. Anyway, I don't want to separate the optional information from the rest of it because everything needs to go into the same data structure eventually. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From fperez528 at yahoo.com Sat Sep 28 21:54:44 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Sat, 28 Sep 2002 19:54:44 -0600 Subject: Lambdaizing Python Code References: <3d9559c4.14281625@news.t-online.de> Message-ID: Gerson Kurz wrote: > A really usefull study ... NOT. > > http://p-nand-q.com/e/quicksort_lambda.html > > also known as "making Guido regret he put lambda in THE BEST > PROGRAMMING LANGUAGE IN THE WORLD(TM)". Now, as an excersise in sillyness it's funny. However, a more reasonable rewriting as a lambda can be found at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66473 And is a simple one-liner: q=lambda x:(lambda o=lambda s:[i for i in x if cmp(i,x[0])==s]:len(x)>1 \ and q(o(-1))+o(0)+q(o(1)) or x)() Granted, for a quicksort I'd _much_ rather use a normal functional form. But this doesn't mean that a lambda form has to be the monstrosity depicted in that page :) I do take my hat off to whoever wrote it: just the fact that it works at all is an accomplishment in and of itself. Cheers, f. From aglyportREMOvethispart at nospam.yahoo.com Wed Sep 4 15:09:49 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Wed, 04 Sep 2002 12:09:49 -0700 Subject: Memory fault - core dumped while compiling 2.2.1 on SCO References: <3D757EFA.9050401@nospam.yahoo.com> Message-ID: <3D765A7D.7000804@nospam.yahoo.com> Andrew Koenig wrote: > Anton> Any ideas? > > Looks like the same symptom I had. > > If you are using binutils 2.13, try going back to 2.12.1 and > see if that fixes the problem. > I don't think I use binutils: Wed Sep 4 11:37:53 PDT 2002 bongo:/u5/src/Python-2.2.1 $ as --version Assembler: (null) aline 1 : Warning: Illegal flag (-) - ignored aline 1 : Warning: Illegal flag (v) - ignored aline 1 : Warning: Illegal flag (e) - ignored aline 1 : Warning: Illegal flag (r) - ignored aline 1 : Warning: Illegal flag (s) - ignored aline 1 : Warning: Illegal flag (i) - ignored Nonexistent file Wed Sep 4 11:37:48 PDT 2002 bongo:/u5/src/Python-2.2.1 $ ar --version ar: ERROR: Illegal option -- - Usage: ar [-V?] -key[arg] [posname] afile [name ...] where key[arg] is one of the following: r[uabi], m[abi], d, q, t, p, x Can't think of other utils in binutils. From marklists at mceahern.com Thu Sep 19 07:40:11 2002 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 19 Sep 2002 06:40:11 -0500 Subject: StructuredText -> HTML module?? In-Reply-To: Message-ID: [Thomas Weholt] > Need a module to parse StructuredText/Wiki into HTML. Looked at > PyWiki, but the generated code was not what I expected. Does anybody > have module or lib to do this? docutils has reStructuredText: http://docutils.sf.net/ // m - From sholden at holdenweb.com Thu Sep 12 12:05:59 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 12 Sep 2002 12:05:59 -0400 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> <3D7FFC43.10002@something.invalid> Message-ID: "Stephen Ferg" wrote > Thanks for the tips on where to find Human Interface Guidelines. > > > It's a fairly universal principle in Tk that the > > "command" of a widget is invoked according to the > > standard behaviour of that widget, so I think it > > deserves treatment as a fundamental principle > > on the same footing as event binding. > > Absolutely! This observation is GOLD! This is just the kind of thing > I'm trying to get at in "Thinking in Tkinter". > > Let me make sure I've got it right. We have two fundamental, and > different, approaches to specifying the behavior of a widget. > > (1) event binding, in which you get to "roll your" own bindings by > binding callbacks to particular events that you specify. > > (2) command binding, in which a standard behavior for a widget is > already defined for you by Tkinter (and Tk), and you bind a callback > to that standard behavior. > > This explains why "command" binding doesn't automatically pass an > event object the way that event binding does. The standard behavior > of a widget might be defined across multiple kinds of events (e.g. > Button's standard behavior is defined across both a button-press and a > button-release), so there is no *single* event that could be passed. > Correct. When you *want* the event data, of course (cursor position, etc.) then bindings are a godsend. But the average programmer of end-user applications gets most of what they need from a command callback. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From fgranger at alussinan.org Fri Sep 27 12:49:56 2002 From: fgranger at alussinan.org (=?ISO-8859-1?Q?Fran=E7ois_Granger?=) Date: Fri, 27 Sep 2002 18:49:56 +0200 Subject: combining mailbox and email modules References: Message-ID: <1fj6jb2.62mx08f47amsN%fgranger@alussinan.org> Bob Horvath wrote: > The problem is that it looks good to me. I've played around with > it, and if I take out the MIME gunk (It actually is a Klez virus), > it parses ok. I have had difficulties with the handling of multipart message with the email package. I did not found a solution yet. -- Ce qu'il y a d'emmerdant dans la morale, c'est que c'est toujours la morale des autres - L?o F?rr? - Cit? par No?lle Adam From cjw at sympatico.ca Wed Sep 4 12:27:21 2002 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 04 Sep 2002 12:27:21 -0400 Subject: MLab in Numeric.py a possible bug Message-ID: <3D763469.F51A60B2@sympatico.ca> Line 296 in the function cov is: val = squeeze(dot(transpose(m) * conjugate(y)) / fact) and gives the error message: ValueError: frames are not aligned dot is expecting two arguments, but does not complain when one is provided. m and y are arrays, replacing them by matrices does not appear to resolve the problem as, with matrix m, transpose(m) is an array, not a matrix. Providing dot with two arguments, array or matrix, seems to resolve the problem. val = squeeze(dot(transpose(m), conjugate(y)) / fact) From jafo at tummy.com Wed Sep 18 13:30:46 2002 From: jafo at tummy.com (Sean Reifschneider) Date: Wed, 18 Sep 2002 11:30:46 -0600 Subject: New RPMs at python.org In-Reply-To: References: <20020918171900.GB13272@tummy.com> Message-ID: <20020918173046.GL1910@tummy.com> On Wed, Sep 18, 2002 at 12:24:06PM -0500, Mark McEahern wrote: >Installs "python2.2" as well as "python2.2". > ^^^ ^^^ > >They are the same, no? That should be "python2.2" and "python2". Also, I had to stop the presses for a moment, because of an issue I noticed. The files are all mode 000 right now, they'll be back to normal in a few minutes. Sean -- I find that a great part of the information I have was acquired by looking up something and finding something else on the way. -- Franklin P. Adams Sean Reifschneider, Inimitably Superfluous tummy.com, ltd. - Linux Consulting since 1995. Qmail, Python, SysAdmin From peter at engcorp.com Fri Sep 6 23:06:35 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 06 Sep 2002 23:06:35 -0400 Subject: Interrupting Python References: Message-ID: <3d796d22@news.sentex.net> Bob Easton wrote: > Using catchCtlC.py in a command line environment works as you expect. When I > hit Ctrl-Break, Windows displays "^C" and then a command prompt. If I hit > Ctrl-C, the exception handler catches it and displays the results as > specified in catchCtlC/py > > However, my preferred execution environment is PythonWin, not a command > prompt. There, neither Ctrl-break, not Ctrl-C have any effect. That could > easily be a bug with PythonWin. Not a bug, I think. The whole Ctrl-C/Ctrl-Break concept is only meaningful for command-line ("console") programs, not GUI apps. I don't use PythonWin, but my guess is it does not bother passing ctrl-c on to the application, possibly by design. Can't you just run it under the console? What advantages do you find by running it under PythonWin other than during development? Also, have you looked at the msvcrt module and kbhit() ? -Peter From tebeka at cs.bgu.ac.il Wed Sep 18 02:47:25 2002 From: tebeka at cs.bgu.ac.il (Miki Tebeka) Date: 17 Sep 2002 23:47:25 -0700 Subject: Loading modules from several directories References: Message-ID: <33803989.0209172247.2e6afc1f@posting.google.com> Hello Eugene, > Trying to reuse the code I found a problem (with Python or me) where > if I have for example, a foo package in two separate directories > (where foo/ contains common files and foo/project_a/ contains > project-specific files) I can't load from both. > > If I put the common path first in the sys.path it tries to load the > project-specific stuff from there too. If I try putting the > project-specific one first it can't find the common stuff. > > Anyone know of a good solution for this problem? Doesn't sys.path.append('/somedir/foo') sys.path.append('/somedir/foo/project_a') import foostuff import projectstuff works? Miki From aleax at aleax.it Wed Sep 25 06:18:01 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 10:18:01 GMT Subject: general thoughts References: <3D8B3250.BA964BCF@ObjectWay.it> Message-ID: Dave Kuhlman wrote: ... >>> I think you need substantial capacity and appetite for abstract thought >>> to really _enjoy_ SICP -- it doesn't spoon-feed you, nor does it use ... > This book is a huge time sink. One section shows you how to fake object > oriented programming in a dialect of lisp with no O-O support. After > working through that section, I asked myself, Why do I need to know this? > What good is it going to do me, unless I'm using a lisp dialect that does > not support object-oriented programming? People who like to think abstractly generally also like to have multiple switchable mental models of how something like method dispatching could be implemented. People who prefer concrete thinking generally want ONE such mental model, preferably the exact one they're dealing with at a given time. That's NOT a put-down of either kind of people - we NEED both kinds, and there's a synergy between the two types when put in the same time, although clashes are quite possible too. I'd never suggest SICP to somebody who prefers concrete thought. It's not a matter of more or less intelligence, please note, but of the WAY one's mind prefers to work. > And, a large part of the book describes how to program without variables > and > state. That's weird and interesting, just like the Elephant Man was weird > and interesting. But, after that, then what? Am I supposed to try to > program that way? You can choose to -- or you can choose to add another capability of abstraction to your panoply of such. You probably already have a mental model of computation WITH side effect -- now you've added another, of computation WITHOUT side effect. Python happens to have just enough functional flavor (though GvR doesn't like that:-) that this specific capability has some use. Actually (see Coplien's "Multi-paradigm DESIGN for C++") a reasonable collection of mental models for highly varied paradigms can come in useful even when you might not think so. Procedural, OO, functional, relational, logical/constraint ... they all have their place even if you're forced to code in machine code, and so do the various subflavors (e.g., the many ways in which OO can be approached -- with or without multiple dispatching, the many ways to model and implement dispatching, etc). For example, often you build little languages for task specific issues, embedded in whatever other languages you're programming with. Scheme and Lisp are quite good for that, but you can and do perform such activities in any language. Then, having some model of paradigms you can use and how to implement them is nice. > What is the lesson to be learned from "Structure and interpretation of > Computer Programs"? Maybe it's main purpose is to provide an enjoyable > read for those who have still not given up on lisp. It's not about Lisp -- it's about mental models of computation. SICP's purpose is definitely not to give concrete, usable-today tips. It's to broaden your horizons, enriching your panoply of mental models about computation. That's why it's no good for people who like to think concretely, and why the "gurus like this book" diagnosis is unfair to many brilliant people who _don't_. > Seriously, what was I supposed to have gained from all that time I spent > on > this book. As you may suspect, it captivated me, too. Aha -- this sounds like somebody WITH appetite for abstract thought (else you wouldn't have liked it) subject to cultural / peer pressures towards concreteness (else you wouldn't feel that broadening your horizons, without learning anything immediately-usable, might be a waste of time). > It did not teach me good Python programming style. I could not hardly > read my own code with all those many layers of parentheses. True, alas -- lispish concrete syntax [expletive deleted] -- expect mild flames from those who like it, of course:-). > It did not teach me how to use Python data structures. I found myself > doing too many screwy things with lists. Python's lists are definitely not what you want as a direct replacement for lisp/scheme ones -- you can build the latter with two-item tuples (if immutable) or lists (if mutable) a la: class lispnode(object): __slots__ = '_car', '_cdr' def __init__(self, car=None, cdr=None): self.car = car self.cdr = cdr cons = lispnode and any embellishments you want to iterate on lispish lists made of such nodes, form such a lispish list from any Python iterable, &c. > I was supposed to learn something more theoretical, right? What was it? See above. > Or, was this book just a devious way to trick more people into using lisp? Naah... not in the concrete-syntax way. It's just that some concepts are fruitful and usable even in other languages. Alex From steve at ferg.org Fri Sep 13 08:43:01 2002 From: steve at ferg.org (Stephen Ferg) Date: 13 Sep 2002 05:43:01 -0700 Subject: ANN: Thinking in Tkinter References: <3D798461.B3FE0E06@earthlink.net> <3D7C210F.7090708@something.invalid> <3D7FF299.2020509@something.invalid> Message-ID: Greg Ewing wrote in message news:<3D7FF299.2020509 at something.invalid>... > It might be better to start with some object > other than a button for the purpose of introducing the > concepts of event binding. Otherwise you're teaching > people an incorrect way of using buttons that they're > going to have to unlearn later. Thanks for your help in other messages in this thread. After thinking it over, my current plan is still to start with Button, just because it supports both event binding and command binding. And also, of course, because Button is the obvious choice for the first widget to learn. So my plan now is first to explain event binding on Button. Then I'll explain command binding on button, and do a "compare and contrast" with event binding: discussing why command binding is better than event binding, noting that it does NOT automatically pass an event object, that it may be available with other widgets than Button, etc. And I'll be careful in the earlier discussion to note that even though we're looking at event binding first as a way to introduce the concept of binding, we'll also soon be looking at a better way (i.e. command binding). From ant at mongrel.dogpound Sun Sep 1 17:57:39 2002 From: ant at mongrel.dogpound (Anthony Ventimiglia) Date: Sun, 01 Sep 2002 21:57:39 GMT Subject: Converting Python app to C++ completely References: Message-ID: On Fri, 30 Aug 2002 13:09:48 +0100, Alan James Salmoni wrote: > Sean 'Shaleh' Perry wrote: >> In general C++ will be more verbose than Python. Using references and the STL >> it is possible to code fairly complex applications without using pointers but >> most likely you will have to learn about them and use a couple. > > I think that's what worries me - luckily, my code is fairly basic so I > might be able to avoid them as much as possible, but I should learn > about them really. Don't be afraid of pointers, they're really not that bad. The STL really allows you to do quite a bit without having to directly do any memory allocation. I'll also add another recommendation for reading Stroustrup. From magnus at thinkware.se Fri Sep 20 06:37:19 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Fri, 20 Sep 2002 12:37:19 +0200 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: <3D8AFA5F.4030205@thinkware.se> jason petrone wrote: > A few other polished programs written in python: > > Visual Python: http://www.activestate.com/Products/Visual_Python/ ... > Visual Python probably has the prettiest screenshot. Stop there! Visual Python is a python plugin for Microsoft Visual Studio, right? So what you see is Visual Studio, which is AFAIK written in C++ with MFC. Or am I in deep waters here? I think it's written _for_ python, not _in_ python. From amk at amk.ca Sat Sep 21 20:32:51 2002 From: amk at amk.ca (A.M. Kuchling) Date: Sun, 22 Sep 2002 00:32:51 -0000 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D8A7630.9090108@something.invalid> Message-ID: In article <3D8A7630.9090108 at something.invalid>, Greg Ewing wrote: > How does it (or how is it envisaged that it will) > handle callbacks from C to interpreted code? Will > it remain stackless under those conditions? I have no idea, and would imagine that it hasn't been designed yet. Looking at how Perl5 works might provide some guidance, because it'll probably look similar in Parrot. (Looking at the perlcall.pod document, which describes how to call Perl5 code from C, it looks like callbacks from C are not stackless, because you just call the call_sv() function which will return the result.) --amk From aleax at aleax.it Thu Sep 26 07:54:54 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 11:54:54 GMT Subject: CGI server by Python References: Message-ID: Brian Lee wrote: > Hi, > > I tested CGIHTTPServer.py in Python 2.2 and found that cgi files in > sub directory does not run. Does anybody know about this? ... > avante.xxx.co.kr - - [26/Sep/2002 19:20:24] code 403, message CGI script > is not a plain file ('/cgi-bin/a') avante.xxx.co.kr - Exactly as it says, /cgi-bin/a is not a plain file (it's a directory!) and CGIHTTPServer.py is written to support plain files right under cgi-bin only. See the parsing in function run_cgi around line 100 and following of that file in your Python library directory. If you don't like the way it parses things, it ain't hard to modify... Alex From zopestoller at thomas-guettler.de Tue Sep 24 06:41:00 2002 From: zopestoller at thomas-guettler.de (Thomas Guettler) Date: Tue, 24 Sep 2002 12:41:00 +0200 Subject: convention for Pickler file extension References: <918bc22f.0209230208.4eaca702@posting.google.com> Message-ID: Terry Reedy schrieb: > "Donnal Walter" wrote in message > news:918bc22f.0209230208.4eaca702 at posting.google.com... > >>When one uses Pickler.dump(object) to serialize an object to a file >>associated with the Pickler, is there a Python convention for the > > file > >>extension name? > > > If there is not currently, I think .pyp is available. I call files *.pickle thomas From bogle at ihug.co.nz Fri Sep 6 19:32:57 2002 From: bogle at ihug.co.nz (Gib Bogle) Date: Sat, 07 Sep 2002 11:32:57 +1200 Subject: Python from C/SDL Message-ID: <3D793B29.3198AB0E@ihug.co.nz> Hi, I am a complete beginner with Python. My interest in it is focussed on a great piece of open-source software called pymol, a system for visualization of molecules that uses Python and OpenGL. I'd like to get access to pymol's graphical functions from my own program, which is built from C, SDL and OpenGL. I'm wondering if (with a bit of surgery) I'd be able to get access to the lower-level functionality of pymol, by which I mean the file I/O and rendering functions. I will not want to use the GUI at all. SDL would create the surface(s), and handle the buffer swapping. My goal is to be able to send a request to the pymol API asking for a frustum view to be rendered on the provided surface. Sorry if my question is one that gets asked and answered frequently. If there is a place where this has been dealt with please direct me. thanks Gib -------------------------------------------- Gib Bogle bogle at ihug.co.nz 1/44 Arthur St Tel: (64-9) 525-6878 Ellerslie, N.Z. Fax: (64-9) 525-6878 -------------------------------------------- From eric.brunel at pragmadev.com Tue Sep 3 03:51:58 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 3 Sep 2002 09:51:58 +0200 Subject: what about things like __*** ? References: <7153651c.0209021927.16a3efaf@posting.google.com> Message-ID: black wrote: > Hi, all~ > > when reading the tutorial I met some trouble.(Maybe trifle to you all > but really trouble to me) > > That is I couldnt figure out what __*** is. Here is the description of > that article but even confused me: > > There is limited support for class-private identifiers. Any identifier > of the form __spam (at least two leading underscores, at most one > trailing underscore) is now textually replaced with _classname__spam, > where classname is the current class name with leading underscore(s) > stripped. > > What's it trying to say please ??? As a good practice in object-oriented programming, the structure of a class, i.e. its actual attributes, are often hidden from the outside world. It's called "encapsulation". It helps to separate the interface of the class from the actual implementation of the methods, that shouldn't be known outside the class itself. Languages like C++ or Java have a native support for encapsulation, by allowing to declare attributes "private" or "protected". A value of a private or protected attribute can't be read or set by another class than the owner class (or one of its sub-classes for protected attributes). IIRC, before Python 2.0, there were no support at all for encapsulation in Python. So you could always do: class C: def __init__(self): self.a = 12 o = C() o.a = 13 print o.a The attribute "a" of instances of class C can be read or modified outside the class, and there's no (simple...) means to prevent that. >From Python 2.0, there's a (limited) support for encapsulation: if the name of an attribute begins with a double-underscore, it's just as if it had been declared private: class C: def __init__(self): self.__a = 12 def get_a(self): return self.__a o = C() o.__a = 13 # Does not work print o.__a # Again, does not work print o.get_a() # Works class CC(C): def __init__(self): C.__init__(self) print self.__a # Does *not* work The attribute __a is private: it can be seen only in the class C. It's impossible to read or set it from outside the class, even in one of its sub-classes. This sounds like a big restriction, but is actually very often used in OO programming. The actual mechanism involves a "name-mangling", and that's what the comment tried to explain. But it's not that important: the final result is just that any attribute beginning with a double-underscore is private. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From loewis at informatik.hu-berlin.de Mon Sep 9 03:50:57 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 09 Sep 2002 09:50:57 +0200 Subject: Embedding - Local dictionaries for local scripts References: <1691b372.0209060746.55b8cf1@posting.google.com> Message-ID: chris.walsh at real-sense.com (Chris Walsh) writes: > PyObject* PyRun_String( > char *str, > int start, > PyObject *globals, > PyObject *locals); > > I have seen some stuff in comp.lang.python about creating a dict and > adding the __builtin__ module but I have been searching now for an > hour and cannot find it. > > Can anyone point me to some code which creates this dictionary? The globals/locals dictionary is not really different from any other dictionary; you create them with PyDict_New. Python should transparently add an __builtins__ into the globals dictionary if there is none, but you can copy the __builtins__ entry just as well yourself (via PyDict_SetItemString). HTH, Martin From sschwarzer at sschwarzer.net Thu Sep 12 16:01:32 2002 From: sschwarzer at sschwarzer.net (Stefan Schwarzer) Date: Thu, 12 Sep 2002 22:01:32 +0200 Subject: "str.contains(part)" or alternatives? References: Message-ID: Hi Skip Skip Montanaro wrote: > >>> try: > ... s.index('ll') > ... do_something_if_found() > ... except ValueError: > ... do_something_if_not_found() > > Stefan> This has the problem that a ValueError raised in > Stefan> do_something_if_found() may give the false impression that the > Stefan> substring isn't contained in the string s. > > I try to minimize the amount of code executed in try blocks. Me too. That above was only a (bad) example. ;-) > Use this instead: > > try: > s.index('ll') > except ValueError: > do_something_if_not_found() > else: > do_something_if_found() I just read today in the Python Cookbook that this syntax is valid. I never saw it in Python code (not meaning that I believe it doesn't exist :) ). As a side note, I remembered then that there are also "else"-Forms of the while and the for loop which are executed when the loop is left via break (IIRC). Thank you (and all others) for their answers. I didn't expect to get so many. Btw, Greg, the .count approach is much nicer than ".find != -1". Stefan From fredrik at pythonware.com Wed Sep 4 18:13:43 2002 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Sep 2002 22:13:43 GMT Subject: How to force built-in commands over imported. References: <3D761C39.4020802@akst.tn.tudelft.nl> Message-ID: Gerhard H?ring wrote: > The technical answer is to use __builtins__["open"]. that should be: import __builtin__ file = __builtin__.open(...) __builtins__ is an implementation detail. From lu_gio at hotmail.com Tue Sep 3 19:19:00 2002 From: lu_gio at hotmail.com (Max) Date: Tue, 3 Sep 2002 23:19:00 +0000 (UTC) Subject: Database BSD on Mac? Message-ID: <3144be3c280c062e5e71a98ab191f664.98737@mygate.mailgate.org> Hi! I'm implementing a simple data manager to store few images and sounds (<5Mb). I'm developing a game on windows platform (so, I don't need a client server db like mysql) but I'd like to port the software on every python supported platform (well, principally on win,linux and mac). I was looking on BSD but I'm not sure it is ported to all platforms. Wich db should I utilize? -- Posted via Mailgate.ORG Server - http://www.Mailgate.ORG From cbarber at curl.com Thu Sep 19 13:01:05 2002 From: cbarber at curl.com (Christopher Barber) Date: 19 Sep 2002 13:01:05 -0400 Subject: Larry Wall's comment on python... References: Message-ID: "Chris Gonnerman" writes: > No smiley this time... I really hate typing curly after curly. > It makes me wonder that anyone *likes* the freakin' things so > much that they named a LANGUAGE after them. The Curl language was indeed named after curly braces, but not because we like them so much but because the nature of the language required some sort of bracketing delimiter punctation and the curly brace seemed a good choice for this. One of the points of the language is to make it easy to do powerful text markup and otherwise mix code and text. To support this, you really need some way to distinguish code from text. For instance: {paragraph Hello {bold Bold} World!} Although it might be annoying to have to type the curly braces, I really don't know what the alternative would be. Parens and square brackets are used much more frequently in text than curly braces and would have to be escaped more frequently, and SGML syntax is much worse. I don't think there is a way to do this kind of thing using Pythonic syntax. - Christopher From chironsw at swbell.net Thu Sep 19 14:06:57 2002 From: chironsw at swbell.net (Greg Goodman) Date: Thu, 19 Sep 2002 18:06:57 GMT Subject: monetary applications (et al) References: Message-ID: <3D8A161E.8060906@swbell.net> > Out of curiousity, does python have any standing in the field of > business accounting? Perhaps those with experience can chime in as to > how this has been handled effectively. We learned long ago to keep all > amounts in whole pennies. The original poster was asking about "currency", which implies a need to store, and possibly to convert between, different currencies. A generic currency class could reasonably store values as long integers, representing the smallest indivisible unit within a given currency (i.e. American cents, English pence, French centimes, Israeli agorot, Afghani puls, etc), along with the number of subunits in the whole (usually 100, but there are exceptions, such as 1000 fils in an Iraqi dinar, or 5 khoums in a Mauritanian ouguiya). On the other hand, cents aren't really indivisible in the American marketplace, where stock prices often change by fractions of a dollar, as in "General Motors down 2 and 1/8". As always, the class you build is determined by the use you to which you intended to put it. Greg Goodman From jb at cascade-sys.com Fri Sep 20 00:51:25 2002 From: jb at cascade-sys.com (James J. Besemer) Date: Thu, 19 Sep 2002 21:51:25 -0700 Subject: e vs exp()? References: <3a838998.0209191933.1f22e977@posting.google.com> Message-ID: <3D8AA94D.1080801@cascade-sys.com> Buckshot wrote: >Can anyone here explain why I'm getting different results from >e**2 and exp(2)? Which is more accurate? > >Python 2.2 (#1, Mar 27 2002, 14:56:58) >[GCC 2.95.3 20010315 (release)] on sunos5 >Type "help", "copyright", "credits" or "license" for more information. > > >>>>from math import * >>>>e**2 >>>> >>>> >7.3890560989306522 > > >>>>exp(2) >>>> >>>> >7.3890560989306504 > > Mathematica says e**2 to 30 digits is: 7.3890560989306502 272304274606 in which case the second form would happen to be more accurate. Since Python math uses your machine's native floating point formats, precision is necessarily limited and one should not be surprised to encounter minor errors in the least significant bits or digits. Although Mathematica recognizes that the two forms are identical, Python uses different formula for computing the two results. The fact that the base is "e" is of no consequence to the computation. exp() is computed from C's exp() runtime library routine, whereas e**2 is evaluated using C's "pow()" function. In general, I would expect pow() to be less accurate, as pow(x,y) probably is computed by exp(log(x)*y). --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com http://cascade-sys.com From observer at NOSPAM.space.pl Sun Sep 22 15:30:50 2002 From: observer at NOSPAM.space.pl (Johann) Date: Sun, 22 Sep 2002 21:30:50 +0200 Subject: Problems with starting Python IDE Message-ID: I cannot I "Python IDE" on my PPC 7600 because of exception errors as the following: "Python 2.2.1:Mac.Tools:IDE:Splash.py, line 51, in Update.Splash splash.GetDialogWindow().ValidWindowRect(splash.GetDialogPort().portRect) NotImplementedError: Not available in this shared library/OS version" What is wrong? I am using clean install of os 8.1. PPC7600/200MHz, 256MB RAM. It should work.... I got no warnigs nor errors during instalation. -- Johann From neal at metaslash.com Wed Sep 4 17:43:23 2002 From: neal at metaslash.com (Neal Norwitz) Date: Wed, 04 Sep 2002 21:43:23 GMT Subject: Strange threads/stack size interaction on FreeBSD References: <3D765A95.6090308@tu-clausthal.de> Message-ID: On Wed, 04 Sep 2002 15:10:13 -0400, Stefan Schwarzer wrote: > OS: FreeBSD 4.6.2 > Python: 2.2.1 (built from the ports collection) Hardware: Dual Processor > Athlon, 1 GB RAM > > I've searched the Python FAQ, Google Groups and the bug database of the > Python project on this, but without success, so I have some questions. > > - Has anybody here experienced something similar, perhaps on other > platforms? Doesn't sound familiar. > - Is Python's threading code dependent on a stack limit set at compiled > time (seems so)? Not that I know of. > - What are your recommendations to deal with the problem? You can try reducing the recursion limit: import sys sys.setrecursionlimit(100) # default is 1000 > - Should I enter a bug report on this topic? Probably, although, there are few people who can test with your configuration. So you may be stuck debugging this yourself. If you have stack traces, are they very long? where does the crash occur? What compiler are you using? Can you report all the tests that don't pass? Have you tried with the latest and greatest source? 2.2.1+: cvs update -r release22-maint 2.3: cvs update -A Neal From see_reply_address at something.invalid Wed Sep 25 22:12:18 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Thu, 26 Sep 2002 14:12:18 +1200 Subject: Larry Wall's comment on python... References: <3D8E6353.7030303@something.invalid> <96zj9.150553$pX1.5399868@news2.tin.it> <3D911CFA.4060405@something.invalid> Message-ID: <3D926D02.4000503@something.invalid> Alex Martelli wrote: > (take it up with KDE KNode's maintainers whether their news > reader is "dumb"... I like it, though it doesn't show tabs:-). Apologies -- I didn't mean to denigrate any piece of software with the term. I was just using it as shorthand for (in this context) "not having any features provided for customising the display of tabs". -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From pereira at cis.upenn.edu Tue Sep 3 20:09:33 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Tue, 03 Sep 2002 20:09:33 -0400 Subject: Would you like a Snobol pattern matcher? (Re: Making regex suck less) References: <3d725881.345921@news.t-online.de> <3D740DFC.1040009@something.invalid> Message-ID: On 9/3/02 2:13 PM, in article al30tq$aud$1 at solaris.cc.vt.edu, "Carl Banks" wrote: > I think there is a good reason to have a higher level syntax. It > serves a purpose heretofore unserved: that complex regular expressions > no longer have to be unbearably unreadable. The stronger version of this point is that at the moment there are no methods for composing complex expressions from simpler ones that do not involve manipulating strings, like building complex Python programs by taking their pieces as strings, gluing them together and passing the result to eval. Clearly a mess. For a good example of an alternative approach (in Scheme) see http://www.ai.mit.edu/people/shivers/sre.txt The beauty of this kind of approach is that the expressive power of the host language is fully available in constructing complex expressions. -- F From gtaylor at lowebroadway.com Fri Sep 27 07:34:37 2002 From: gtaylor at lowebroadway.com (Garry Taylor) Date: 27 Sep 2002 04:34:37 -0700 Subject: Unicode (inc. Japanese) in Python and TK Message-ID: Hi, I'm just seeking a little reassurance regarding use of unicode in Python, before I write my program, and then later find out I'm going to have to re-write in Java or something. Basically, am I going to run into any brick walls by doing the following: 1) Parsing XML with unicode characters. 2) Measuring unicode characters using TK 3) Printing unicode to a file Really, I just want someone to pat me on the back any say 'everythings going to be alright'. The reason I am sceptical is I have used Perl for similar antics, and now now I wake up screaming, lying in a pool of my own sweat. Thanks, sorry if this is a FAQ Garry From blarson at crary.com Thu Sep 12 12:08:26 2002 From: blarson at crary.com (Bradley D. Larson) Date: Thu, 12 Sep 2002 11:08:26 -0500 Subject: Coding Style: Quotes References: <20020912105305.A6508@phy.duke.edu> Message-ID: <3D80BBFA.8F1122A1@crary.com> Since most SQL statements utilize single quotes to designate 'strings' I have gone pretty much to double on the outside and single on the inside. ie. sql = "update mytable set firstname = 'Brad' where idx = 1;" execute (sql) Otherwise the decision is pretty much arbitrary. Michael Stenner wrote: > On Thu, Sep 12, 2002 at 02:25:11PM +0000, John Waycott wrote: > > I'm curious if others have adopted any standards for choice of single vs. > > double quotation marks to delimit strings. A look through the standard > > library reveals the choice of one over the other is rather arbitrary. I > > suspect it really makes no difference, but the question has come up during a > > code review. > > Since there is no "physical" difference between them, I can't imagine > why it would matter. The only reason there "needs" to be two is for > nested quoting. Sure, it would be annoying to alternate for each > string, but beyond that... > > Personally, my use tends to be c/perl influenced. I use single quotes > for short static things and double quotes for longer things and format > strings. > > f['key'] = "This is a long string, but it's just _my_ style..." > > -Michael > > -- > Michael Stenner Office Phone: 919-660-2513 > Duke University, Dept. of Physics mstenner at phy.duke.edu > Box 90305, Durham N.C. 27708-0305 > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: blarson.vcf Type: text/x-vcard Size: 400 bytes Desc: Card for Bradley D. Larson URL: From lbrannma at cablespeed.com Sun Sep 22 14:10:06 2002 From: lbrannma at cablespeed.com (Lance) Date: Sun, 22 Sep 2002 11:10:06 -0700 Subject: sys.ps2 assignment has no effect Message-ID: I'm running the latest Python on Windows XP. The default installed secondary string appears to be blank spaces rather than an ellipse. The following has no effect: import sys sys.ps2 = '... ' Any suggestions? Thanks, Lance From missive at frontiernet.net Sun Sep 1 17:19:14 2002 From: missive at frontiernet.net (Lee Harr) Date: Sun, 01 Sep 2002 21:19:14 -0000 Subject: del(instance.attr) -- no attribute Message-ID: Is this a bug? >>> class C: ... a = 1 ... >>> c = C() >>> c.a 1 >>> del(c.a) Traceback (most recent call last): File "", line 1, in ? AttributeError: C instance has no attribute 'a' >>> hasattr(c, 'a') 1 >>> I can see that maybe del(c.a) should not be allowed to delete the attribute, but I think the error message is misleading. From vetter at lincom-asg.com Wed Sep 4 11:40:22 2002 From: vetter at lincom-asg.com (Keith) Date: 4 Sep 2002 08:40:22 -0700 Subject: Regexp Over Multiple Lines Message-ID: <565e316f.0209040740.36573b56@posting.google.com> In Python can I have a regular expression that spans multiple lines... e.g. In Perl I may define a regular expression like: $depends_def = qr/ [\w_\.]+\s*: # simobject: \s* [\w_\.]+ # job name \(\s*(?:[\d]*)?\s*\) # arg list for job (optional num) \s+ depends\s+on # keywords "depends on" \s+ (?: [\w_\.]+\s*: # simobject: \s* (?: [\w_\.]+ # job name \(\s*(?:[\d]*)?\s*\) # arg list for job (optional num) (?: (?: \s+ and\s*[\w_\.]*\s*: # "and simobject:" \s* [\w_]* # job name \(\s*(?:[\d]*)?\s*\) # arg list for job (optional num) )+ )? # match optional "and" 1 or more times ) ) /sx; then later I can use that regular expression in another regular expression. It helps to span multiple lines for commenting what the heck the ugly regular expression is trying to do... BTW: I am investigating Python and have no knowledge of it. Our Perl code has just gotten out-of-hand. Thanks, Keith From fgranger at alussinan.org Fri Sep 27 12:49:57 2002 From: fgranger at alussinan.org (=?ISO-8859-1?Q?Fran=E7ois_Granger?=) Date: Fri, 27 Sep 2002 18:49:57 +0200 Subject: Length of file extension Was: convention for Pickler file extension References: <918bc22f.0209230208.4eaca702@posting.google.com> Message-ID: <1fj6mww.zdjb2wpp3dogN%fgranger@alussinan.org> Thomas Guettler wrote: > Richie Hindle schrieb: > >>I call files *.pickle > > > > Are there any non-medieval platforms that don't let you have arbitrary > > length file extensions? > > I think it works for Win98, WinNT, Win2000 and of corse Unix. > > Don't know about Mac MacOS 9 does not know of file extension and allow dots(.) inside a name. So, no limit. > or MacOSX is Unix. -- "Le plus difficile au monde est de dire en y pensant ce que tout le monde dit sans y penser." - Alain (?mile Chartier, dit), Histoire de mes pens?es - cit?e par Natacha From kathuw at swbell.net Thu Sep 26 01:27:31 2002 From: kathuw at swbell.net (Kat & Huw) Date: Thu, 26 Sep 2002 00:27:31 -0500 Subject: curses troubles Message-ID: <000001c2651d$7f2b5b40$0100a8c0@mshome.net> Ok, problem. I'm trying to take user entered data input and store it as a var. inside an __init__ I have curses set up a window, and display some options. Then I use: while 1: self.k = self.stdscr.ch() if self.k == ord('G'): do_this() elif self.k == ord('P'): do_another() elif self.k == ord('Q'): break Now, when running this, if I hit either G or P, the applications closes as if I'd hit Q any idea what I'm doing wrong here? yours, Huw -------------- next part -------------- An HTML attachment was scrubbed... URL: From jhorneman at pobox.com Sun Sep 29 12:39:28 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: 29 Sep 2002 09:39:28 -0700 Subject: Python's import: why doesn't it work? Message-ID: <9ac02e81.0209290839.4f4d6475@posting.google.com> Once again my attempt to profit from Python's vaunted productivity increase has come to a screeching halt because some innocent thing that one would reasonably expect to work in one line, intuitively, and without even having to think about, turns into a nightmare already lasting more than an hour, requiring numerous experiments, searching through the documentation - both manually and using my editor's find-in-files - finally leaving me no other option but to write a post to comp.lang.python, knowing that my programming flow for today is well and truly gone. I hate doing this, because I know I cannot keep my frustration out of my writing, and also that someone will reply and gently or not so gently point out something which actually IS written down in some obscure corner of the documentation, despite my attemps to RTFM. So, what is it this time? No, it's not Unicode, another aspect that frequently trips me up, causing my face to meet the rough asphalt of the infobahn. It's importing modules. Again. (This is an obscure reference to an attempt on my part to implement MBCS conversion functions as Python codecs. This failed miserably and despite the helpful advice I received here, I never did try again. Too bad, because those conversion functions are pretty good. And since I'm doing some parenthesized ranting here: does anyone outside of the Python world use 'codec' to refer to anything except audio / video codecs? I actually had to post here just to find out that what I was looking for were *called* codecs. Sheesh.) Anyway. I have this script, let's call it 'blah.py'. It sits in a directory far, far away from where my Python is installed. It wants to include a module called 'intro' from a subdirectory called 'templates'. This is evidently impossible. Among my vain, futile attempts were: *** Solution 1 *** The World is a Beautiful Place >>> import templates.intro Ha! ha! ha! OK, even I knew this was a bit optimistic. *** Solution 2 *** .PTH file Put a templates.pth containing the single line 'templates' in the same place as 'blah.py', then >>> import templates.intro or >>> import intro No dice: 'ImportError: No module named...' etc. *** Solution 3 *** IMPorting by hand >>> import imp >>> f = open('templates\intro.py') >>> imp.find_module('intro.py') Traceback (most recent call last): File "", line 1, in ? ImportError: No module named intro.py >>> imp.find_module('intro') Traceback (most recent call last): File "", line 1, in ? ImportError: No module named intro >>> imp.find_module('intro', '\\templates\\') Traceback (most recent call last): File "", line 1, in ? ImportError: No frozen submodule named .\templates\.intro (No WHAT?) >>> imp.find_module('intro', '\\templates\\') Traceback (most recent call last): File "", line 1, in ? ImportError: No frozen submodule named \templates\.intro >>> imp.find_module('intro', ['\\templates\\']) Traceback (most recent call last): File "", line 1, in ? ImportError: No module named intro >>> imp.find_module('intro.py', ['\\templates\\']) Traceback (most recent call last): File "", line 1, in ? ImportError: No module named intro.py >>> imp.find_module('intro', ['.\\templates\\']) (, '.\\templates\\intro.py', ('.py', 'r', 1)) Whoa! I finally managed to call imp.find_module without raising an exception! OK, now to call imp.load_module, because the documentation says: "Load a module that was previously found by find_module()" Alright, so there seems to be some connection between find_module and load_module... The latter probably takes the return value of the former as a parameter, right? Right? Wrong. Here are my attemps to call imp.load_module: x = imp.find_module('intro', ['.\\templates\\']) >>> y = imp.load_module('intro', f, 'intro.py', x) Traceback (most recent call last): File "", line 1, in ? TypeError: load_module() argument 4, item 0 must be string, not file >>> y = imp.load_module('intro', x) Traceback (most recent call last): File "", line 1, in ? TypeError: load_module() takes exactly 4 arguments (2 given) Okay, wait, my assumption was obviously naive, better read the doc... aha. Almost the same parameters as find_module... wonder why I even needed to call find_module in the first place. OK: >>> y = imp.load_module('intro', f, 'intro.py', imp.get_suffixes()) Traceback (most recent call last): File "", line 1, in ? TypeError: load_module() argument 4 must be sequence of length 3, not 5 What? But... but... *splutter* the doc says: "The description argument is a tuple, as would be returned by get_suffixes(), describing what kind of module must be loaded." So why doesn't this work? OK, I have no idea why I'm bothering with these kinds of arcana, but for the heck of it I'll try: >>> y = imp.load_module('intro', f, 'intro.py', ('.py', 'r', 1)) Traceback (most recent call last): File "", line 1, in ? File "intro.py", line 29, in ? ImportError: No module named Base Yay! What?! Now my IMPORTED module can't find the modules IT is trying to import? (It doesn't matter if I put Base next to Blah.py or in templates - Intro can't find it.) Arrrgghhh!!!! OK, enough time spent on this dead end. (Oh, and by the way not all the functions of the imp module are documented.) *** Solution 4 *** Packages OK, more searching, browsing and scouring my hard drive for the word 'import'. Of course! I forgot that in the Python docs, important information is cunningly hidden in the Tutorial section! (Really, am I being unreasonable for assuming that once one has reached a certain level of knowledge, one shuns the Tutorial and goes straight for the main documentation, because that's where one can find everything there is to know? That's only how it works in every language or piece of software in general I've ever encountered.) So there are these things called 'packages'. Wow! Handy, that! All one needs to do is put an empty file called '__init__.py' in a directory, and hey! That directory becomes a package and Bob's your uncle. So I put an empty file called '__init__.py' in 'templates' and try the following: >>> import templates.intro Traceback (most recent call last): File "", line 1, in ? ImportError: No module named templates.intro >>> from templates import intro Traceback (most recent call last): File "", line 1, in ? ImportError: No module named templates This is *exactly* how it's written in the Tutorial, and it-does-not-work. *** Solution 5 *** Abject Defeat, Ask on Internet, Be Ridiculed by Peers for Not Managing Basic Operation Amusing little anecdote: I've performed all of the above steps twice - once while growing increasingly frustrated, and a second time while writing this post. Twice, while typing in the code above, I at some point entered: import intro ... and it would work. For real. The symbols were there. Not a peep out of the interpreter. Because I don't trust PythonWin (don't get me started on PythonWin, I haven't found a better IDE yet, I may actually succumb and PAY for one soon *shock horror*) I quit and restarted and lo and behold! the interpreter complained that there was no such module, as it had been doing all along, the horrible beast. In other words, at random, unreproducable moments, Python perversely imported my module, whereas normally it refused to. To cut a long story... hm... Please please help me! Stop me before I whine again. And please don't be offended by my ranting, I just can't hide this much frustration. I'm using Python 2.2 by the way. Thanks in advance, Jurie. From phr-n2002b at NOSPAMnightsong.com Fri Sep 20 00:03:40 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 19 Sep 2002 21:03:40 -0700 Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <23891c90.0209190014.26c5bb9@posting.google.com> Message-ID: <7xk7lhb943.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > The only language I've ever encountered that had a truely monetary > safe fixed point data type is COBOL -- which has always used packed BCD > formats (though where the sign "bit" is stored may vary). COBOL was > created from the beginning for "business" applications (heck: COmmon > Business Oriented Language) and was spec'd by a government team. My > college mainframe required /four/ of the sixteen registers to hold > /one/ BCD number (32 BCD digits, 2 digits/byte, 16bytes @ 4/register). I'm finding it hard to imagine how any real-world financial calculation using IEEE doubles could be off by as much as a penny. BCD doesn't guarantee accuracy either. If you do a compound interest calculation in BCD and in IEEE floating point, the floating point answer will probably be more accurate. From sa at hogia.net Mon Sep 9 05:24:27 2002 From: sa at hogia.net (Sebastian Andersson) Date: Mon, 9 Sep 2002 09:24:27 +0000 (UTC) Subject: How to embed python ? Message-ID: I've got an old game server where I would like to make the server extensible via python code which will be called when things happen in the game. I would like to call different code depening on the event and I would like to pass on different data. In the game server I've got level files where I intend to put the python code. It will look something like this: triggers { 0,0 79,17 (enter) { def my_helper_function(): rch2.message(m, NOW, "Hello there") my_helper_function() rch2.message(m, NOW, " and bye now!) }; }; (The first two lines and the last two lines are part of the level file format). I use Py_CompileString to compile the python code. As it is now I have to remove the extra white space before each line while building the string. Is there a way around that to let Py_CompileString do it by itself? Or even better, is there a way to pass each line by itself to the python parser and let it signal when the white space count has become too small (ie on the " };" line) ? How should I organize the python code? The first argument to all "triggers" is an integer called m. Then follows one, two or three arguments that vary depending on the trigger. Should I make each piece of code into a function with the correct arguments or should I just put the triggers' arguments into variables before calling the code with PyImport_ExecCodeModule ? Should I use the code as above or should I put it inside a function definition and later call that function instead of using PyImport_ExecCodeModule ? I want each trigger call to be as fast as possible. TIA, /Sebastian From sholden at holdenweb.com Mon Sep 9 16:04:06 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 9 Sep 2002 16:04:06 -0400 Subject: transform a list of lists in a lit of strtings??? References: Message-ID: "James Kew" wrote in message news:algb9t$1q0jg0$1 at ID-71831.news.dfncis.de... > "James Kew" wrote in message > news:algah9$1p0kp3$1 at ID-71831.news.dfncis.de... > > labels1 = [["D1"], ["D2"], ["D3", "D4"]] > > --> labels2 == ["D1", "D2", "D3", "D4"] > > > labels2 = reduce(lambda x, y: x+y, labels1) > > > > Can this be written in list comprehension form? > > Emile's google link suggests (a) flattening is a hoary old chestnut, and (b) > yes it can: > > labels2 = [i for item in labels1 for i in item] > > (I find this oddly hard to read.) > This will work if your list structure can contain data items and lists with data items in them, but it won't flatten a nested list structure of general complexity. For example: >>> labels1 = [ [1, 2], [[3, 4, 5], 6], [[[7], 8], 9]] >>> labels2 = [i for item in labels1 for i in item] >>> labels2 [1, 2, [3, 4, 5], 6, [[7], 8], 9] For a complete solution to such a problem you have to use recursion, testing whether each item you process is composite and recursing to flatten it if so. This has been discussed so many times before that you should use Google to find the best way. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From aleax at aleax.it Thu Sep 26 07:50:46 2002 From: aleax at aleax.it (Alex Martelli) Date: Thu, 26 Sep 2002 11:50:46 GMT Subject: Getting last char in string. References: Message-ID: CheapSkate wrote: ... > if s[-1] returns a single element, why woulnd't it return " ? > Single character are strings of length 1(as u said) and " is single > character right? Nope: '', the empty string, is 0 characters, not 1 character. Alex From jepler at unpythonic.net Sat Sep 28 15:25:26 2002 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 28 Sep 2002 14:25:26 -0500 Subject: Python threading? In-Reply-To: References: Message-ID: <20020928142517.A3027@unpythonic.net> On Sat, Sep 28, 2002 at 06:03:57PM +0000, Bengt Richter wrote: > Any thoughts on defining the next method with a generic *args optional arg list > and making it visible to an executing generator function g as g.__args__ ? > > g.__args__ would then just be () for current usage, and could be > backwards-compatibly ignored as desired. I think you can get something like this using a class. For this solution, you'll need to make the list visible as a parameter to the generator, or else write it so that you derive a class for each generator, making the generator a method. You may also be able to work something up involving nested functions that lets the inner function see the argument list as a variable in the outer scope. class ArgsGenerator: def __init__(self, f, *args, **kw): self.args = [] self.__iter = f(self.args, *args, **kw) def next(self, *args): self.args[:] = list(args) return self.__iter.next() def primes(x): n = 2 while 1: if x: n=x[0] if n == -1: return while 1: composite = 0 for d in range(2, n-1): if n%d == 0: composite = 1 break if not composite: yield n break n=n+1 n=n+1 x = ArgsGenerator(primes) print x.next() # 2 print x.next(8) # 11 print x.next() # 13 print x.next(-1) # raises StopIteration Jeff From nhycqb at yahoo.com Sat Sep 14 01:03:09 2002 From: nhycqb at yahoo.com (nhycqb at yahoo.com) Date: Sat, 14 Sep 2002 05:03:09 +0000 (UTC) Subject: $$$$$ secret realease for the first time 5484 Message-ID: http://myweb.ecomplanet.com/PETE7323/ http://myweb.ecomplanet.com/PETE7323/ - Instant Download - Instant Download - Instant Download Free Download The Absolute Beginner's Guide to Starting a Web Site Totally Free Web Resources Unlimited Profits 7 Secrets To Unlimited Traffic Scientific Advertising How to Start Your Own Traffic Virus Marketing Warriors Tips eBookoMatic eBook Submitter The Best of Web Gold On Line Stealth Marketing and more http://myweb.ecomplanet.com/PETE7323/ http://myweb.ecomplanet.com/PETE7323/ - Instant Download - Instant Download - Instant Download http://myweb.ecomplanet.com/PETE7323/ http://myweb.ecomplanet.com/PETE7323/ klmbteirptjjozqulyehheueoosxviecjcdneirgijgvnsjbtdkphdvecnqzdtuclpjjucnmftwmkdhvliqcbdby From jason at mastaler.com Thu Sep 5 16:01:37 2002 From: jason at mastaler.com (Jason R. Mastaler) Date: Thu, 05 Sep 2002 14:01:37 -0600 Subject: New `spambayes' project on SourceForge References: <15735.40259.117828.402419@anthem.wooz.org> Message-ID: barry at zope.com (Barry A. Warsaw) writes: > There are also two mailing lists related to the spambayes project. > The first is a general discussion list: > > http://mail.python.org/mailman-21/listinfo/spambayes > > and the other is a list for cvs checkin message notices: > > http://mail.python.org/mailman-21/listinfo/spambayes-checkins These lists have now been added to Gmane (http://gmane.org) as well: spambayes at python.org <==> news://news.gmane.org/gmane.mail.spam.spambayes.general spambayes-checkins at python.org <==> news://news.gmane.org/gmane.mail.spam.spambayes.cvs -- (http://tmda.net/) From pan-newsreader at thomas-guettler.de Thu Sep 19 02:02:16 2002 From: pan-newsreader at thomas-guettler.de (Thomas Guettler) Date: Thu, 19 Sep 2002 08:02:16 +0200 Subject: shared mem & semaphores module References: Message-ID: On Thu, 19 Sep 2002 05:57:44 +0200, Jeff Davis wrote: > I found a module online by "INRIA" (I don't know who that is) that seems > to wrap the C functions for shared memory management and semaphores. > > http://gigue.peabody.jhu.edu/~mdboom/omi/source/shm_source/shm.html > > My question is: are these functions included elsewhere? The threading module has a semaphore class. AFAIK there is no module for shared memory. thomas From henrik.motakef at web.de Sun Sep 1 16:37:34 2002 From: henrik.motakef at web.de (Henrik Motakef) Date: 01 Sep 2002 22:37:34 +0200 Subject: Making regex suck less References: <3d725881.345921@news.t-online.de> Message-ID: <874rd9phtd.fsf@pokey.henrik-motakef.de> gerson.kurz at t-online.de (Gerson Kurz) writes: > So basically, couldn't one come up with a *human readable* syntax > for re, and compile that instead? Python prides itself on its clean > syntax, and human readability, an bang - import re, get perl-ish > code instantly! There is an Emacs Lisp package called "symbolic regexps" (or sregexp.el) that lets you write regular expressions in standard lisp syntax, like (sregexq bol (or "abc" "def")) instead of "^(abc|def)" (bol meaning "beginning of line"). I don't see how that maps elegantly to Python syntax, however. Regards Henrik From kennethg at pd.jaring.my Sat Sep 21 12:09:43 2002 From: kennethg at pd.jaring.my (Kenneth Gomez) Date: Sat, 21 Sep 2002 16:09:43 GMT Subject: Local Python Server Installation References: <3d8b47c6.277669@news.jaring.my> Message-ID: <3d8c993c.2190426@news.jaring.my> Dear Gerhard I tried your method. But instead of getting a cgi listing of my environmental listings, all I saw on my browser was the two input lines ..i.e. import cgi and cgi.test() My url was http://localhost/test.py Any advise. Regards, Kenneth. On 20 Sep 2002 17:36:21 GMT, Gerhard =?iso-8859-1?Q?H=E4ring?= wrote: > >Add this line at the end of your .../Apache Group/Apache2/conf/httpd.conf: > > ScriptInterpreterSource Registry > >Then you can write Python CGI scripts that have the .py extension. I >recommend to create a test.py script with the following two lines: > >import cgi >cgi.test() > >After you verify that this works (http://localhost/cgi-bin/test.py) you can >continue reading the documentation about the cgi module and writing your >own CGI scripts. The cgitb and Cookie modules should come in useful, too. > >If you experience the limits of CGI one day, you can think about using a >full-blown appliation server like WebWare. > >-- Gerhard Cheers, Kenneth Gomez. From claird at phaseit.net Mon Sep 30 15:18:19 2002 From: claird at phaseit.net (Cameron Laird) Date: Mon, 30 Sep 2002 19:18:19 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 30) Message-ID: QOTW: "One can always write very sparse or very dense lines of code that break the model, but in-the-large programmers do not normally do that. They tend to write code in lines that fit easily in their head and, because of this, one line of code is pretty much comparable to another." Jonathan Hogg "Why are there always jobs for salesmen?" Stephen Satchell Jack Diederich makes high-performance Permutations, Combinations, and other probability and statistics constructs available through SourceForge. http://probstat.sourceforge.net/ Puffin makes automation nice. http://www-106.ibm.com/developerworks/opensource/library/os-puffin2.html Pexpect fills in Puffin's most severe lack. http://sourceforge.net/projects/pexpect/ Uche Ogbuji introdues Python's XML and XML-RPC capabilities, and PyXML. http://www.xml.com/pub/a/2002/09/18/py.html http://www-106.ibm.com/developerworks/library/ws-pyth10.html http://www.xml.com/pub/a/2002/09/25/py.html September brought another round of attention to CP4E in the EDU-SIG group http://mail.python.org/pipermail/edu-sig/2002-September/thread.html Think in Tkinter. http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html Martin v. L?wis gives background to management of patches and contributions in the Python project. http://mail.python.org/pipermail/python-list/2002-September/122988.html Blog with Python. http://www.awaretek.com/nowak/kaa.html ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of summarizing action on the python-dev mailing list once every other week. http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From DennisR at dair.com Sun Sep 29 15:38:26 2002 From: DennisR at dair.com (Dennis Reinhardt) Date: Sun, 29 Sep 2002 19:38:26 GMT Subject: Python and GUI question References: <3d96b808_3@news.bluewin.ch> Message-ID: Python could also be used for writing CGI interfaces so that HTML pages are the GUI. HTML has well characterized strengths, weaknesses, and tools support. My web site at http://www.autorunning.com/arpyexe.cgi permits building AutoRunning Windows executables using HTML CGI interfaces from Python source code. -- Dennis Reinhardt http://www.dair.com From pereira at cis.upenn.edu Thu Sep 5 22:59:50 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Thu, 05 Sep 2002 22:59:50 -0400 Subject: Graham's spam filter References: <3D647B4B.28D9BF04@alcyone.com> <3D655AE6.A097AA25@alcyone.com> <3D770156.2E55864C@alcyone.com> <3D77AC75.B9B7F27@alcyone.com> <3D77D657.DE280373@alcyone.com> Message-ID: On 9/5/02 6:10 PM, in article 3D77D657.DE280373 at alcyone.com, "Erik Max Francis" wrote: > Christopher Browne wrote: > >> Quoth Erik Max Francis : >> >>> Spammers are hitting upon the strategy, though, of sending emails in >>> which the body consists of nothing but a completely encoded base64 >>> MIME part. So in that case, the entire body of your message would >>> consist solely of your "base64encoded" token. So in the general >>> case of any kind of spam filter (not just limited to a Graham > ^ >>> filter), it's questionable how useful this will be, unless you plant >>> to always filter against that token, presuming it to always indicate >>> spam. >> >> I've been using naive Bayesian filtering for years; I don't assume >> that _any_ particular token indicates _any_ particular result. > > I thought I made it clear that I was discussing spam filters in general, > not just Graham/Bayesian filters. That is, you overstated the case. Your point may be true of rule-based filters that look for particular words presumed to be spam indicators. But a machine-learning approach using a rich set of message features will pick on *anything* that is correlated with spamminess, not just the obvious features. In an arms race, the spammer may gain temporary advantage by changing message format and thus which features are significant, but after receiving a few new spams, retraining will pick on other appropriate features, for instance fraction of the message bytes that are base-64 encoded. Occasionally, filter designers may want to add new features based on some exploratory analysis of spam, but the decision of which of those are relevant is left to the learning algorithm. -- F From nospam at bigfoot.com Wed Sep 11 08:08:35 2002 From: nospam at bigfoot.com (Gillou) Date: Wed, 11 Sep 2002 14:08:35 +0200 Subject: IDLE References: Message-ID: Can't you be more explicit ? What do you exactly observe when you try to run IDLE ? What's your OS, Python version ? How do you try to run IDLE ? Did you switch the computer power on ? ... --Gilles > Why won't my IDLE work? > > From aleax at aleax.it Wed Sep 18 02:59:15 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 18 Sep 2002 06:59:15 GMT Subject: Python GUI app to impress the boss? References: Message-ID: <7vVh9.108027$ub2.2286654@news1.tin.it> David LeBlanc wrote: ... > What prevents the creation of a decimal money type? I agree, it would be Nothing prevents it. In particular, nothing prevents implementing such a type in Python itself. There are various implementations of decimal numbers around, including one (not sure how mature and complete) that meets the standards for decimal arithmetic behavior (as per the IBM Rexx implementation). It seems to me a relatively simple problem, compared with many others that are routinely solved by Python programmers. If there's no single "best of breed" Currency extension that dominates the scene (as, for example, Lemburg's mxDateTime dominates the date-time handling scene) I suspect it must be because of a lack of demand, strange as it may seem. Defining new types is SO easy... So prove my suspicion wrong: pick an almost-there implementation, complete it per your specs, release it, and see it take over the world. How much effort can it be...? > nice if python could do something akin to calculator aritmetic with types > like scientific (covered) engineering (improper scientific with the > exponent as a power of 3 and the (oops, forgot the term - mantissa?) more That's just an issue of display, isn't it? Computations are just the same whether the calculator is set to always display exponents as a power of three, or not -- at least, that's how I recall my calculator worked: a single button switched display mode from scientific to engineering and back, but all numbers in the calculator's stack and registers were supremely unaffected by it. > then a single digit as in 12.2e3), fixed precision (1..n to the right of > the decimal). The forthcoming fractions are going to be interesting... > (chinese interpretation). If by "fractions" you mean Rationals, that's another thing yet. > Be nice too if math could do rads, grads and decimal degrees. That's a completely different issue: math is a module, not a type. In this case, what you want is simply a different module that wraps math and multiplies/divides some arguments or results by appropriate conversion factors. Still a pretty modest programming effort (all of, what, 10 minutes...?). Modifying the math module to behave this way upon some switch set in it should not be much more. > Just my $0.02 worth. If you really think, just to take a simple example, that having a sin function that accepts degrees rather than radians is important for Python, why not just take the 10 minutes to implement that (or 20 minutes, if you're keep to modify rather than wrap the math module) and thus prove I'm wrong in suspecting that such a project would be pretty much useless...? I'll even volunteer to perform the programming part of the task (not a huge commitment:-) if you undertake to deal with testing, documentation, and advocacy (to get it widely used, and in the long run to get it into the core by popular demand). Alex From jorgencederberg at hotmail.com Fri Sep 13 03:46:27 2002 From: jorgencederberg at hotmail.com (Jørgen Cederberg) Date: Fri, 13 Sep 2002 09:46:27 +0200 Subject: Tkinter experts out there? References: Message-ID: "Marcus" wrote in message news:mOfg9.461067$UU1.75649 at sccrnsc03... > I am trying to get some answers on using Tkinter, does anyone know if there > are channels or forums being actively used? Hi Matthew, you can ask away here in comp.lang.python. People are happy to answer your questions regarding Tkinter. Other resources of interest are: An introduction to Tkinter by Fredrik Lundh: http://www.pythonware.com/library/tkinter/introduction/index.htm Tkinter: GUI programming with Python http://www.nmt.edu/tcc/help/lang/python/tkinter.html Python Faqts http://www.faqts.com/knowledge_base/index.phtml/fid/264 Regards Jorgen From jbublitzNO at SPAMnwinternet.com Sat Sep 7 02:44:12 2002 From: jbublitzNO at SPAMnwinternet.com (Jim) Date: Sat, 07 Sep 2002 06:44:12 GMT Subject: PyQT picture display References: Message-ID: <3D799F42.2020903@SPAMnwinternet.com> Jim wrote: > Hello to all, > > I've a widget with three buttons and a label. I want to display a JPEG > picture when either of the first two buttons is clicked. When I run the > code below, the widget displays on screen but when either button is clicked, > the picture does not appear( the text in the label disappears as it should > ). Can anyone tell me what I'm doing wrong here? As far as I can tell, nothing's wrong. It works fine for me. Are you sure the jpg files actually exist and the path to them is correct? The only thing I changed in your program was the filenames for the image files. I used PyQt-3.3.2 with Qt 2.3.0 on Linux. (another) Jim From narnett at mccmedia.com Wed Sep 4 19:15:01 2002 From: narnett at mccmedia.com (Nick Arnett) Date: Wed, 4 Sep 2002 16:15:01 -0700 Subject: Bind threads to addresses -- Windows & urllib? In-Reply-To: Message-ID: > i think you mean something like this: > > import thread > > > def spiderStuff(Socket): > # do the spider stuff here > pass > > ... > > thread.start_new_thread(SpiderStuff, (,newSocket)) I would like to avoid going to the low-level modules -- I guess I was hoping for something along the lines of urllib or urllib2 that would have already have this exposed. Perhaps I can hack one of them. It looks to me as though I could at least hard-code the addresses into my code, then pass them to a hacked urllib that uses them instead of the localhost and thishost methods. Of course, hard-coding the addresses would be very ugly and non-portable. Any further thoughts out there? Nick From CousinStanley at HotMail.com Fri Sep 27 13:20:19 2002 From: CousinStanley at HotMail.com (Cousin Stanley) Date: Fri, 27 Sep 2002 10:20:19 -0700 Subject: Data Plotting Library DISLIN 8.0 References: <3D940A37.92FD45D5@linmpi.mpg.de> Message-ID: Helmut ... The DISLIN Plot Library from http://www.dislin.de/ looks VERY impressive and widely diversified ... I'm interested in the Python 2.2 version but a bit confused about the various compiler version listings ... Are the compilers listed for the various distributions the ones that have been used to pre-compile a particular version or is the compiler listed the one needed to compile a particular version once DISLIN has been downloaded ??? In otherwords, can I download DISLIN and run __out_of_the_box__ without compiling anything ??? Cousin Stanley From ckasso at sprynet.com Thu Sep 26 18:11:59 2002 From: ckasso at sprynet.com (Chris Kassopulo) Date: Thu, 26 Sep 2002 18:11:59 -0400 Subject: How do you pronounce "__" (double underscore)? References: <525eaba.0209260956.72bf6786@posting.google.com> <20020926164641.1753ebbb.ckasso@sprynet.com> <873crwfowo.fsf@pokey.henrik-motakef.de> Message-ID: <20020926181159.30ec41f3.ckasso@sprynet.com> On 26 Sep 2002 22:59:19 +0200 Henrik Motakef wrote: > Chris Kassopulo writes: > > > How about: > > > > _ = "un" > > __ = "dun" > > "dun-init-dun"? Sounds too much like "done" for me... :-) Then how about: _ = "unce" (rhymes with) __ = "dunce" dunce-init-dunce has a nice ring to it. no? :-) From ponderor at lycos.com Tue Sep 17 14:03:37 2002 From: ponderor at lycos.com (Dean Goodmanson) Date: Tue, 17 Sep 2002 18:03:37 -0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 28) Message-ID: QOTW: "that was the original poster's point. When you start side scrolling it i=s=20 time to refactor." http://mail.python.org/pipermail/python-list/2002-September/121710.html Robert Oschler: "If Peter Piper pickles a peck of Python packages, can he pack the pickled Python peckers in a proper packing place?" Greg Ewing: "Will such suitably squashed SQLed strings satisfy?" http://mail.python.org/pipermail/python-list/2002-September/122479.html "The changes to Python are also so small now, that it doesn't matter if it will be merged or not." Christian Tismer Threads Dealing with whitespace in XML node attribute values: http://mail.python.org/pipermail/python-list/2002-September/121947.html NumPy two-fer: Binary Input and exponentiate zero solutions: http://mail.python.org/pipermail/python-list/2002-September/121978.html http://mail.python.org/pipermail/python-list/2002-September/121981.html Rational Numbers in Python? Demo, but no target for Python 2.3, and PEP 239: http://mail.python.org/pipermail/python-list/2002-September/121998.html Web Crawler iresources noted: http://mail.python.org/pipermail/python-list/2002-September/121591.html Python on WinCE issues summarized: http://mail.python.org/pipermail/python-list/2002-September/122424.html http://www.murkworks.com/Research/Python/PocketPCPython/Overview Pickling objects for an object-relational adapter: http://mail.python.org/pipermail/python-list/2002-September/122491.html Searching for sub-strings alternatives discussed: http://mail.python.org/pipermail/python-list/2002-September/122270.html How to properly call a Python COM component from C#/.Net: http://mail.python.org/pipermail/python-list/2002-September/122630.html Tim Peters follows up on potential speed issues parsing large data files: http://mail.python.org/pipermail/python-list/2002-September/121646.html Stackless Python merge into Python's core trunk possibilities explained: http://mail.python.org/pipermail/python-list/2002-September/122734.html Software pyPgSQL v.2.2 has been released. This is a bug fix release for v.2.1. PyPgSQL is a Python DB-API 2.0 compliant interface to PostgreSQL databases. http://pypgsql.sourceforge.net PyQuante 1.03 available. PyQuante is a suite of programs for writing quantum chemistry software. http://pyquante.sourceforge.net The (standalone) Python email package version 2.3 is available. It is compatible with Python 2.1.3 and Python 2.2.1. http://sf.net/projects/mimelib/ SC-Track Roundup issue tracking system, v. 0.5 beta2 announced. http://mail.python.org/pipermail/python-announce-list/2002-September/001686.html Pymqi .4 released. Pymqi is a Python extension for IBM's Messaging & Queuing middleware, MQSeries. http://www.hare.demon.co.uk/pymqi/ omniORB 4.0.0 and omniORBpy 2.0 release candidates available, with the intention to make a full release in a week or so: http://mail.python.org/pipermail/python-announce-list/2002-September/001683.html Leo (Literate Editor with Outlines) gains momentum and moves to v. 3.6: http://mail.python.org/pipermail/python-announce-list/2002-September/001684.html The first beta release of ZODB3 (3.1b1), formerly known as StandaloneZODB : http://mail.python.org/pipermail/python-announce-list/2002-September/001685.html Plone 1.0 goes Beta, and will be presented at OSCOM. http://plone.org/Members/runyaga/news/Plone-beta1.news http://plone.org/Members/runyaga/news/oscom2002 Python 2.2.1 for DOS test release http://www.delorie.com/archives/browse.cgi?p=djgpp/2002/05/19/15:30:25 ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of summarizing action on the python-dev mailing list once every other week. http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From grabiller at 3dvf.net Wed Sep 25 11:14:32 2002 From: grabiller at 3dvf.net (Guy Rabiller) Date: Wed, 25 Sep 2002 17:14:32 +0200 Subject: Newbie References Question -> Exemple References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> Message-ID: <3d91d2cf$0$1484$79c14f64@nan-newsreader-01.noos.net> Ok, thanks for your answers, I understand now that a variable name is 'just' a name in a dictionary, and not a container. What I want to do is simple, and I suppose that this is my 'way of thinking' regarding Python that is wrong. I have a list of points, and a list of polygons that should contain 'references' to points. So for me: -> points list: p = [] p.append([0,0]) p.append([0,1]) p.append([1,1]) p.append([1,0]) -> polygon: quad = [] quad.append(p[0]) quad.append(p[1]) quad.append(p[2]) quad.append(p[3]) But now, if I change the coordinate of one point: p[0] = [5,5] I will have: >>> p [[5, 5], [0, 1], [1, 1], [1, 0]] but: >>> quad [[0, 0], [0, 1], [1, 1], [1, 0]] For me the quad list of point is not 'updated' with the change of one of its point. What I want to do is that, quad keeps a list of 'references' to points coordinates. Then if I change one point coordinates, the change is reflected in the quad list of points. I have no clue how to do this. -- guy rabiller 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net Guy Rabiller wrote: > Hi, > > let say I have: > i1 = 1 > i2 = 2 > and > p = [i1,i2] > > How can I have: > p=[*i1,*i2] > rather than > p=[**i1,**i2] as it is curently ? > > ( Sorry for this nasty hybrid syntax ) > > Textualy, how if I want that p[0] refere to the 'i1' container, and > not to the refererence it contains ? > > What I want is that if now I set: > i1 = 4 > that automaticaly: > p -> [4,2] > and not keeping [1,2] > > Thanks in advance. From max at alcyone.com Sun Sep 15 05:07:26 2002 From: max at alcyone.com (Erik Max Francis) Date: Sun, 15 Sep 2002 02:07:26 -0700 Subject: html template system? References: Message-ID: <3D844DCE.3C1C3B05@alcyone.com> :B nerdy wrote: > what are good templating systems avaliable for python? In addition to the ones already mentioned, there's also empy: http://www.alcyone.com/pyos/empy/ -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ An undevout astronomer is mad. \__/ Edward Young Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From werner.merkl at fujitsu-siemens.de Fri Sep 27 09:05:27 2002 From: werner.merkl at fujitsu-siemens.de (Werner Merkl) Date: Fri, 27 Sep 2002 15:05:27 +0200 Subject: Python, unicode, Windows32 and NTFS... Message-ID: Hi, in my job I have a lot of differnt language to deal with, now including japan. And we have all these languages on our server (Windows 2000)... So NTFS uses UNICODE (I think it's 'utf-16'). Python -- at least since version 1.6 -- is supposed to understand and handle UNICODE. But my experience is, it doesn't support UNICODE for NTFS file names. eg: PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> abc = u'a:\u03b1\u03b2\u03b3.txt'; print abc a:???.txt # if you use Pythonwin you should see 'A:alpha beta gamma .txt' >>> open(abc,'w').write('test') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'a:a\xdf?.txt' >>> Oops! Does this mean, I have to use VisualBasicScript to handle this???? Or are there any swiches or tools or libs to use UNICODE filesystems? BTW: It would be fine, to use all that good stuff like walk, isdir, isfile ... Thanks in advance Regards/Mir freundlichen Gr??en Werner Merkl -- ---------------------------------------------------------------------- Werner Merkl Senior Engineer Software Pre-Installation FSC VP BP PRO PI Fujitsu Siemens Computers Buergermeister-Ulrich-Str. 100 86199 Augsburg Germany Telephone: +49(0)821 804-3548 Telefax: +49(0)821 804-3835 E-mail: mailto: werner.merkl at fujitsu-siemens.com Internet: http://www.fujitsu-siemens.com From joorce at hotmail.com Tue Sep 24 04:30:08 2002 From: joorce at hotmail.com (Jose Ortega) Date: 24 Sep 2002 01:30:08 -0700 Subject: [wxPython] ListCtrl: How can I change the column header text at runtime? References: Message-ID: <25f7fd21.0209240030.3c99d137@posting.google.com> Hi Maybe this will be useful. http://wiki.wxpython.org/index.cgi/ListAndTreeControls Bye. From dsavitsk at e-coli.net Tue Sep 17 18:10:05 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Tue, 17 Sep 2002 22:10:05 GMT Subject: Test Post References: Message-ID: <1LNh9.10302$yt3.4826468@newssrv26.news.prodigy.com> perhaps in the future people wanting to test could test w/ a real (or even fake) question of some relevance. Even a post saying "I am new to Python and I just love it." would be more appropriate. In your heart you would know it was a test, but we could all be slightly happier thinking that the knowledge disseminated per bit ratio for c.l.p was that much higher. welcome. your test worked. -d "David B. Margossian" wrote in message news:am8656$3npc1 at ncc1701.polaroid.com... > Please excuse the intrusion. Trying to establish a feed for this group... > > From sandorlevi at yahoo.com Fri Sep 13 23:12:39 2002 From: sandorlevi at yahoo.com (Levente Sandor) Date: 13 Sep 2002 20:12:39 -0700 Subject: transform list of int in a list of string?? References: Message-ID: <8b5e42a6.0209131912.3c598acb@posting.google.com> jubafre at brturbo.com wrote in message news:... > Traceback (most recent call last): > File "C:\Documents and Settings\jubafre\Desktop\montador\teste.py", line > 78, in ? > t=str(x[i]) > TypeError: 'list' object is not callable The error message says that a list object in your code is identified by 'str'. You must use a different name for your list, or the str() function will no longer be available. It's generally a good idea to avoid using built-in identifiers for your own objects. levi From ianb at colorstudy.com Wed Sep 4 12:16:49 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 4 Sep 2002 11:16:49 -0500 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 4) Message-ID: <448A0F008E0AFE11.19B9EF86BEE2B191.107D5020B234F743@lp.airnews.net> QOTW: The canonical, "Python is a great first language", elicited, "Python is a great last language!" -- Noah Spurrier "We C++ programmers have developed tricks to help us deal with this sort of thing, in much the same way that people who suffer severe childhood trauma develop psychological mechanisms to insulate themselves from those experiences :-) " - Joseph A. Knapka http://groups.google.com/groups?th=b16d1daabdacd1de "A growing number of utilities is a sign that a format is popular, not that it is good." -- Oren Tirosh Threads: A thoughtful note on one person's decision to use Python in a scientific environment: <3D60A1E2.7FD246E0 at anansispaceworks.com> A Lisp implementation of a statistical spam filter described at http://www.paulgraham.com/spam.html is converted to Python, debated, and discussed: http://groups.google.com/groups?th=163046edb9100ee8 A newbie's question about the behavior of lists and references is answered: <001601c24750$c5490d10$0effa8c0 at john> Sites and stuff: gamasutra.com has an article on using Python to script games: http://www.gamasutra.com/features/20020821/dawson_01.htm (free but intrusive registration required) New PEP Format: reStructuredText http://aspn.activestate.com/ASPN/Mail/Message/python-dev/1341652 'Seen the new Python book? http://click.unixreview.email-publisher.com/maaavMbaaTpIEa2scaRb/ Software: Psyco 0.4.1 is released. Psyco is an extension to the standard Python interpreter to perform "specialized compiling" -- giving Python some of the speed advantages of statically typed languages like C: http://psyco.sourceforge.net/ Jimmy Retzlaff posts benchmarks of standard Python, Pyrex, and Psyco which show impressive performance: http://groups.google.com/groups?th=d85d63a710c53607 XMail 1.00 is released, both a suite of applications, and a framework to extend. It is both an SMTP and POP server: http://xmail.marketmix.com/products/xqm/xqm_lib.php The Albatross web application framework reaches 1.00: http://www.object-craft.com.au/projects/albatross/ SimpleParse 2.0.0 is released. SimpleParse is a parser generator -- for parsing programming-language-like syntaxes: http://simpleparse.sourceforge.net/ Python In PHP: a Python interpreter embedded in PHP, for the linguistically indecisive (alpha code): http://www.csh.rit.edu/~jon/projects/pip/ ======================================================================== Everything you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newly-revitalized newsgroup at least weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Michael Hudson continued Andrew Kuchling's marvelous tradition of summarizing action on the python-dev mailing list once every other week, into July 2001. Any volunteers to re-start this valuable series? http://starship.python.net/crew/mwh/summaries/ http://www.amk.ca/python/dev The Vaults of Parnassus ambitiously collect Python resources http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Software Foundation has replaced the Python Consortium as an independent nexus of activity http://www.python.org/psf/ Cetus does much of the same http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Links2Go is a new semi-automated link collection; it's impressive what AI can generate http://www.links2go.com/search?search=python Tenth International Python Conference http://www.python10.org Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. [http://www.egroups.com/list/python-url-leads/ is hibernating. Just e-mail us ideas directly.] To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From phil at river-bank.demon.co.uk Fri Sep 13 04:25:22 2002 From: phil at river-bank.demon.co.uk (Phil Thompson) Date: Fri, 13 Sep 2002 09:25:22 +0100 Subject: Extending a C++ App References: <996eade8.0209120912.3a653d7@posting.google.com> <996eade8.0209122352.45721938@posting.google.com> Message-ID: <3D81A0F2.5090808@river-bank.demon.co.uk> Bwuce_Wee wrote: > Thanks for your help > > I looked at SWIG > However I have a few concerns (forgive me if Im being dense) > > (1) All the examples are created as DLLs (ie APIs) > This is fine - except how would my C++ App use the same object instances? > (ie. share the memory and API objects) > > (2) SWIG does not do a nice job of object wrapping (in my opinion) > For instance instead of saying > c = example.Circle > c.x = 10 > c.y = 20 > del c > > I need to do this: > c = example.new_Circle() > example.Shape_x_set(c,10) > example.Shape_y_set(c,20) > delete_Circle(c) > > Isn't there a cleaner library somewhere to do this? > SIP has no documentation - so I don't know what to expect of it A .sip file containing... %Module example class Circle { %HeaderCode #include "circle.h" %End public: int x, y; }; ...would generate a module where you... import example c = example.Circle() c.x = 10 c.y = 20 del c While documentation is obviously a problem, there are enough people on the PyKDE mailing list who have made the necessary blood sacrifices to be able to help. Phil From duncan-news at grisby.org Tue Sep 24 04:40:42 2002 From: duncan-news at grisby.org (Duncan Grisby) Date: Tue, 24 Sep 2002 08:40:42 GMT Subject: ANN: omniORB 4.0.0 and omniORBpy 2.0 Message-ID: I am pleased to announce the release of omniORB 4.0.0 and omniORBpy 2.0. omniORB is a robust, high performance CORBA ORB for C++. omniORBpy is a version for Python. They are freely available under the terms of the GNU Lesser General Public License (for the libraries), and GNU General Public License (for the tools). For more information, see http://omniorb.sourceforge.net/ Highlights of the new features since omniORB 3.0 and omniORBpy 1: - Updated to CORBA 2.6. - Support for GIOP 1.1 and 1.2. - Wide string and codeset negotiation. - Unix domain and SSL transports. - Bidirectional GIOP. - Flexible thread pool mode. - PortableServer::Current. - Interceptors. - Fixed point. - Complete freeing of all heap allocations. - Efficient in-process calls between C++ and Python. - Python / C++ object reference translation API. - New comprehensive configuration mechanism. - Commercial support. See http://www.omniorb-support.com/ Release notes are available from http://sourceforge.net/project/shownotes.php?release_id=112373 and http://sourceforge.net/project/shownotes.php?release_id=112375 You can download the releases themselves via the release notes pages, or from http://sourceforge.net/project/showfiles.php?group_id=51138 Enjoy! Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From drifty at bigfoot.com Mon Sep 16 00:00:11 2002 From: drifty at bigfoot.com (Brett C.) Date: 15 Sep 2002 21:00:11 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Sep 9) References: Message-ID: > Michael Hudson continues Andrew Kuchling's marvelous tradition > of summarizing action on the python-dev mailing list once every > other week. Uh, actually, I (Brett Cannon) am doing them now. Michael has decided to not come out of retirement. The last thing we would need is him blowing his fingers out dealing with the summary twice a month. =) -Brett C. From aleax at aleax.it Fri Sep 27 06:57:37 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 27 Sep 2002 10:57:37 GMT Subject: comparing all values of a list to regex References: <0lUk9.149240$ub2.3291527@news1.tin.it> Message-ID: Manuel Hendel wrote: > Sorry for forgetting some details. > > On Fri, Sep 27, 2002 at 08:07:24AM +0000, Alex Martelli wrote: >> >> def classify(login_email): >> l_e = login_email.split(',') > > I think that I nearly understand what you are doing here. But I don't > understand the assert part. I already checked at the documentations > but this doesn't helped me at all. > >> assert 1 <= len(l_e) <= 2, "More than one comma in (%s)" % >> login_email assert is just a sanity check. I want the program to bail out with a clear error message if it's ever presented with an input file that does NOT respect the specs you've given (the only ones which the program is prepared to handle), rather than keep chugging and producing meaningless, misleading results. assert is nice to use for this purpose, because when you run the program with python -O it silently goes away and you pay no performance price whatsoever for having assert there. By the same token, assert may not be the right statement in this case, because I'm validating sanity of *input*, NOT sanity of my program. Even when the program is fully valid it may still be presented with invalid input, and it needs to scream when that happens. So, you may prefer to change the assert into, e.g.: L = len(l_e) if L<1 or L>2: raise ValueError, "%s commas in (%r)" % (L-1, login_email) Alex From claird at starbase.neosoft.com Thu Sep 5 20:24:26 2002 From: claird at starbase.neosoft.com (Cameron Laird) Date: 5 Sep 2002 19:24:26 -0500 Subject: newbie problem: use socke lib to retrieve one web page: References: Message-ID: In article , Erik Price wrote: > >On Wednesday, September 4, 2002, at 11:53 PM, koko wrote: > >> I write this to retrieve one web page using socket lib. . . . >Works for me: > > >>> import socket > >>> host = 'www.uic.edu' > >>> port = 80 > >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >>> s.connect((host, port)) > >>> header = """HEAD /home/events.shtml HTTP/1.0 >... From: hh at uic.edu >... User-Agent: test/1.0 >... >... """ > >>> s.send(header) >72 > >>> data = s.recv(4096) > >>> print data >HTTP/1.1 200 OK >Date: Thu, 05 Sep 2002 15:40:00 GMT >Server: Apache/1.3.26 (Unix) PHP/4.1.2 mod_perl/1.27 mod_ssl/2.8.10 >OpenSSL/0.9.6 >Connection: close >Content-Type: text/html > > > >>> s.close() > > >I used the HEAD method instead of GET for brevity. But GET works too. . . . To criticize code that's already giving satisfaction is nearly beyond me. I'll point out, though, that the original questioner might consider this alterna- tive which has, I believe, evident advantages for long-term maintenance: from urllib import urlopen URL = "http://www.uic.edu" page = urlopen(URL).read() print page Note that urllib is one of the batteries the standard Python distribution includes. My summary: use higher-order facilities when applicable. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://starbase.neosoft.com/~claird/home.html From mal at lemburg.com Mon Sep 23 06:44:29 2002 From: mal at lemburg.com (M.-A. Lemburg) Date: Mon, 23 Sep 2002 12:44:29 +0200 Subject: ANN: eGenix.com mx BASE Extension Package 2.0.4 Message-ID: <3D8EF08D.204@lemburg.com> ________________________________________________________________________ ANNOUNCING: eGenix.com mx BASE Extension Package for Python Version 2.0.4 Open Source Python extensions providing important and useful services for Python programmers. ________________________________________________________________________ WHAT IS IT ?: The eGenix.com mx BASE Extensions for Python are a collection of professional quality software tools which enhance Python's usability in many important areas such as fast text searching, date/time processing and high speed datatypes. Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. The tools have a proven record of being portable across many Unix and Windows platforms. You can write applications which use the tools on Windows and then run them on Unix platforms without change due to the consistent platform independent interfaces. All available packages have proven their stability and usefulness in many mission critical applications and various commercial settings all around the world. ________________________________________________________________________ WHAT'S NEW ? The RPM packages were updated to install to /usr/ instead of /usr/local/ to comply with the Linux Standard Base (LSB) and to be compatible with the Python RPMs which are available from python.org. As always we are providing precompiled versions of the package for Windows and Linux as well as sources which allow you to install the package on all other supported platforms. ________________________________________________________________________ EGENIX.COM MX BASE PACKAGE OVERVIEW: mxDateTime - Generic Date/Time Types mxDateTime is an extension package that provides three new object types, DateTime, DateTimeDelta and RelativeDateTime, which let you store and handle date/time values in a much more natural way than by using ticks (seconds since 1.1.70 0:00 UTC; the encoding used by the time module). You can add, subtract and even multiply instances, pickle and copy them and convert the results to strings, COM dates, ticks and some other more esoteric values. In addition, there are several convenient constructors and formatters at hand to greatly simplify dealing with dates and times in real-world applications. In addition to providing an easy-to-use Python interface the package also exports a comfortable C API interface for other extensions to build upon. This is especially interesting for database applications which often have to deal with date/time values (the mxODBC package is one example of an extension using this interface). mxTextTools - Fast Text Processing Tools mxTextTools is an extension package for Python that provides several useful functions and types that implement high-performance text manipulation and searching algorithms in addition to a very flexible and extendable state machine, the Tagging Engine, that allows scanning and processing text based on low-level byte-code "programs" written using Python tuples. It gives you access to the speed of C without the need to do any compile and link steps every time you change the parsing description. Applications include parsing structured text, finding and extracting text (either exact or using translation tables) and recombining strings to form new text. mxStack - Fast and Memory-Efficient Stack Type mxStack is an extension package that provides a new object type called Stack. It works much like what you would expect from such a type, having .push() and .pop() methods and focusses on obtaining maximum speed at low memory costs. mxTools - Collection of Additional Builtins mxTools is an extension package that includes a collection of handy functions and objects giving additional functionality in form of new builtins to the Python programmer. The package auto-installs the new functions and objects as builtins upon first import. This means that they become instantely available to all other modules without any further action on your part. Add the line import NewBuiltins to your site.py script and they will be available to all users at your site as if they were installed in the Python interpreter itself. mxProxy - Generic Proxy Wrapper Type mxProxy is an extension package that provides a new type that is suitable to implement Bastion like features without the need to use restricted execution environments. The type's main features are secure data encapsulation (the hidden objects are not accessible from Python since they are stored in internal C structures), customizable attribute lookup methods and a cleanup protocol that helps in breaking circular references prior to object deletion. The latest version adds a very interesting new feature: weak references which help you work with circular references in a way that doesn't cause memory leakage in a Python system. Note that even though Python 2.1+ has its own weak reference implemetation, this package can be used to write applications which also work on Python 1.5.2 and 2.0. mxBeeBase - On-disk B+Tree Based Database Kit mxBeeBase is a high performance construction kit for disk based indexed databases. It offers components which you can plug together to easily build your own custom mid-sized databases (the current size limit is sizeof(long) which gives you an address range of around 2GB on 32-bit platforms). The two basic building blocks in mxBeeBase are storage and index. Storage is implemented as variable record length data storage with integrated data protection features, automatic data recovery and locking for multi process access. Indexes use a high performance optimized B+Tree implementation built on top of Thomas Niemann's Cookbook B+Tree implementation (http://epaperpress.com/). ________________________________________________________________________ WHERE CAN I GET IT ? The download archives and instructions for installing the packages can be found at: http://www.egenix.com/ ________________________________________________________________________ WHAT DOES IT COST ? The BASE package comes with a Python 2.0 style license, which means that you can use it in both commercial and non-commercial settings without fee or charge. The package comes with full source code. ________________________________________________________________________ WHERE CAN I GET SUPPORT ? Commercial quality support for these packages is available from eGenix.com Software GmbH. Please see http://www.egenix.com/files/python/eGenix-mx-Extensions.html#Support for details about the eGenix support offerings. ________________________________________________________________________ Enjoy, -- Marc-Andre Lemburg CEO eGenix.com Software GmbH ______________________________________________________________________ Company & Consulting: http://www.egenix.com/ Python Software: http://www.egenix.com/files/python/ From brian at sweetapp.com Wed Sep 4 18:05:14 2002 From: brian at sweetapp.com (Brian Quinlan) Date: Wed, 04 Sep 2002 15:05:14 -0700 Subject: str() of a tuple In-Reply-To: <20020904145034.S7096-100000@bisquick.cs.washington.edu> Message-ID: <000a01c2545f$2567ef70$df7e4e18@brianspiv1700> > > (Before I tell you, could you please tell me what this tuple contains? I > > bet that you can't figure it on in less than, say, 5, days) > > Huh? The second sentence especially does not parse. I'm trying to cleverly say that, if str() were used recursively, item boundaries would be ambiguous. Cheers, Brian From max at alcyone.com Mon Sep 23 22:37:39 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 23 Sep 2002 19:37:39 -0700 Subject: confusion about opening files References: <3d8fcda4$0$198$75868355@news.frii.net> Message-ID: <3D8FCFF3.FD52AFE5@alcyone.com> robie1373 wrote: ... > file = os.open("e:\\d12", "r") > TypeError: an integer is required > > I get this error if the mode is r, r+, a+ or whatever. I also get it > whether the file exists or not. Can someone explain what I am doing > wrong? You meant open, not os.open. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Insight -- the titillating knack for hurting! \__/ Colette Erik Max Francis' bookmarks / http://www.alcyone.com/max/links/ A highly categorized list of Web links. From jiba at tuxfamily.org Sat Sep 28 16:24:31 2002 From: jiba at tuxfamily.org (Jiba) Date: Sat, 28 Sep 2002 22:24:31 +0200 Subject: watching mutables? References: Message-ID: <3d96f25a$0$498$7a628cd7@news.club-internet.fr> Anton Vredegoor wrote: > Hello all, > > here's a function I would like to have: > > > >>>> m = [1,2] >>>> m >>>> [1,2] >>>> from watcher import watch >>>> watch(m) >>>> m.append(3) >>>> "hey, you changed variable m!, new value is [1,2,3]" > > > > Is this possible? How would this be called? > > Anton. Try EditObj (http://oomadness.tuxfamily.org/en/editobj) and look at the module editobj.eventobj. It does exactely what you need, but it is quite a hack... Jiba From ianb at colorstudy.com Tue Sep 17 02:51:17 2002 From: ianb at colorstudy.com (Ian Bicking) Date: 17 Sep 2002 01:51:17 -0500 Subject: Stackless Python, eventual merge? In-Reply-To: References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: <1032245477.2444.1465.camel@dsl-65-184-205-5.telocity.com> On Tue, 2002-09-17 at 01:03, Martin v. Loewis wrote: > Ian Bicking writes: > > > But it doesn't seem like complexity was ever the fundamental problem -- > > the complexity could have been dealt with, but I don't believe there was > > ever any indication that if it was simplified or documented that it > > would get into standard Python. > > That is not true. I have indicated this atleast once, namely when I > studied the code. For me, the complicatedness was always the problem - > complexity is fine, since this is a complex problem. Was there some indication that Stackless would be integrated if the code was cleaned up, documented, or otherwise simplified? I don't believe there was, but I may be wrong. Without such an indication, there is no reason to think that mere technical changes to Stackless will lead to it being included in standard Python. Ian From pinard at iro.umontreal.ca Sat Sep 7 19:07:38 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Sat, 07 Sep 2002 19:07:38 -0400 Subject: Larry Wall's comment on python... In-Reply-To: <200209071429.26401.shalehperry@attbi.com> ("Sean 'Shaleh' Perry"'s message of "Sat, 7 Sep 2002 14:29:26 -0700") References: <1549197.0PZNOebDTH@cartman> <200209071429.26401.shalehperry@attbi.com> Message-ID: [Sean 'Shaleh' Perry] > [yka] >> [Kow Kuroda] >> > [...] For example, vi and emacs indent by 8 characters by default >> [...] Well at vim :set ts=4 makes more fitting > actually emacs defaults to 4 space indenting [...] The Python mode writers for Emacs managed to automatically recognise the indentation in use in a file, and continue editing that file with the same. For new files, I get four spaces per level. However, for Python files indented with TABs only, Emacs cannot successfully guess if the author's intent was to expand those TAB with four or eight spaces. By default, I vaguely remember it picks eight. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Thu Sep 12 18:21:42 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Fri, 13 Sep 2002 00:21:42 +0200 Subject: [ANN] PySQLite 0.3.0 released References: Message-ID: <3d811376$1@news.mt.net.mk> >> for row in cursor: >> print "%14s, %15s, %19s, %8s, %25s" % tuple(row) >> ? >> >> Terry J. Reedy >> > You can already do it, using iter(): > for row in iter(cursor, None): > print .... you mean: for row in iter(cursor.fetchone, None): print ... -- ?????? In a world without walls and fences, do we care about Windows and Gates ? From pereira at cis.upenn.edu Fri Sep 6 20:57:29 2002 From: pereira at cis.upenn.edu (Fernando Pereira) Date: Fri, 06 Sep 2002 20:57:29 -0400 Subject: Python class ( Prolog ) ??? References: <20020905234600.11264.60328.Mailman@mail.python.org> <3D7914FD.5D713A48@anansispaceworks.com> Message-ID: On 9/6/02 7:06 PM, in article mailman.1031353570.17391.python-list at python.org, "Terry Hancock" wrote: > Can > anyone fluent in both compare what sort of applications > you might apply a prolog-python solution to? Where > would you draw the line between the two? What would > using prolog help me with? What's a good problem to > solve as a learning project? Any more book or website > recommendations for a learner? While a superficial connection between Python and Prolog is possible, I don't think that's particularly interesting. It's the kind of thing you would do if you had code in both languages that you wanted to glue together. I think that you are looking for closer connections. That's not easy, but there are some interesting examples of logic-programming ideas being married with other languages for mutual benefit. A good example are the constraint programming engines of ILOG (www.ilog.com) that mesh with OO languages like C++ and Java. A more researchy example are hybrid languages like Oz/Mozart (http://www.mozart-oz.org/) that combine logic, OO and functional features in an interesting package. Finally, there are several nice embeddings of logic or constraint programming in Lisp-family languages, starting from the tutorial examples in SICP (http://www-mitpress.mit.edu/sicp/) and including systems like Screamer (ftp://ftp.ecn.purdue.edu/qobi/ircs-93-03.ps.Z). There's a lot more along these lines, but these are just those that came to mind right away. I think that Python would be a good language to host something along those lines, but of course someone would have to do the work, and if you want reasonable efficiency as well as power you'll have to work pretty hard. -- F From loewis at informatik.hu-berlin.de Tue Sep 17 03:13:03 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 17 Sep 2002 09:13:03 +0200 Subject: file mode attributes... In-Reply-To: <60FB8BB7F0EFC7409B75EEEC13E2019201253349@admin56.narex.com> References: <60FB8BB7F0EFC7409B75EEEC13E2019201253349@admin56.narex.com> Message-ID: "Bjorn Pettersen" writes: > Thanks. Do you think there would be any interest in adding these > kinds of utility functions to e.g. the os.path module? I doubt that. Your implementation is valid only on Windows, on Unix, you need to determine whether you are interested in user, group, or other bits, and you also have not only read and write, but also execute. The current API is as portable and convenient is it can get. Also, finding out that way that a file is writable does not mean you can write to it: - the file might be on a read-only file system (will report EROFS, on Unix), - the Win32 ACL might prevent writing, - on Unix, you need to get your owner and group id, - the Unix euid/fsuid might prevent writing, as it might differ from your user id, - the file system might be full. So the only way to truly find out whether you can read is to attempt to read or write, and prepare for an exception. > win32all isn't standard on Windows ? No; that's a huge code base, and nobody has proposed to incorporate it into Python proper. Regards, Martin From aleax at aleax.it Tue Sep 17 06:05:21 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 17 Sep 2002 10:05:21 GMT Subject: faster way for adding many strings References: Message-ID: Ulli Stein wrote: > What is the faster way: appending many strings to a list and then joining > them, or writing to > StringIO and then getvalue()? Best ways to answer such questions is to try! For example, put in timit.py: import time, cStringIO, array manystrings = [str(x) for x in xrange(10000)] repeater = [None] * 100 def directly(manystrings): return ''.join(manystrings) def withappend(manystrings): alist = [] for x in manystrings: alist.append(x) return ''.join(manystrings) def withwritelines(manystrings): aux = cStringIO.StringIO() aux.writelines(manystrings) return aux.getvalue() def withwrite(manystrings): aux = cStringIO.StringIO() for x in manystrings: aux.write(x) return aux.getvalue() def witharray(manystrings): aux = array.array('c') for x in manystrings: aux += array.array('c', x) return aux.tostring() def timit(func): start = time.clock() for x in repeater: func(manystrings) stend = time.clock() return '%.2f %s' % (stend-start, func.__name__) for func in directly, withappend, withwritelines, withwrite, witharray: print timit(func) Now run it: [alex at lancelot examples]$ python -O timit.py 0.21 directly 1.43 withappend 0.26 withwritelines 1.11 withwrite 19.51 witharray [alex at lancelot examples]$ python -O timit.py 0.22 directly 1.48 withappend 0.22 withwritelines 1.15 withwrite 19.67 witharray >From this we see that, on my machine, if I have the strings to join already, joining them directly is a bit faster; but if I have to append them as they come, then cStringIO is a bit faster -- nothing much to it one way or another, but may perhaps be meaningful in a hot-spot of a program. The array solution, as coded above, is clearly out of the fray (but might be interesting if you had some estimation of total size and could size the result array directly, rather than have to use += -- I'll leave that to you). Having a way to measure means you can try directly on the platforms and python versions that matter to you. Such timing issues may often change between releases and/or platforms, after all! Alex From uwe.schmitt at procoders.net Fri Sep 27 10:46:10 2002 From: uwe.schmitt at procoders.net (Uwe Schmitt) Date: 27 Sep 2002 14:46:10 GMT Subject: __getitem__() in python2.2 Message-ID: Hi, in Python 2.1 one could define class X: def __getitem__(self, par): print par and a=X() a[1,2,3] resulted in (1,2,3) If I change to newstyle classes, __getitem__ does not accept tuples anymore. Is there a good reason for this behaviour ? Can i simmulate the v2.1 functionality ?? It was quite usefull to access multidimensional matrices... Greetings, Uwe. -- Uwe Schmitt Computer science is no more about Computers, dr.schmitt at procoders.net than astronomy is about telescopes. (Dijkstra) http://www.procoders.net From python at rcn.com Tue Sep 10 01:49:06 2002 From: python at rcn.com (Raymond Hettinger) Date: Tue, 10 Sep 2002 01:49:06 -0400 Subject: IDLE References: Message-ID: "Ali K" wrote in message news:wpbf9.264320$aA.45691 at sccrnsc02... > Why won't my IDLE work? This is the documented behavior according to the American Heritage Dictionary: idle (intr. verb): To pass time without working or while avoiding work. From aleax at aleax.it Tue Sep 24 10:26:23 2002 From: aleax at aleax.it (Alex Martelli) Date: Tue, 24 Sep 2002 14:26:23 GMT Subject: Three dumb questions (ordered by dumbness descending) References: <82Zj9.136094$ub2.2966822@news1.tin.it> Message-ID: Bernhard Herzog wrote: ... >> def shuffle_ian(x): >> newList = [(random(), i) for i in x] >> newList.sort() >> x[:] = [i[1] for i in newList] > > What's missing, though, is a proof that shuffle_ian produces each > possible permutation with the same probability (assuming random() has > suitable properties) Among the "suitable properties" would be to have random() return real numbers -- thus the probability of two equal numbers in N calls becomes 0 -- or come from a pseudo-random generator arranged in a plain/usual way so that it will never return two identical numbers until you use up its cycle (e.g. a typical linear-congruential one). > One problem I can see is that there's a non-zero chance that there will > be at least two equal random numbers in newList in which case the > corresponding values of x are used to sort newList. This skews the > probabilities and furthermore means that shuffle_ian can only shuffle > lists whose items can be ordered which among others exludes complex > numbers. Good point, of course -- an arbitrary pseudo-random (or HW random) generator returning output with a finite number of bits DOES have a non-0 chance of a duplicate, in general -- e.g., (1-2**53)**N prob of no problems if 53 bits differ significantly and you generate N+1 truly-random numbers. Alex From g0w1s0 at yahoo.ca Sun Sep 1 20:52:16 2002 From: g0w1s0 at yahoo.ca (Cesar) Date: Sun, 01 Sep 2002 20:52:16 -0400 Subject: curses: AttributeError: initscr Message-ID: I'm running python 1.5/2.2.1 under redhat linux 7.2. I'm trying to use the curses module like this : 1: import curses 2: 3: screen = curses.initscr() 4: and I get this error msg: Traceback (innermost last): File "./curses_test.py", line 6, in ? screen = curses.initscr() AttributeError: initscr any idea ?? From deblnononospammmmmyyy at theworld.com Thu Sep 19 02:19:19 2002 From: deblnononospammmmmyyy at theworld.com (David Lees) Date: Thu, 19 Sep 2002 06:19:19 GMT Subject: How to build Python 2.2.1 on Windows? References: Message-ID: <3D896C68.39591E76@theworld.com> Excellent. I just built the core and python.exe out of the box with my antique installation of VC++ Version 6. And it runs on my Win98 box. Thanks guys. David David LeBlanc wrote: > > I have built Python on Windows using both the distribution and CVS download. > The necessary VC++ project files are included in both. You will have to also > download some other components as described in the readme file, including a > special version of BSDDB version 1.85, zlib, Tcl/Tk (Tk needs Tcl to build), > expat and maybe some other things. These are for extensions, and are not > required to build the core Python. > > WRT BSDDB, there are projects out there to build Sleepycat BSDDB version 4.0 > and that's a better choice then the default version 1.85 used by Python (due > to bugs). The downside is that Sleepycat BSDDB is free for personal use > only. > > See \dist\Python-2.2.1\PCbuild for complete details. > > Oh yes, put your python source distro or cvs dump under a directory called > 'dist'. I found the directions to do that unclear in the readme and it gave > me a bit of trouble. The other packages you'll need also go in 'dist' as > peers of the python source tree. Those should be built before Python. > > David LeBlanc > Seattle, WA USA > > > -----Original Message----- > > From: python-list-admin at python.org > > [mailto:python-list-admin at python.org]On Behalf Of David Lees > > Sent: Wednesday, September 18, 2002 18:43 > > To: python-list at python.org > > Subject: How to build Python 2.2.1 on Windows? > > > > > > I have been playing with Python for awhile and would like to know how to > > try building Python on a Windows machine that has MS C++ version 6. Is > > there a standard download that is configured to do this? If not could > > someone point me in the direction of information on builds? I > > downloaded Python-2.2.1.tgz.tar on my Win98 box and WinZip 8 does not > > even seem to know how to unzip it. I just transfered the tar file over > > to a linux box and it unzips without and problem using tar. The README > > seems to only talk about linux/unix type systems. > > > > David Lees > > -- > > http://mail.python.org/mailman/listinfo/python-list From wlfraed at ix.netcom.com Sat Sep 21 14:32:16 2002 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Sat, 21 Sep 2002 11:32:16 -0700 Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <7xn0qcfafp.fsf@ruckus.brouhaha.com> <7xwupf52jx.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin fed this fish to the penguins on Friday 20 September 2002 10:34 pm: > > I do know that financial modelling software I worked on that was sold > to banks used floating point. Also, spreadsheets use floating point. > There's probably a subtle distinction between "modelling" (to me that implies something that approximates expected behavior for rapid "what if" scenarios) and accounting type applications. > But it's possible (likely even) that some bookkeeping applications use > BCD. One that I worked on actually used exact, multi-precision > rational arithmetic, but I think that's unusual. > If it is done in COBOL that's pretty much a given... Though most COBOL compilers /have/ added things like "usage is computation" -- wherein the programmer explicitly has to request a binary value rather than normal BCD. Though I must be mis-interpreting the book I have -- it implies that the default for Fujitsu Cobol v4 is "Display" (8-bit characters), and one would have to ask for "packed-decimal" in a usage clause. COMP for floating point, and BINARY for integer. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Bestiaria Home Page: http://www.beastie.dm.net/ < > Home Page: http://www.dm.net/~wulfraed/ < From plusk at radford.edu Thu Sep 19 20:45:10 2002 From: plusk at radford.edu (Paul D. Lusk) Date: 20 Sep 2002 00:45:10 GMT Subject: Cookbook - multireplace Message-ID: This is more an exercise in sub-classing a dict than a speed optimization. It may not even be a speed optimization, since I didn't time it. # Original algorithm by Xavier Defrang. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 # and modified by alane at sourceforge.net # This implementation by plusk at radford.edu import re class NotImplemented(Exception): pass class textsub(dict): __slots__ = ('pat','regex','flags') def __init__(self, *ds): self.pat = None self.regex = None self.flags = None dict.__init__(self) for d in ds: self.update( d ) def popitem(self): """popitem doesn't make sense for this class""" raise NotImplemented def setdefault(self,key,default): # print 'set default 1 %s %s' % (key, default) new = not dict(self).has_key(key) val = dict(self).get(key,default) # print 'set default 2 %s %s %s' % (key,default, val) if new: dict.__setitem__(self,key,default) self.compile() return val def update(self,newdict): dict.update(self,newdict) self.compile() def __setitem__(self,key,val): new = not dict(self).has_key(key) dict.__setitem__(self,key,val) if new: self.compile() def __delitem__(self,key): dict.__delitem__(self,key) self.compile() def compile(self): # print 'compile called' if dict(self) and len(dict(self)) > 0: tmp = "(%s)" % "|".join(map(re.escape, dict(self).keys())) if self.pat != tmp: self.pat = tmp if self.flags: self.regex = re.compile(self.pat,self.flags) else: self.regex = re.compile(self.pat) # not called from outside, but is needed by # the sub below # self.regex.sub(self,s) is regex.sub(func=self.__call__,s) def __call__(self, match): return dict(self)[match.group()] def sub(self, s): if len(dict(self)) == 0: return s return self.regex.sub(self, s) if __name__ == "__main__": text = "As you know, Bob, Larry Wall is the creator of Perl" adict = { "Larry Wall" : "Guido van Rossum", "creator" : "Benevolent Dictator for Life", "Perl" : "Python" } print 'start' xlat = textsub(adict) print 'Fred for Bob' xlat["Bob"] = "Fred" print 'set default is' xlat.setdefault('is','really is') print xlat.sub(text) print """set default Bob, xlat['Bob'] is 'Fred'""" print xlat.setdefault('Bob','Jay') print xlat.sub(text) print """del xlat['Bob'], setdefault""" del xlat['Bob'] print xlat.setdefault('Bob','Jay') print xlat.sub(text) print 'del creator' del xlat["creator"] print xlat.sub(text) print 'popitem' try: dummy1,dummy2 = xlat.popitem() except NotImplemented: print 'popitem not implemented' else: print 'oops' print 'clear' xlat.clear() print xlat.sub(text) From tjreedy at udel.edu Mon Sep 30 13:34:16 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 30 Sep 2002 17:34:16 GMT Subject: conditional expressions References: <33b491f.0209181820.17b6ea70@posting.google.com> Message-ID: "Alex Martelli" wrote in message news:oOZl9.162526$ub2.3640508 at news1.tin.it... > Terry Reedy wrote: > > If b is a non-null constant, there is no such risk. Consider > > If it's a constant, you don't need short-circuiting! If the alternative is *also* a constant, correct; indexing works fine. If it is not, the short-cicuiting of 'or' may be crucial. Example: y==0 and NAN or x/y. Reversing the test and alternatives won't work if x might be 0. (Yes, I might prefer to let x/y raise an exception. Or I might write a function fdiv(x,y). But for one time use or in the innermost loop of a calculation, the quickly written condtional might be just what I want.) > def plur(*ns): > for n in ns: > yield n > yield 's'[n!=1:] Using the conditional in a slice rather than an index to get a null alternative is a cute trick I had not thought of. Posting a concrete usage for and/or an pulled out nice alternatives from 3 or 4 different people. Let's try a couple of others: In the middle of an expression, I want the 7th or 3rd item in seq depending on (an expression yielding 0 or 1). Five alternatives (where ... ... is usage context): ...seq[ and 2 or 6]... ...seq[(6,2)[]]... ...seq[6-4*]... ...seq[2+(not)*4]... # this generalizes better -- see below if : tem = 2 else : tem = 6 ...tem... Anything else? Among these four I would probably prefer the first, but don't care if others choose elsewise. Now for a three-way split: ...seq[ and 2 or and 6 or 3]... # abbreviating if : tem = 2 elif : tem = 6 else : tem = 3 ...tem... Assuming doesn't need short-cicuiting when is true and doesn't take significantly long to calculate when not needed, we can again substitute tuple indexing (or direct index calculation), but I think it would take most people longer to correctly write any alternative below, at least the first time. Is it worth it to avoid the easy-to-write and easy-to-read-and-understand conditional expression? Not for me, I think, but others are welcome to differ. ...seq[((3,6)[],2)[]]... #or ...seq[(3,6,2,2)[2* + ]]... ...seq[2 + (not)*(1+3*)]... ...seq[2 + (not)*(4-(not)*3)]... Terry J. Reedy From shalehperry at attbi.com Thu Sep 12 01:31:20 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Wed, 11 Sep 2002 22:31:20 -0700 Subject: [FEEDBACK] Is this script efficient...is there a better way? In-Reply-To: References: Message-ID: <200209112231.20706.shalehperry@attbi.com> On Wednesday 11 September 2002 18:09, Bob X wrote: > > 2) do you expect to find more than one keyword in a particular line? If > > not you could save some iterations by stopping the inner line.find() loop > > as soon as one item is found. > > I could but it doesn't matter after the first on a line. How would I > stop it? > use 'break' for i in range(1,20): if i == 6: break print i and you get: 1 2 3 4 5 so your code becomes: for line in inFile.readlines(): for badword in kw: if line.find(badword) > -1: result = '%s %s' % (badword, line) print result # Print the result outFile.write(result) # Write the result break # only need one keyword on a line there is also the keyword 'continue' which says "I am done with this loop iteration, go back to the top of the loop". for i in range(1,20): if (i % 2) == 0: continue print i this loop will only print the odd numbers. From macdict at optushome.com.au Wed Sep 18 08:34:58 2002 From: macdict at optushome.com.au (Richard Tardif) Date: Wed, 18 Sep 2002 22:34:58 +1000 Subject: minimizing Tk programs to the taskbar Message-ID: <3D8872F1.87850856@optushome.com.au> Hello all, Is there any way to minimize programs to the taskbar? I'm talking about windows here. By taskbar I mean the area down in the bottom right corner, near the clock, that shows icons for what proggies you've got running. Thanks for any help. From a_salnikov at yahoo.com Wed Sep 25 19:26:01 2002 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Wed, 25 Sep 2002 16:26:01 -0700 Subject: a python puzzle References: Message-ID: "Gary Herron" wrote in message news:mailman.1032992492.8970.python-list at python.org... > On Wednesday 25 September 2002 02:42 pm, Michal Wallace wrote: > > Here's a python puzzle. Solve it and you win a prize. :) > > > > I decrypted (building the strings up character by character) with: > > tr hokdrawfezxmylqcubijHpvsIFgt importysngalejufzvchIwxbCSkd < puzzle > > and got: > > > The fact that this puzzle was easy to decrypt says something (good) > about Python: It is so readable, that even encrypted, one can > recognize significant portions. Imagine decrypting a similar puzzle > in C or, worse yet, Perl! > C'mon, "the fact that this puzzle was easy to decrypt says" that "encription" was really trivial. Indeed the most "important" spaces, and non-alpha characters were not encripted at all. With such simple encription you'll be able as easily decrypt C and Perl (or any English text of suffitient length) Cheers, Andy. From tjreedy at udel.edu Thu Sep 12 09:26:10 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 12 Sep 2002 13:26:10 GMT Subject: "str.contains(part)" or alternatives? References: Message-ID: "Joseph A. Knapka" wrote in message news:mailman.1031804415.15646.python-list at python.org... > Ah. So we have: > > not(X in Y <==> X in [Z for Z in Y]) > > But only if Y is a string. That strikes me as a trifle odd, > but nevertheless I agree that the "substring in string" > behavior seems more useful. As Tim said, this was debated on the dev list. In the end, Guido decided that giving 'in' slightly expanded semantics for strings and strings only, though not 'pure', seemed very natural and practical and no wierder than some other type-specific differences for other operators. While strings are sequences, they are different in that they are *not* recursive, unlike tuples and lists. A string of len>1 can be a substring of a string but it cannot be a 'member' of the string. On the other hand, [1,2,3] is both a sublist and item of [1,2,3,[1,2,3]]. So "[1,2,3] in alist" would be ambiguious unless restricted to one meaning or the other. Terry J. Reedy From maxm at mxm.dk Fri Sep 6 03:47:57 2002 From: maxm at mxm.dk (Max M) Date: Fri, 06 Sep 2002 09:47:57 +0200 Subject: Python-dev summary for 2002-08-16 - 2002-09-01 References: Message-ID: <3D785DAD.5050905@mxm.dk> Brett Cannon wrote: > This is a summary of traffic on the python-dev mailing list between August > 16, 2002 and September 1, 2002 (exclusive). It is intended to inform the > wider Python community of ongoing developments. To comment, just post to > python-list at python.org or comp.lang.python in the usual way. Great stuff!!! > ================================= > New PEP Format: reStructuredText > ================================= > It has been suggested that the summaries try using reST; I am considering > it. LOL! regards Max M From wade at lightlink.com Mon Sep 16 12:17:58 2002 From: wade at lightlink.com (Wade Leftwich) Date: 16 Sep 2002 09:17:58 -0700 Subject: [xml] convert funny chars to char entites? References: Message-ID: <5b4785ee.0209160817.64b3842f@posting.google.com> ":B nerdy" wrote in message news:... > ive got a string "Il Est N?" and i want to put it into a xml document > > is there a quick and easy way to conver the funny characters to char > entities so i can store them? > or is there existing libraries? > > cheers I've got a content syndication application that sends out XML, and some of the recipients have a surprisingly hard time coping with UTF-8. So I supply them with ASCII, after escaping everything over 7 bits to a character reference. This also guarantees proper display in Internet Explorer. >>> s = 'Il est n\x82!' >>> u = unicode(s, 'iso-8859-1') >>> L = [] >>> for char in u: val = ord(char) if val > 127: L.append('&#%s;' % val) else: L.append(char) >>> u2 = ''.join(L) >>> u2 u'Il est n‚!' >>> s2 = u2.encode('ascii') >>> s2 'Il est n‚!' -- Wade Leftwich Ithaca, NY From tjreedy at udel.edu Fri Sep 6 08:49:49 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 06 Sep 2002 12:49:49 GMT Subject: Python "compiler" is too slow for processing large data files??? References: Message-ID: > list1 = [ > (323, 870, 46, ), > (810, 336, 271, ), > (572, 55, 596, ), > (337, 256, 629, ), > (31, 702, 16, ), > ] > Anyway, as my data files went from just a few lines, up to about 8000 lines > (with 10 values in each line for total of about 450KB of text), the time to > 'exec' the file became too slow (e.g. 15 seconds) and used too much memory > (e.g. 50MB) (using ms-windows, python 2.2.1). It is the "compile" phase, > because if I re-run, and there is *.pyc file available, the import goes very > fast (no compilation required). I am curious whether any C/C++ compilers (or those for other languages) would have any problems with literal array of 10000 10-member structs? Would the following go faster? Leave off outer list lines (first and last) to make more data like. Then read file twice: once to count lines and allocate list; second to populate list. f = file('data') lenf = len(f.readlines()) data = [0]*lenf f.rewind() for i in range(lenf): data[i] = maketuple(f.readline()) # substitute code for maketuple Terry J. Reedy From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Mon Sep 23 20:53:04 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Tue, 24 Sep 2002 02:53:04 +0200 Subject: list problem References: Message-ID: <3d8fb76f@news.mt.net.mk> > i have: > x=[['0020', '0000x9'], ['0030', '0000xa'], ['00B4', '0000x8'], ['0030', '0000xb'], ['00F0'], ['0001'], ['0003'], ['0005']] > and i want: > y=['0020', '0000x9', '0030', '0000xa', '00B4', '0000x8', '0030', '0000xb','00F0', '0001', > '0003', '0005'] > how to do this? hmm, x[0] -- ?????? If Bill Gates had a dime for every time a Windows box crashed... ...Oh, wait a minute, he already does. From debl2nonospammmmyy at bellatlantic.net Wed Sep 18 21:43:04 2002 From: debl2nonospammmmyy at bellatlantic.net (David Lees) Date: Thu, 19 Sep 2002 01:43:04 GMT Subject: How to build Python 2.2.1 on Windows? Message-ID: <3D892BBD.5B38DD49@bellatlantic.net> I have been playing with Python for awhile and would like to know how to try building Python on a Windows machine that has MS C++ version 6. Is there a standard download that is configured to do this? If not could someone point me in the direction of information on builds? I downloaded Python-2.2.1.tgz.tar on my Win98 box and WinZip 8 does not even seem to know how to unzip it. I just transfered the tar file over to a linux box and it unzips without and problem using tar. The README seems to only talk about linux/unix type systems. David Lees From lutz at rmi.net Tue Sep 17 17:54:59 2002 From: lutz at rmi.net (Mark Lutz) Date: Tue, 17 Sep 2002 15:54:59 -0600 Subject: Ann: Python training, Colorado, Oct 28-30 Message-ID: <005b01c25e94$e4b47e40$88133b41@PythonToy> I will be holding another 3-day Python training session in Colorado, on October 28-30. This is a public class, open to individual enrollments. For more details about this session, please visit this page: http://www.rmi.net/~lutz/oct02-longmont-class.html General course details are maintained here: http://www.rmi.net/~lutz/mytrain.html Cheers, --Mark Lutz (http://www.rmi.net/~lutz) From gerhard.haering at opus-gmbh.net Wed Sep 18 10:19:39 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 18 Sep 2002 14:19:39 GMT Subject: BibTeX module? References: Message-ID: Matthias Huening wrote: > Hi, > > I am looking for a simple BibTeX module, allowing me to read and > manipulate/convert a bibliography file. Did you try Google? It suggests http://canvas.gnome.org:65348/pybliographer/ -- Gerhard From max at alcyone.com Wed Sep 25 23:50:37 2002 From: max at alcyone.com (Erik Max Francis) Date: Wed, 25 Sep 2002 20:50:37 -0700 Subject: a python puzzle References: Message-ID: <3D92840D.3D422522@alcyone.com> "Delaney, Timothy" wrote: > I suspect it took Holger somewhat less than half an hour to solve ... > 5 > minutes at most, and most of that is writing the decryption code ;) It only took two or three minutes for me to solve with an emacs window open and tr on an interactive shell. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ Gods are born and die, but the atom endures. \__/ Alexander Chase Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html A new, virtual planet, every day. From teaandbikkie at aol.com Wed Sep 11 20:49:06 2002 From: teaandbikkie at aol.com (TeaAndBikkie) Date: 12 Sep 2002 00:49:06 GMT Subject: file upload using msvcrt References: Message-ID: <20020911204906.00669.00000156@mb-fh.aol.com> >I am trying to upload msword docs to my webserver. I suspect the following lines... data = fileinfo.file.read( ) if not data: break This will break on the "not data" condition... ie. when data is zero, "", None So your binary file may have a zero... read() returns empty string for EOF, so this would be better: if data == "": break Kind regards... From vincent_a_primavera at netzero.net Fri Sep 27 04:53:42 2002 From: vincent_a_primavera at netzero.net (Vincent A. Primavera) Date: 27 Sep 2002 08:53:42 +0000 Subject: comp.lang.python... In-Reply-To: References: Message-ID: <1033116822.1570.3.camel@del-vap-bos.ralphpill.com> Hello, I've been subscribed to python-list at python.org for at least a couple of years I would guess. I have been using a mail client to receive all of the messages, but I figure that using a news client would be a more organized method. However, I can't seem to find what I need to enter for a server & user/password combination... Thank you, Vincent A. Primavera On Fri, 2002-09-27 at 12:28, Thomas Guettler wrote: > Vincent A. Primavera schrieb: > > Hello, > > Stupid question... What information do I need to set up > > comp.lang.python with my news client(Pan)? > > > > You need to subscribe this newsgroup and > you need a newsserver. > > But how could you post this message without it? > > thomas > > -- > http://mail.python.org/mailman/listinfo/python-list From aleax at aleax.it Fri Sep 27 02:43:05 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 27 Sep 2002 06:43:05 GMT Subject: http://www.python-in-business.org References: Message-ID: Conrad Schneiker wrote: > Chris, > > Do you have anything to do with these people? Not quite sure who you are addressing, but, anyway, I do have something to do with them -- I was elected to the PBF board. > Is there any sort of analogous North American organization? The PBF can accept member firms from anywhere in the world: it is not limited to Europe... North Americans are all right (our Treasurer is Canadian, for example). Alex From janeaustine50 at hotmail.com Thu Sep 26 04:38:39 2002 From: janeaustine50 at hotmail.com (Jane Austine) Date: 26 Sep 2002 01:38:39 -0700 Subject: Is mmap usable for IPC? Message-ID: Is mmap module usable for inter-process communication? Does it provide lock, or semaphore? Is it safe to write from a process and read from multiple other processes simultaneously? Any information appreciated. From sebastian.wangnick at eurocontrol.int Sat Sep 21 04:32:26 2002 From: sebastian.wangnick at eurocontrol.int (Sebastian Wangnick) Date: 21 Sep 2002 01:32:26 -0700 Subject: Trying the impossible? Message-ID: <30292041.0209210032.6e07d9f3@posting.google.com> Dear all, I'm trying to overload, using dynwin/calldll under Windows, the Tkinter drawing routines to perform some additional drawing on top of Tk. My first attempt was to bind to "", but this binding seemingly is triggered before Tk performs its drawing, so my stuff was erased by Tk :( Now I'm trying to overload the WindowProc itself. To test the mechanism, I started by simply passing everything on to CallWindowProc: from Tkinter import * import dynwin import dynwin.gencb import dynwin.windll import dynwin.winwin user32 = dynwin.windll.module ('user32') def my_winproc (hwnd, message, wparam, lparam): return user32.CallWindowProc (tk_winproc, hwnd, message, wparam, lparam) my_winproc_cb = dynwin.gencb.generated_callback ('llll', my_winproc) def map (event): global tk_winproc hwnd = frame.winfo_id() tk_winproc = user32.GetWindowLong (hwnd, dynwin.winwin.GWL_WNDPROC) user32.SetWindowLong (hwnd, dynwin.winwin.GWL_WNDPROC, my_winproc_cb.address) root = Tk() frame = Frame(root,width=100,height=100) frame.pack(fill=BOTH,expand=1) frame.bind("",map,"+") root.mainloop() However, when starting this it crashes with 'The instruction at "0x1e0381fa" referenced memory at "0x00000008". The memory could not be "read".' Any idea what I'm doing wrong? I'm using XP, btw. Regards, Sebastian From robin at execulink.com Sat Sep 14 21:57:06 2002 From: robin at execulink.com (robin at execulink.com) Date: Sat, 14 Sep 2002 21:57:06 -0400 Subject: threads or queue for this task References: Message-ID: Mark Hammond wrote: >threads = [] >for i in range(number_of_tasks): > thread.append(thread_for_task) ># let the threads run - just wait for shutdown >for t in threads: > t.join() > >Each thread itself contains a loop which continually look for more work >to do, or exit. Er, quite. For some reason I had not thought of simply having the worker threads look for work. I was thinking more in terms of a Queue, where the workers are fed work. But this is likely not even needed. In my case I would have them loop indefinitely. Something simple like: nap = 1 while 1: try: LookForWork() time.sleep(nap) except MyInterrupt: break except: raise Having individual threads sleeping will not adversely effect performance I imagine. Or is there some reason to avoid mixing the mechanisms? >Look for Aahz's threading tutorial - URL not at hand, but it can't be >too hard to find. Indeed, I predict he will tell you exactly where it is ;) Yes he has! But this slideshow is a little sketchy. Has someone done a more thorough tutorial covering all the different mechanisms (semaphore, events, etc.)? 'Twould be useful for a newbie like me. -- robin From sismex01 at hebmex.com Sat Sep 21 11:51:33 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Sat, 21 Sep 2002 10:51:33 -0500 Subject: if...else on the same line? Message-ID: > > i'm sorry for this terrorizingly basic question, but is it > possible at all to write an if ... else statement on a single > line in python? > > -- > dave > Depends on what you want it for. If you're trying to do the equivalent of C's a?b:c expression, then you "kinda" can, but if it's for statements, you can not. -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From abuse at nospam.riot.com.au Fri Sep 6 02:31:31 2002 From: abuse at nospam.riot.com.au (Glen Murphy) Date: Fri, 6 Sep 2002 16:31:31 +1000 Subject: about parse a link References: Message-ID: Prefix them with http://www.uic.edu/ That's what your browser does. "koko" wrote in message news:cVUd9.6962$yt3.3362358 at newssrv26.news.prodigy.com... > if I have extracted the links on the page: > e.g: > > http://www.uic.edu/index.htm > on this page: there are > a.htm > b.htm > c.htm > http://www.uic.edu/home/e.htm > > how can I log the a.htm, b.htm, c.htm with the full web address? > > thx > > From paul at boddie.net Mon Sep 16 04:50:29 2002 From: paul at boddie.net (Paul Boddie) Date: 16 Sep 2002 01:50:29 -0700 Subject: AspectP? References: <7cl9oucm65a4qr2tolm74gltqn7morbbm5@4ax.com> Message-ID: <23891c90.0209160050.7ba0e11@posting.google.com> Lothar Scholz wrote in message news:<7cl9oucm65a4qr2tolm74gltqn7morbbm5 at 4ax.com>... > [Aspect Oriented Programming for Python] > I think from this posting he has no problems in finding instable > implementations. What about the Zope acquisition stuff, or does that not go far enough? Paul From frithiof.jensen at removethis.ted.ericsson.dk Tue Sep 17 05:06:44 2002 From: frithiof.jensen at removethis.ted.ericsson.dk (Frithiof Andreas Jensen) Date: Tue, 17 Sep 2002 11:06:44 +0200 Subject: More on Protecting Source Code References: Message-ID: "David LeBlanc" wrote in message news:mailman.1032232999.22661.python-list at python.org... > * Why invest a substantial amount of time and money developing in a language > that makes it trivial to gain access to the work product? > Why indeed - why do you bother? Why is existing Copyright law not sufficient for you? > beyond those that > are fairly closely licensed and/or have substantial parts of the app written > in C/C++. Do that then - there is nothing intrinsic in the Python licensing that restricts what you can do with it; I seem to recall that you can pretty much do whatever you bloody like, including wrapping Python in your own product and selling it! > A better solution is to make a .pyc file approximately as hard as a binary > .exe file to decompile - however that could be done. And according to the generous license awarded to you by the very people whoms work you are critisizing, *you* can indeed do that; you are in fact *encouraged* to make you own enhancements to Python and release them. Simple Darwinism will show whether others feels the same way. One could, in theory, package the application with a custom build of the Python interpreter so that each interpreter uses it's own unique set of bytecodes. Performance will likely suck and you will have a real issue with upgrades, extension modules and maintenance of the many unique applications shipped - but again this is your choice to make. Personally, I do not care - I like Python exactly the way it is, including the "openess", since that is an essential part of simplifying the development task. If I was really, really worried about some "IP-leakage" I would stick the core algorithm in an extension library - that would not stop someone from just ripping the software though. From mwh at python.net Thu Sep 26 13:35:39 2002 From: mwh at python.net (Michael Hudson) Date: Thu, 26 Sep 2002 17:35:39 GMT Subject: Is there a portable way to copy files in Python? References: <3D80A78B.5030206@impathnetworks.com> Message-ID: Duncan Booth writes: > Pierre Rouleau wrote in > news:3D80A78B.5030206 at impathnetworks.com: > > > I could write code that identifies the operating system (the os.path > > way) and use os.system("cp " + source_filename + " " + destination) for > > Unix-type and os.system("copy " + source_filename + " " + destination) > > but i would prefer to use a simple call. > > > > Is this available in the Python library? If not, why is it not part of > > the library? > > Try the shutil module. Or distutils.file_copy. I don't like shutil much; somewhere on my todo list is doing something about that... Cheers, M. -- > I'm a little confused. That's because you're Australian! So all the blood flows to your head, away from the organ most normal guys think with. -- Mark Hammond & Tim Peters, comp.lang.python From peter at engcorp.com Thu Sep 19 07:40:23 2002 From: peter at engcorp.com (Peter Hansen) Date: Thu, 19 Sep 2002 07:40:23 -0400 Subject: where is the __dict__ ? References: Message-ID: <3d89b79b$1@news.sentex.net> black wrote: > my book said all dictionaries have __dict__ method but couldnt find it by using dir(), where is it ? I think I already saw a response to this posting, but it just showed up in c.l.p on my system... Your book is probably wrong, since dictionaries don't have a __dict__ method. In 2.2 their *classes* do, although dir() still doesn't show it. Perhaps you misread it. What exactly did it say? Any more importantly, what goal do you have in mind. Sometimes there are alternatives that aren't the first thing that comes to mind. -Peter From martin at v.loewis.de Tue Sep 3 16:16:54 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 03 Sep 2002 22:16:54 +0200 Subject: PyListObject & C Modules References: Message-ID: jggramlich at yahoo.com (Joshua Gramlich) writes: > I am trying to find examples of this type of activity. I've found the > documentation at www.python.org (the C api), but I'm a bit green (new) > and cannot read the List Objects page with any, well, usefulness. Here is a function that gets a list as an argument, and returns a list that has the same first element: PyObject* get_first_elem(PyObject *unused, PyObject *args) { PyObject *list; PyObject *first; PyObject *result; if(!PyArg_ParseTuple("O", &list)) return NULL; if(!PyList_Check(list)) { PyErr_SetString(PyExc_TypeError, "get_first_elem expects a list"); return NULL; } if(PyList_Size(list) == 0){ PyErr_SetString(PyExc_ValueError, "empty lists not allowed"); return NULL; } first = PyList_GetItem(list, 0); result = PyList_New(1); if (!result) return NULL; PyList_SetItem(result, 0, first); return result; } The Python equivalent of this is def get_first_elem(_list): if type(_list) != list: raise TypeError, "expects a list" if len(_list) == 0: raise ValueError, "must not be empty" first = _list[0] return [first] HTH, Martin From alessandro.riolo at sen.it Thu Sep 26 09:15:36 2002 From: alessandro.riolo at sen.it (Alessandro Riolo) Date: Thu, 26 Sep 2002 15:15:36 +0200 Subject: Decimal arithmetic, was Re: Python GUI app to impress the boss? References: <7xwupf52jx.fsf@ruckus.brouhaha.com> Message-ID: Alex Martelli wrote: > The two ways of computing interest use the acronyms TAEG > and _TAEV_ in Italy -- I'm not sure what they refer to, exactly: They are TAEG ("Tasso annuo effettivo globale") and TAN ("Tasso annuo nominale"); I never heard of TAEV. The TAN is ever lower than the TAEG, 'cause the TAN is just the yearly nominal interest rate, it is useful only to compare it with the national infation rate or similar general purpose index, while the TAEG is a rate calculated following a specific law, and in TAEG are comprised also the effective costs (all of the most hidden ones as commissions and insurances), and it is the rate we have to use to compare different loans. When there is a large discrepance betweeen TAN and TAEG, I would not entrust that so much, and even when the TAN is higher than the TAEG I would be really worried (it would mean the bank is paying money to me to open a loan ..). p.s.: Alex, I'm really having funny time with Python ;-) -- ale www.sen.it From pyth at devel.trillke.net Mon Sep 30 17:45:54 2002 From: pyth at devel.trillke.net (holger krekel) Date: Mon, 30 Sep 2002 23:45:54 +0200 Subject: Question about __getattribute__/__getattr__ In-Reply-To: ; from jpm@papercut.org on Mon, Sep 30, 2002 at 04:32:22PM -0400 References: <20020930215327.X30315@prim.han.de> Message-ID: <20020930234554.Y30315@prim.han.de> Joao Prado Maia wrote: > On Mon, 30 Sep 2002, holger krekel wrote: > > > Probably you are interested in the Memoize recipe at > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 > > > > That looks interesting, and it is indeed similar to what I'm trying to > acomplish, but on my case I want to keep each specific return value in a > separate cache file. > > The first Memoize class keeps every cached item in a dictionary, which it > may be fine for some applications, but I need it for a network server that > may be running for several days. It's not the best thing to keep > everything in memory ;) > > The second class keeps everything on the same pickled file (please let me > know if I'm wrong), which will be very slow after a couple hundred megs of > data in there. > > Anyway, I'm still going back to my original question: how do I get the > full list of arguments passed to a function ? This can't be that hard :) The important lines from the above link are: def __call__(self, *args): if not self.memo.has_key(args): self.memo[args] = self.fn(*args) return self.memo[args] and 'args' is a tuple of arguments. 'args[0]' would give you the first argument, for example. HTH, holger From hancock at anansispaceworks.com Sun Sep 8 13:27:28 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 08 Sep 2002 10:27:28 -0700 Subject: horizontal scrolling (was Re: Larry Wall's comment on python...) References: <20020908044502.16742.69743.Mailman@mail.python.org> Message-ID: <3D7B8880.A089BC76@anansispaceworks.com> Hi all, I wanted to point out a good reason why Python often led me to overly-wide source files before I learned more about it. I suspect this is one thing that trips up a lot of newbies: In C or Perl (any non-whitespace significant language), you can easily code long if conditions (or other expressions), like this: if ( condition_one_which_has_a_nice_long_expression || ((condition_two_which_also_is_pretty_long) && (condition_three_wich_needs_two_to_apply)) || condition_four_also_pretty_darn_long) { /* Do what I need to do in this oddball case */ } But the Python intro books usually don't put much emphasis on how to do this, so you wind up thinking you have to write: if condition_one_which_has_a_nice_long_expression or (condition_two_which_also_is_pretty_long and condition_three_wich_needs_two_to_apply) or condition_four_also_pretty_darn_long: # Do what I need to do in this oddball case pass which is indeed pretty obnoxious. The newbie has been taught that you don't need () on the if-clause (they may think they will cause a syntax error -- which they *do* in csh/tcsh, which they may have previous experience in, BTW). So they take a long time before they get around to trying: if ( condition_one_which_has_a_nice_long_expression or ( condition_two_which_also_is_pretty_long and condition_three_wich_needs_two_to_apply) or condition_four_also_pretty_darn_long ): # Do what I need to do in this oddball case pass which is a fairly simple trick that results from the Python rules for parsing expressions, but isn't usually mentioned when introducing the 'if' statement. Maybe it ought to be obvious, but some of us don't make the connection right away. ;-D BTW, I think the wording used at one point was more like Python will continue any expression it knows to be unfinished, rather than that is contained in delimiters. This led me to wonder why I can't just type: if condition_one_which_has_a_nice_long_expression or ( condition_two_which_also_is_pretty_long and condition_three_wich_needs_two_to_apply) or condition_four_also_pretty_darn_long: # Do what I need to do in this oddball case pass which would seem to be unambiguous, but which causes a traceback on the first line. It seems to me that the dangling operator is enough of a clue that more expression is to follow. (I think there was a thread about this a month or two ago, so I won't pursue it -- at least until after I've reviewed it ;-D). Anyway, I actually had a Perl instructor make a big deal about being able to spread an if statement over several lines like this in Perl, as if it were a big win over Python. I didn't have the heart to tell him that it could be done exactly the same way in Python. From: Peter Hansen > My point is that indentation (the way I've done it anyway) looks > *exactly* the same in C, Pascal, Python, or any other block-structured > language, so I still have no idea why Python would feel any different > in this respect for someone. > > Clearly I'm missing some point, but I still don't know what it is. > [... examples ...] > > The only thing that would make me exceed 80 columns with a language > like this is if I couldn't define subroutines and call them, to > keep the nesting from growing too large. Since all these languages > allow that, I have no idea what is special about Python that leads > to excessive indentation. You can avoid this problem by always using a function call to evaluate the expression, but IMHO it often is bad style (fails the "explicit is better than implicit" test). This probably depends on the application domain, I suspect -- in some types of projects, the expression will almost always have some kind of logical meaning in itself, in which case a function makes sense -- but in other places, it's just a lump of conditions with only one obvious place to use it. You could define a function for one use, but it just requires more typing without really making anything clearer, IMHO. BTW -- I always used to write for 132-columns because that's what my printer printed (way back when). Nowadays, I hardly ever use a terminal or printer that is narrower than this. I find wide formatted code easier to comprehend (on the whole I don't like splitting expressions over multiple lines if I can help it, even though it's sometimes necessary, as I was trying to point out here). I suppose this is probably some kind of open-source sin. Oh well. Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From scherrey at proteus-tech.com Mon Sep 16 23:12:56 2002 From: scherrey at proteus-tech.com (Benjamin Scherrey) Date: Mon, 16 Sep 2002 23:12:56 -0400 Subject: Point of Sale Software in python Message-ID: I'm looking to develop some point of sale software (initially for restaurants) that integrates with POS hardware that's out there and was wondering if there might be something already developed along these lines. My hope is for a Postgres database backend. Appreciate any pointers... Ben Scherrey From rjones at ekit-inc.com Sat Sep 14 10:00:56 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sun, 15 Sep 2002 00:00:56 +1000 Subject: html template system? In-Reply-To: References: Message-ID: <200209150000.56803.rjones@ekit-inc.com> On Sat, 14 Sep 2002 9:24 am, :B nerdy wrote: > what are good templating systems avaliable for python? > > ive been at http://zebra.sourceforge.org and the documentation is kinda > sus. zope DocumentTemplate is included with zope. but i want a smaller > footprint system. > > what are my options? cheers I've had good results integrating Zope's PageTemplates with Roundup: http://www.zope.org/Members/4am/ZPT http://roundup.sf.net/ A remarkalbly well-designed templating system... Richard From andrew.thompson at ashecastle.com Mon Sep 23 13:22:29 2002 From: andrew.thompson at ashecastle.com (Andrew Thompson) Date: Mon, 23 Sep 2002 18:22:29 +0100 Subject: parsing tabs in a string In-Reply-To: <006201c26324$4148ae90$025e10ac@calibredd.com> Message-ID: <012001c26325$cc10fb80$4802a8c0@blair> Andrew, You might find it easier to split up the line first into a collection of fields using the tab-delimiter, and then just access the collection As an array : ' import string aString='abc \t def \t xyz \t' anArray = string.split ( aString , '\t') anArray[0] now equals 'abc ' Andrew -----Original Message----- From: python-list-admin at python.org [mailto:python-list-admin at python.org] On Behalf Of Andrew Alzner Sent: 23 September 2002 18:11 To: python-list at python.org Subject: parsing tabs in a string Hello, I'm getting to know Python and have a quick question for something I don't understand. I'm trying to parse information extracted from a spreadsheet which is tab separated. Here is a simplified version of what I have: list=['"103-01a-17"\t2\t33\t256\t227\n'] y=list[0] print y.find("\t") print y.find("\t",1) I thought the second .find should return the second occurence of "\t". To get the index of the second tab I have to type: print y.find("\t",13) This doesn't make sense to me. Can someone help me please. Thanks, Andrew -------------- next part -------------- An HTML attachment was scrubbed... URL: From op73418 at mail.telepac.pt Wed Sep 18 17:24:16 2002 From: op73418 at mail.telepac.pt (Gonçalo Rodrigues) Date: Wed, 18 Sep 2002 22:24:16 +0100 Subject: multiple index inconsistency References: Message-ID: <4arhouona0ts9l2pur0p2scrar4h7ohnq6@4ax.com> There is no bug here. On Wed, 18 Sep 2002 13:59:58 -0700, bert wrote: >The following line of code >>>> a = 3*[range(3)] >produces >[[0, 1, 2], [0, 1, 2], [0, 1, 2]] What this does is create a list, named a, where each element references *the same* list range(3) - That is the semantics of the * operator, it only makes shallow copies. > >If I then write, say, >>>> a[0][1] = 3.7 >I get >[[0, 3.7, 2], [0, 3.7, 2], [0, 3.7, 2]] >and not >[[0, 3.7, 2], [0, 1, 2], [0, 1, 2]] So when you change one of them, since they are all aliases to the same list, you in fact are changing all the elements. > >Now if I write >>>> a = [[0, 1, 2], [0, 1, 2], [0, 1, 2]] Here no copies involved, since the list is built out of literals. They are all different objects (different id's) - albeit equal. >instead, and then >>>> a[0][1] = 3.7 >I get the result I expected (and wanted): >[[0, 3.7, 2], [0, 1, 2], [0, 1, 2]] So changing only one element changes... well, only one element. >Why the inconsistency? Is this a bug or am I missing something? There is no inconsistency. You just have to watch out that for mutable objects (such as lists) this is the semantics - You will get the hang of it. All the best, Gon?alo Rodrigues P.S: BTW, I think there is a FAQ entry on this. You should read it. From gherron at islandtraining.com Wed Sep 25 18:20:19 2002 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 25 Sep 2002 15:20:19 -0700 Subject: a python puzzle In-Reply-To: References: Message-ID: <200209251520.19397.gherron@islandtraining.com> On Wednesday 25 September 2002 02:42 pm, Michal Wallace wrote: > Here's a python puzzle. Solve it and you win a prize. :) > > > > """ > Ha'f ahoy ad ayfa wdqr srxhekdpyr! H phmm zhby > fhv odeajf dc cryy pys jdfahez ad ajy chrfa kyrfde > ad fdmby ajhf irwkadzrxo. Ixe wdq chzqry ha dqa? > > Fheiy wdq jxby axgye ow ijxmmyezy xet tyirwkayt > ajy fyirya oyffxzy, H phmm ybye zhby wdq ajy > irwkadzrxo-oxghez fdqriy idty ad xoxuy wdqr > crhyetf! > """ > hokdra fwf, farhez, rxetdo > ihkjyr = mhfa(farhez.myaayrf[:26]) > rxetdo.fjqccmy(ihkjyr) > ihkjyr = "".ldhe(ihkjyr) > ihkjyr += ihkjyr.qkkyr() > oxk = {} > cdr kmxhe, irwka he uhk(farhez.myaayrf, ihkjyr): > oxk[kmxhe] = irwka > cdr mhey he dkye(fwf.xrzb[1]): > krhea "".ldhe([oxk.zya(ij,ij) cdr ij he mhey])[:-1] > I decrypted (building the strings up character by character) with: tr hokdrawfezxmylqcubijHpvsIFgt importysngalejufzvchIwxbCSkd < puzzle and got: """ It's time to test your brainpower! I will give six months of free web hosting to the first person to solve this cryptogram. Can you figure it out? Since you have taken my challenge and decrypted the secret message, I will even give you the cryptogram-making source code to amaze your friends! """ import sys, string, random cipher = list(string.letters[:26]) random.shuffle(cipher) cipher = "".join(cipher) cipher += cipher.upper() map = {} for plain, crypt in zip(string.letters, cipher): map[plain] = crypt for line in open(sys.argv[1]): print "".join([map.get(ch,ch) for ch in line])[:-1] The fact that this puzzle was easy to decrypt says something (good) about Python: It is so readable, that even encrypted, one can recognize significant portions. Imagine decrypting a similar puzzle in C or, worse yet, Perl! Dr. Gary Herron From marklists at mceahern.com Wed Sep 4 10:15:13 2002 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 4 Sep 2002 09:15:13 -0500 Subject: efficient list merging In-Reply-To: Message-ID: > Here's an example: > > lol1 = [['a'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', 'j']] > lol2 = [['d', 'e', 'f'], ['k', 'l', 'm'], ['d'], ['f', 'g'], ['a']] > > I want a function which returns > > mergelol = [['a'], ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i', > 'j'], ['k', 'l', 'm'], ['d']] why isn't ['f', 'g'] in mergelol? // m - From aahz at pythoncraft.com Mon Sep 2 16:58:13 2002 From: aahz at pythoncraft.com (Aahz) Date: 2 Sep 2002 16:58:13 -0400 Subject: Threads References: Message-ID: In article , Shashank Date wrote: > >I am trying to write a simple threading app in Python 2.2 (on Windows) which >will spawn mutiple threads. >Each thread will go out on the web (various web sites) and fetch certain >documents. The main thread will wait for all the threads to terminate OR >some external event (like deletion of a file). If the external event fires >before termination of child-threads it kills all the spawned threads and >terminates. > >Any ideas how to go about doing this. See my web page. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From akineko at pacbell.net Sun Sep 8 16:27:49 2002 From: akineko at pacbell.net (Aki Niimura) Date: 8 Sep 2002 13:27:49 -0700 Subject: Creating a Text widget in a Dialog (Tkinter) Message-ID: Hi, I'm trying to create a simple dialog which has a Text with scrollbars(H and V) in a dialog. (I'm inherting Tkinter Dialog class) I'm using a grid to attach two scrollbars to the Text widget. I don't know why but the text widget is disappeared (not mapped) while two scrollbars are displayed correctly. If I use pack instead of grid then all of them appear (but Horizontal scrollbar are not placed correctly). I used the same code in the main window and it worked fine. Is there anything I'm overlooking? Any insights are highly appreciated. Thanks, Aki- ### ### Class HelpDlg ### class HelpDlg(Dialog): def __init__(self, parent, excerpt, title = None): self.lines = excerpt Dialog.__init__(self, parent, title) def body(self, master): self.usage = Text(master, height=26, width=80) self.grid = Frame(master) self.yscroll = Scrollbar(master, command=self.usage.yview) self.xscroll = Scrollbar(master, orient=HORIZONTAL, command=self.usage.xview) self.usage.configure(xscrollcommand=self.xscroll.set, yscrollcommand=self.yscroll.set) for line in self.lines: self.usage.insert(END, line+'\n') self.grid.pack(expand=YES, fill=BOTH) self.usage.grid(in_=self.grid, row=0, column=0) self.yscroll.grid(in_=self.grid, row=0, column=1, sticky='news') self.xscroll.grid(in_=self.grid, row=1, column=0, sticky='news') From bh at intevation.de Wed Sep 4 09:46:25 2002 From: bh at intevation.de (Bernhard Herzog) Date: 04 Sep 2002 15:46:25 +0200 Subject: default tuple unpacking? References: <3d758180$1@news.sentex.net> <3d7584d2$1@news.sentex.net> Message-ID: <6qd6rtdg0e.fsf@thetis.intevation.de> Peter Hansen writes: > Hmm... I think there might be an inconsistency or an unexpected > result in this. What if e already contains a tuple? > > e = (1, 2, 3) > *a = e # a is ((1, 2, 3), ) > > That seems sensible, and it's just what happens if you pass > "e" in to a function defined as "def func(*a)". No it isn't. If you call func as func(e) the tuple being unpacked into the function's parameters is (e,) not e. So the situation is more like calling func as func(*e) so that *a = e would be the same as a = e or perhaps a = tuple(e) > Now what about this: > > a, *b = e # a is 1, b is (2, 3) > > That's one possible result, and presumably the one you want with > this syntax, but it's not what you'd get with the function syntax: > > def func(a, *b): > print a > print b > > func(e) Again the tuple being upacked to a, *b is (e,)... > Here of course you get (1, 2, 3) in "a" and () in b. ... so this is obviously what you should get. Bernhard -- Intevation GmbH http://intevation.de/ Sketch http://sketch.sourceforge.net/ MapIt! http://www.mapit.de/ From cmkleffner at gmx.de Thu Sep 5 03:14:25 2002 From: cmkleffner at gmx.de (cmkl) Date: 5 Sep 2002 00:14:25 -0700 Subject: make informixdb1.3 References: <3D71300E.8010403@sschwarzer.net> Message-ID: <3b091a1c.0209042314.3b99bb80@posting.google.com> "Farhad" wrote in message news:... > Hi Stefan, > > thank you for your response. I start "make" in correct directory. The point > is, there is no "_informixdb.c" file in downloaded files (from python.org). > I suppose the make file should generate one but in my case it couldn't. > > Farhad > Hi there, there should be _informixdb.ec which has to be prepprocessed by esql - a tool supplied with the informix sdk on your machine. Locate esql and your informix libraries. run: esql -e -G -thread -libs _informixdb.ec to get a list of the libraries and potientially object files which has to be linked to your _informixdb module. Be aware, that on some systems the informix sdk is supplied as 32 bit and/or 64 bit version. Instead of using the Makefile I compiled informixdb manually (I didn't patched the makefile). I use a patch to _informixdb.ec to get rid of the most common pitfalls (DATE problem, ignore warnings instead treat them as errors). Send me a private email in the case of interest. cmkl From niemeyer at conectiva.com Thu Sep 12 12:59:27 2002 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Thu, 12 Sep 2002 13:59:27 -0300 Subject: ANN: NINZ 1.2.1 Message-ID: <20020912135926.A7584@ibook.distro.conectiva> NINZ stands for NINZ Is Not ZSI. This name was used to leave it clear that NINZ is a fork from ZSI. I have done this because I wanted a few features in ZSI which were not available at the moment, and at the same time, I don't wanted to distribute a hacked version of ZSI, since I could cause harm to Rich Salz's work on ZSI. My plans are to keep in sync with ZSI, always submitting what I change back to Rich, so he can keep his great work, and use in ZSI any code he likes. I don't want to takeover any credits of his work, and that's why I leave it clear here that my changes are insignificant compared to the comprehensive work he has done on ZSI. Indeed, my expectatives is that most of these features will be included in ZSI itself someday, and NINZ will die. More information about NINZ, including a comprehensive "NINZ vs. ZSI" session at: http://moin.conectiva.com.br/NINZ More information about ZSI at: http://pywebsvcs.sourceforge.net -- Gustavo Niemeyer [ 2AAC 7928 0FBF 0299 5EB5 60E2 2253 B29A 6664 3A0C ] From danb_83 at yahoo.com Wed Sep 25 16:15:20 2002 From: danb_83 at yahoo.com (Dan Bishop) Date: 25 Sep 2002 13:15:20 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <3D8B1537.4010803@thinkware.se> Message-ID: "Stuart D. Gathman" wrote in message news:... >... > There ought to be severe penalties for idiots that use floating point > dollars for financial applications. If forced to use floating point > (e.g. because customer demands BASIC), then keep money amounts in > whole pennies (or whatever the smallest currency unit for the country > is), and divide by 100 (or whatever) for printing only (or just add the > decimal point yourself). That's exactly how things were done at my old workplace, except that cents were also used for user input. Most of the time. From margosd at polaroid.com Tue Sep 17 17:17:23 2002 From: margosd at polaroid.com (David B. Margossian) Date: Tue, 17 Sep 2002 17:17:23 -0400 Subject: Test Post Message-ID: Please excuse the intrusion. Trying to establish a feed for this group... From mbonig at hotmail.com Sun Sep 22 03:45:03 2002 From: mbonig at hotmail.com (Matthew Bonig) Date: Sun, 22 Sep 2002 07:45:03 GMT Subject: Jython file manipulation?! Message-ID: <2yej9.32454$gA4.4053@sccrnsc02> I am trying to rename a file in Jython... the command I am using is just os.rename(filename, newFilename) I also tried doing in in java with f = File(filename) f.renameTo(File(newFilename) but that didn't work either! Any ideas? thanks matthew From joconnor at cybermesa.com Wed Sep 4 11:11:56 2002 From: joconnor at cybermesa.com (Fearless Freep) Date: 4 Sep 2002 08:11:56 -0700 Subject: Why Python? References: Message-ID: <7d3dc526.0209040711.6b10d5aa@posting.google.com> "RPM1" wrote in message news:... > If you really want to get a feel for a language, read a fairly large > program that somebody else has written in that language, (not > just little snippets). Amen to that. I now hate TCL for that very reason Take care, Jay From skip at pobox.com Tue Sep 3 17:18:22 2002 From: skip at pobox.com (Skip Montanaro) Date: Tue, 3 Sep 2002 16:18:22 -0500 Subject: Distributed Shared Memory In-Reply-To: <20020903203102.88032.qmail@web11401.mail.yahoo.com> References: <20020903203102.88032.qmail@web11401.mail.yahoo.com> Message-ID: <15733.10014.586464.763881@12-248-11-90.client.attbi.com> Carlos> I need a Python bind for some lib that supports Carlos> "Distributed Shared Memory". Is there? There is PyBrenda, which supports Gelerntner's tuple space concept (aka Linda). It only runs on Unix systems and there are some serious restrictions (shared network drive, etc). Google for "PyBrenda". You might find some similar packages by searching the Vaults of Parnassus for "PyBrenda" and browsing the category in which it resides. -- Skip Montanaro skip at pobox.com consulting: http://manatee.mojam.com/~skip/resume.html From thomas at xs4all.net Thu Sep 12 08:57:22 2002 From: thomas at xs4all.net (Thomas Wouters) Date: Thu, 12 Sep 2002 14:57:22 +0200 Subject: Fatal Python error: PyThreadState_Get: no current thread In-Reply-To: References: Message-ID: <20020912125722.GB797@xs4all.nl> On Thu, Sep 12, 2002 at 09:45:39PM +0930, Ben Gerblich wrote: > My code has just started crashing. I get the message: > Fatal Python error: PyThreadState_Get: no current thread > Aborted (core dumped) > Is there a way to turn on debug mode or something that will allow me to see > where/why my app is crashing. "python2 -d main.py" does not shed any light. This is an internal Python error, not one related to your program (other than that it seems to want threads, directly or indirectly.) If memory serves, the problem is that Python is compiled without threads, but one or more of the extention modules you're using were compiled _with_ threads. (Or, possibly, the other way 'round, but I don't think so.) Testing to see if python is compiled with threads is fairly easy: run 'python2' and type 'import thread'. Perhaps you need to get threaded (or non-threaded) versions of some of your RPMs ? *cough*debian*cough*-ly y'rs, :) -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! From paul at boddie.net Tue Sep 10 04:10:11 2002 From: paul at boddie.net (Paul Boddie) Date: 10 Sep 2002 01:10:11 -0700 Subject: Larry Wall's comment on python... References: Message-ID: <23891c90.0209100010.2c08c949@posting.google.com> brueckd at tbye.com wrote in message news:... > ["I need braces" complainants] > But just because people consistently complain about something does not > mean the answer is to bow to their wishes. Especially if the adamant complainants in question are the usual screaming 14 year old Slashdot "contributors" who think they know it all after "hanging out" on IRC for a bit. Paul From michela_rossi66 at hotmail.com Mon Sep 23 12:15:49 2002 From: michela_rossi66 at hotmail.com (michela rossi) Date: 23 Sep 2002 09:15:49 -0700 Subject: UK ZOPE Contract. Message-ID: <1ed550fd.0209230815.2ec6304a@posting.google.com> Hi, We have a ZOPE contract up and coming soon. Around two months work. If there are any ZOPE contractors available, please get in contact with me. Regards, Michela. From sholden at holdenweb.com Mon Sep 16 08:03:52 2002 From: sholden at holdenweb.com (Steve Holden) Date: Mon, 16 Sep 2002 08:03:52 -0400 Subject: IDLE References: <3D7D4F84.318CDB0F@bellatlantic.net> Message-ID: "Thorsten Kampe" wrote in ... > * syver-en at online.no > >"Ali K" writes: > >> Hardware: 386 enhanced, 75MHz, 32MB RAM. > >> OS: Win98 > >> Copied files from other computer to mine. > >> It doesn't open when I click on ide.pyw or when I choose to edit a py > >> file > >> > >> with it. > > > > I suggest you install the python distro from www.python.org. > > You think this will work on medieval computers? > Depends what you mean by mediaeval. The latest release should work fine on anything that runs Windows 95 or a more recent Microsoft OS, and pretty much any old Unix implementation you care to choose. Otherwise, installer are still available for version back to 1.5.2, I seem to remember. Someone even recently revived the DOS implementation, though I'm not sure I'd recommend that unless absolutely necessary. You certainly shouldn't expect your Windows system to understand what a .pyw file is supposed to do without being told (in some installation process, or manually). ".pyw" files should run pythonw.exe (no console), ".py" files should run python.exe. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From bosahvremove at netscape.net Fri Sep 6 03:19:49 2002 From: bosahvremove at netscape.net (Bo) Date: Fri, 06 Sep 2002 07:19:49 GMT Subject: Zope Status? Message-ID: I apologise if this isn't the proper forum to do this in. 1) Can anyone tell me roughly if\when Zope is moving to python 2.2? 2) Also any idea when they might release Zope 3? 3) Anyone close to the Zope team who is willing to shed some light on the near future for things Zope? Great thanks in advance. Bo From tim.one at comcast.net Wed Sep 11 20:20:43 2002 From: tim.one at comcast.net (Tim Peters) Date: Wed, 11 Sep 2002 20:20:43 -0400 Subject: SpamBayes PIK file? In-Reply-To: <7KQf9.1760$Lg2.232748@news2.news.adelphia.net> Message-ID: [Robert Oschler] > I want to look at the SpamBayes project so I downloaded the zip file from > source forge. Inside there's just a PIK file. How do I read a PIK file? It's a binary pickle of a trained instance of class GrahamBayes in the code base. If what to do next isn't instantly obvious, you should return the .pik file for a full refund -- unless you're a developer on this project, you don't stand much chance of getting any good out of it. For more read the associated mailing list: http://mail.python.org/mailman-21/listinfo/spambayes Nothing in this project is end-user usable yet. From jhorneman at pobox.com Sun Sep 29 16:05:03 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: Sun, 29 Sep 2002 22:05:03 +0200 Subject: Python's import: why doesn't it work? References: <9ac02e81.0209290839.4f4d6475@posting.google.com> <874rc8d9c9.fsf@nospam.eml.cc> Message-ID: <3d975c8f$0$18866$91cee783@newsreader02.highway.telekom.at> "Gerhard H?ring" wrote in message news:mailman.1033319977.7828.python-list at python.org... > It's also highly recommended to start Python with "python -vv", then > trying to import the module in question. This will show you where Python > tries to find the module. Thanks, that's good advice! > Btw. sys.modules contains the module search path. I did look at sys.path, but it didn't help me much... Jurie. From tismer at tismer.com Wed Sep 18 09:16:56 2002 From: tismer at tismer.com (Christian Tismer) Date: Wed, 18 Sep 2002 15:16:56 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D881B66.1080200@something.invalid> <3D8868C3.9090005@one.net> Message-ID: <3D887CC8.5040306@tismer.com> Michael Schneider wrote: ... > "stackless python behaves the same as 'normal' python, until you > import the > stackless module. At that point, it becomes stackless python. This > allows you > to run 'stackless unsafe' modules with the same interpretor as > stackless modules, > in a predictable manner (as long as you don't import stackless, and > an unsafe module)" > > > Is this the correct understanding???? Almost. It is slightly different (and slightly better): Part I: stack slicing --------------------- Stackless Python has built-in support for stack slicing. This is by default off. Stackless Python behaves exactly like Python as long as you don't activate things. There is a couple of new functions in the sys module which control behavior: old_flag = sys.enable_stackless(new_flag) sets stackless behavior to on or off and returns the old state. When it is enabled, then the C stack will be hijacked every nth interpreter recursion, in order so save stack space. This behavior is controlled by the two functions sys.setslicinginterval(n) sys.getslicinginterval() If this interval is set very high, you will also get no stack slicing. Part II: Multitasking --------------------- Completely apart from the features of part I, there is an extension module named stackless. It can be imported only if the Python interpreter was built for it, since it does in fact make use of the above stack slicing technique. But instead of slicing stacks in order to save space in deep recursion, the stackless module uses it to move stacks forth and back. This is like switching threads, just not by stack switching but moving. These multitasking features are independant from the sys options of part I. If a tasklet is asked to switch context to another one, it will do that, since you demanded it. There will be no switching if you don't ask for it. Both parts can be used in any combination. If small stack size is desirable, turn stack slicing on. If you want to use tasklets, use them. In combination, you will of course xperience the best performance. About extension modules: ------------------------ Stack slicing has shown up as a problem with tkinter. I had to modify the _tkinter module to make this safe (and I really should include that in the distro now). The problem with stack slicing is that it occours in a context where an extension might expect certain data to be still on the C stack. Usually, using tasklets is much more safe than stack slicing. It depends on your application. But a tasklet switch, while technically the same, has the semantics of a context switch. You are moving out of a context where some extensiom module might be involved, into a different context, where this extension module is not active. But still some care needs to be taken, since tasklets do microthreading, which is scheduling at a finer grain than real threads. An extension module (or even Python module) might be thread safe, but not microthread safe. The reason is that the extension does not have any knowledge about this context switching, it still thinks of the one existing thread. For that reason, one should avoid to use certain resources more than once in a real thread. Some locking should be used to protect data structures. At the moment the above problems are rather easy to handle, since context switching is explicitly done by the user. I am going to support pre-emptive scheduling, soon, which makes things more difficult, and I will provide a mechanism that inhibits auto-scheduling unless the user declares a module as definativly microthread safe. so much so far - ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From kowk at earthlink.net Wed Sep 25 01:22:35 2002 From: kowk at earthlink.net (Kow K) Date: Tue, 24 Sep 2002 22:22:35 -0700 Subject: how to change font and its size in IDLE (in UNIX)? Message-ID: Hi all, I'm trying to figure out how to change the font and its size in IDLE. It's Courier in 10pt. I don't like Courier, and what's worse, 10pt is too small for me. I wish I could change it to Fixed 7x13. Any input will be appreciated. Kow From aleax at aleax.it Fri Sep 27 03:41:59 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 27 Sep 2002 07:41:59 GMT Subject: readlines() and "binary" files References: <3d90cacf$0$30457$afc38c87@sisyphus.news.be.easynet.net> <3d91de2d$0$30457$afc38c87@sisyphus.news.be.easynet.net> <9yqk9.143972$ub2.3161265@news1.tin.it> <3d936f05$0$30456$afc38c87@sisyphus.news.be.easynet.net> Message-ID: Justin wrote: >> Pity you ruled out defining your own iterator -- > > I had ruled it out by laziness, but since you were kind enough to > provide an implementation, I'll definitely use it! Thanks a lot, You're welcome! I'm lazy too -- that's why I like generators so much... they do LAZY evaluation, after all:-). > it works nicely. Gee I can't wait for that nutshell to crack !-} Delay's not my fault _this_ time -- the complete, technically reviewed and revised draft is now in the editor's hands -- she's probably struggling to make my prose (a mix of verbose, enthusiastic Mediterranean exhuberance [where I let myself go] and tight, precise, dry, maybe overly-technical conciseness [where I carefully revised to minimize text down to the number of characters absolutely needed to convey the essential information]) into a more reasonable, Nutshell-style medietas (OK, so some of that _is_ my fault, I guess, but there's nothing I can do about it right now...). Alex From ajw126NO at SPAMyork.ac.uk Wed Sep 11 07:09:38 2002 From: ajw126NO at SPAMyork.ac.uk (Andrew Wilkinson) Date: Wed, 11 Sep 2002 12:09:38 +0100 Subject: Abstract Syntax Trees Message-ID: Hi, I'm having a lot of trouble trying to get the parser and compiler modules to properly parse some files. At the moment the trouble seems to be with any loop construct (i.e. for or while). If you create a test file like this... --- for i in range(10): print i --- That'll run fine, but type this into python... >>> import compiler >>> compiler.parseFile() and you get... Traceback (most recent call last): File "", line 1, in ? File "C:\PROGRA~2\Python22\lib\compiler\transformer.py", line 43, in parseFile return parse(src) File "C:\PROGRA~2\Python22\lib\compiler\transformer.py", line 47, in parse return Transformer().parsesuite(buf) File "C:\PROGRA~2\Python22\lib\compiler\transformer.py", line 115, in parsesuite return self.transform(parser.suite(text)) parser.ParserError: could not parse string I get the same thing if I replace the for loop with a while loop. A couple of times it has parsed the for loop correctly, but that just seems to be down to which way the wind was blowing a the time. Does anyone know what's going on? I've only been able to test it on my computer, so it could just be me... I'm running Python 2.2.1 Thanks in advance, Andrew Wilkinson From gumuz at looze.net Wed Sep 4 18:33:56 2002 From: gumuz at looze.net (Guyon Morée) Date: Wed, 04 Sep 2002 22:33:56 GMT Subject: Bind threads to addresses -- Windows & urllib? References: Message-ID: i think you mean something like this: import thread def spiderStuff(Socket): # do the spider stuff here pass ... thread.start_new_thread(SpiderStuff, (,newSocket)) "Nick Arnett" wrote in message news:mailman.1031157680.4128.python-list at python.org... > I can't see an obvious easy way to bind threads to IP addresses on a Win2K > machine. I have a multi-threaded Web spider, which uses urllib to retrieve > pages, and would like to bind each thread to a different address on the > machine, if possible. Alternatively, I'd be willing to run separate > processes to accomplish the same. So far, my searches aren't coming up with > any solution... And it would be wonderful if such an approach were also > portable to Linux... Pointers? > > -- > Nick Arnett > Phone/fax: (408) 904-7198 > narnett at mccmedia.com > > > From Henrik.Weber at sys.aok.de Mon Sep 30 04:19:11 2002 From: Henrik.Weber at sys.aok.de (Henrik Weber) Date: 30 Sep 2002 01:19:11 -0700 Subject: DBI cursor behaviour with multiple statements? References: <7e964d1d.0209270137.568a3f3@posting.google.com> Message-ID: <7e964d1d.0209300019.361eea62@posting.google.com> Gerhard H?ring wrote in message news:... > > Ok. Then the Database SIG's mailing lists is the appropriate place to > ask. You'll find that almost all module authors and many users are > subscribed there. Well, their archive is going to make interesting reading. > > > Now I'm not quite sure how to interpret the DBI2 specification when it > > comes to the execution of multiple data returning statements with the > > same cursor. > > The behaviour is undefined for more than one DQL statement. And > .nextset() isn't meant for this case, either. So I can take the easiest way out. I can live with that. > > In fact, I asked the same question on the SIG's mailing list some time > ago: > > Date: Tue, 28 May 2002 21:36:47 +0200 > To: Python DB-SIG Mailing List > Subject: [DB-SIG] Multiple Statements > Message-ID: <20020528193647.GA902 at lilith.my-fqdn.de> > > ... and was referred to a discussion about a year ago (then), where the > consensus was what I summarized above. > > Here's the SIG's mailing list: http://python.org/sigs/db-sig/ > > Btw. an updated form of the specification several interesting "optional > features" is available as PEP 0249. > > -- Gerhard That sounds interesting. Thank you. Henrik From aldo at nullcube.com Sat Sep 14 23:11:03 2002 From: aldo at nullcube.com (Aldo Cortesi) Date: Sun, 15 Sep 2002 13:11:03 +1000 Subject: html template system? In-Reply-To: <0ro7ouskb8ctv6f846gb8cfpqtl5vs1avc@4ax.com> References: <0ro7ouskb8ctv6f846gb8cfpqtl5vs1avc@4ax.com> Message-ID: <20020915031103.GA21206@nullcube.com> ":B nerdy" wrote: >what are good templating systems avaliable for python? A quick search on Google will turn up dozens. Start by reading the following interesting (but, sadly, Perl-centric) article: http://www.perl.com/pub/a/2001/08/21/templating.html Perrin Harkins gives a very good summary of the broader issues involved in picking a templating system. After that, have a look at some of these: Cheetah - http://www.cheetahtemplate.org/ YAPTU - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305 Cubictemp - http://www.nullcube.com/software/cubictemp.html They're all quite good, and your choice will depend mostly on your coding style and sense of aesthetics. I use Cubictemp for much of what I do, but since it was written by my company, my preference for it may simply be habit or bias... Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com From mhammond at skippinet.com.au Tue Sep 24 00:37:52 2002 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 24 Sep 2002 04:37:52 GMT Subject: Outlook 2002 and Python References: Message-ID: Paul Sage wrote: > What: I saw an idea for a way to create a good SPAM filter for email. > > How: I would like to try to implement the algorithm in Python. > > Why: I am trying to get familiar with Python, as I will be using it at > work quite a bit, and would like to keep my skills honed. > > Where: Windows XP and Outlook 2002 > > Okay, so smart people would say, ?just go use Visual Studio or Visual > Basic,? I suppose. I don?t know those two languages either, and they > might be the right tools for the job. However, that would defeat the > point of trying something in Python. Doing something else probably > wouldn?t be as useful to me personally. > > Does anyone know how and where in the world I would even start to try to > write some kind of addin for Outlook 2002 in Python? I don?t even know > how to start the project currently, and I am turning here first. This would be an interesting project ;) You would need to use the new Universal Gateway code (see win32com\test\test_pycomtest.py) and create a server that implements IDTExtensibility2. From there, you should be able to use any of the VB samples to move forward - all the params passed are standard COM objects, so you should be able to do whatever you want. You would also need to get your head around COM events and how to connect to them from Python, as addins are very much event based. I'm doing some work on a plugin now - but not using Python :( And I would *love* to see this work, especially in the face of the Bayes work being done in Python. Mail me if you need a hand. Mark. From glibc at videotron.ca Sun Sep 1 03:29:06 2002 From: glibc at videotron.ca (Pascal Gauthier) Date: Sun, 01 Sep 2002 03:29:06 -0400 Subject: way to pickling locals() Message-ID: <_Ljc9.154$LR1.3474@wagner.videotron.net> Hi, I am currently writing an application that uses the InteractiveInterpreter (PyCrust to be exact). I want to be able to save the state by pickling locals() of the interpreter. The problem is that pickle doesn't support module pickling. To make a long story short, I want to : l = locals() InteractiveInterpreter(locals=l) pickle.dump(l, file) ... InteractiveInterpreter(locals=pickle.load(file)) The only solution I found is to remove __builtins__ and marshal modules from the locals() dictionnary. But this is not really clean... Any other suggestion ??? Thanks. From mfranklin1 at gatwick.westerngeco.slb.com Wed Sep 11 07:25:51 2002 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 11 Sep 2002 11:25:51 +0000 Subject: function pointer In-Reply-To: References: Message-ID: <200209111125.51483.mfranklin1@gatwick.westerngeco.slb.com> On Wednesday 11 Sep 2002 10:15 am, Christina wrote: > Hi! > > Does Python have function pointers? If not, is there a possibility to > emulate them? Excuse my ignorance but what is a function pointer.... could this be the answer:- def aFunction(): print "aFunction was called" ## call it aFunction() ## create a reference to it af=aFunction ## call the reference af() ## at the python command line:- [dev]$ python Python 2.2.1 (#3, May 29 2002, 20:32:44) [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-98)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def aFunction(): ... print "aFunction was called" ... >>> aFunction() aFunction was called >>> af=aFunction >>> af() aFunction was called >>> Regards Martin From phr-n2002b at NOSPAMnightsong.com Fri Sep 20 05:05:57 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Sep 2002 02:05:57 -0700 Subject: monetary applications [was: Python GUI app to impress the bos s?] References: <31575A892FF6D1118F5800600846864DCBD817@intrepid> <23891c90.0209190014.26c5bb9@posting.google.com> <7xk7lhb943.fsf@ruckus.brouhaha.com> <9Qzi9.117104$ub2.2497933@news1.tin.it> Message-ID: <7xd6r9uj2i.fsf@ruckus.brouhaha.com> Alex Martelli writes: > Using double binary floating-point, the result of 0.70 x 1.05 is > 0.73499999999999998667732370449812151491641998291015625; the result should > have been 0.735 (which would be rounded up to $0.74) but instead the > rounded result would be $0.73. Interesting. > Should your business get tax-audited, inspectors may take a dim view > of your shaving a cent off the sales tax due on each and every item > you sell to the public at $0.70 -- "I found it hard to imagine" how > rounding effects might affect the result (when the law specifies > rounding to the nearest cent and always rounding half cents up) may > not be an acceptable defense. I don't think they ask or care whether you round up or down on individual 70 cent items. They want to know the total value of the stuff you sold, and then the tax you pay is X percent of that total, for whatever your local value of X is. From aglyportREMOvethispart at nospam.yahoo.com Wed Sep 4 19:44:14 2002 From: aglyportREMOvethispart at nospam.yahoo.com (Anton Graph) Date: Wed, 04 Sep 2002 16:44:14 -0700 Subject: Is it okay to compile 2.2.1 with gcc 2.96? Message-ID: <3D769ACE.7000801@nospam.yahoo.com> I've copied over the 2.2.1 tree from RH7.2 box to a RH7.3 box and run gmake install. For some reason it decided to recompile everything. My question is this. Is gcc 2.96: Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/2.96/specs gcc version 2.96 20000731 (Red Hat Linux 7.3 2.96-112) considered to be a stable compiler for the purpose of compiling 2.2.1? From tismer at tismer.com Thu Sep 19 09:10:05 2002 From: tismer at tismer.com (Christian Tismer) Date: Thu, 19 Sep 2002 15:10:05 +0200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> <3D890FB0.4030408@something.invalid> Message-ID: <3D89CCAD.1020406@tismer.com> Martin v. L?wis wrote: > Thomas Heller writes: > > >>>That is not true. It is more reliable to inspect the source code. >>>In general, it is very easy to do so: if there are no callbacks to >>>Python, the module is stackless-safe. >> >>So win32all probably wxPython are incompatible with stackless? > > > No. If a module has callbacks, it is thread safe if it does not put > data on the stack whose addresses are used outside the function, and > it does not use setjmp, and it does not use exception handling. Maybe sufficient for not crashing on the C level. But this is not enough for micro-thread-safety. See the random module for example, it needs a lock or it will give unpredictable results. ciao - chris -- Christian Tismer :^) Mission Impossible 5oftware : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 89 09 53 34 home +49 30 802 86 56 pager +49 173 24 18 776 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From grabiller at 3dvf.net Wed Sep 25 12:00:20 2002 From: grabiller at 3dvf.net (Guy Rabiller) Date: Wed, 25 Sep 2002 18:00:20 +0200 Subject: Newbie References Question -> Exemple References: <3d91c72f$0$8558$79c14f64@nan-newsreader-02.noos.net> <3d91d2cf$0$1484$79c14f64@nan-newsreader-01.noos.net> Message-ID: <3d91dd96$0$14626$79c14f64@nan-newsreader-03.noos.net> Yes, exactly. I forgot that 'p' refere to nested lists :/ How shame.. Thanks a lot. -- guy rabiller 3d animator / td grabiller at 3dvf.net http://grabiller.3dvf.net Andrew Koenig wrote: > Guy> But now, if I change the coordinate of one point: > Guy> p[0] = [5,5] > Guy> I will have: >>>>> p > Guy> [[5, 5], [0, 1], [1, 1], [1, 0]] > Guy> but: >>>>> quad > Guy> [[0, 0], [0, 1], [1, 1], [1, 0]] > > That is because you are not changing the coordinates of the point; you > are causing p[0]--the 0th element of p--to refer to a completely new > point. > > If you wanted to change the coordinates of the point, you should > have written this: > > p[0][0] = 5 > p[0][1] = 5 > > or, more succinctly: > > p[0][:] = [5, 5] > > If you try this, I think you will get the behavior you want. From tjreedy at udel.edu Thu Sep 5 18:12:21 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 05 Sep 2002 22:12:21 GMT Subject: Python Source Code Documentation References: Message-ID: <9FQd9.324581$Aw4.13464627@bin2.nnrp.aus1.giganews.com> "Sean Ross" wrote in message news:al8k02$186$1 at driftwood.ccs.carleton.ca... > Terry: Yes, I did mean the Python interpreter. And I will give your > suggestion a try. > > Martin: I will check out both of those documents. > > Thank you both for your suggestions. When I looked a few years ago, I mentally divided the source files into four groups: compilation phase (a few files) interpretation phase (1 file, the main loop -- ceval.c?) builtin datatypes (one for each -- int, long, tuple, etc -- each with similar structure) other Hope this helps a bit to get started TJR From rond at ixsys.com Thu Sep 5 22:47:10 2002 From: rond at ixsys.com (Ron Darling) Date: Thu, 5 Sep 2002 21:47:10 -0500 Subject: What database should I use In-Reply-To: Message-ID: Below is what I had sent to the original question off forum (replied direct). The description of VFP was not a sales pitch. It was in response to obsolete. =============================== I program in Foxpro/VFP and have since 1989. The reason I do that is not because of the tables but because of the language and runtime enviroment that is available to me. In my opinion... 2000 - 3000 records is not a decision point for most DB table types. Too small they will all handle very well. As far as I know in all three you will have to deal with ODBC so that does not make a difference. One of the advantages of the Fox enviroment (not Python -> Fox) is the table can be native or not. Meaning in VFP I can pull data from VFP tables as well as Access and MySQL all at the same time but the VFP table is native. Easy distribution. I know this is not part of the answer you are looking for but if you used VFP table and for some reason you needed more horse power you have a cleaner option moving into VFP as far as the data is concerned. Most people are surprised to see the volume of data VFP is handling out there in the business world once they find out. MySQL - You have to install MySQL somewhere. Seems a little much for 3000 records especially if you are running MySql on a separate box. Access - Everything is stored in the MDB. If it corrupts well you risk loosing everything you stored in the .MDB file. I have always just hated Access but that is me. Too many reasons to discuss here. In my opinion VFP has the strongest most organized community mainly due to http://www.universalthread.com. I suspect you could even get support there with Python -> VFP tables. I see that discussed there often. I think your choice comes down to what are you interested in learning and living with or maybe what looks best on your resume with your specific career path. ============================= -----Original Message----- From: Ganz, Will [mailto:wganz at imacs.com] Sent: Thursday, September 05, 2002 11:18 AM To: 'Ron Darling'; Sathish Chandrasekaran (S); printers at sendme.cz; python-list at python.org; tutor at python.org; activepython at listserv.ActiveState.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: RE: What database should I use I grant that FoxPro is still a formidable competitor in the marketplace but given the size that the original poster stated of 2K-3k records; the 2gig Access limitation shouldn't come into play. In this instance, Visual FoxPro would be like using a supersonic fighter jet as a crop duster. 8-) -----Original Message----- From: Ron Darling [mailto:rond at ixsys.com] Sent: Thursday, September 05, 2002 10:30 AM To: Sathish Chandrasekaran (S); printers at sendme.cz; python-list at python.org; tutor at python.org; activepython at listserv.ActiveState.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: RE: What database should I use >> (though it's it considered obsolete now-a-days). This is only a consideration for the uni-formed or those that have never really used it. MS is still dumping lots of money into it. Just shipped v7.0 will be going into Beta with 8.0 in a couple of months. Amazing String capabilties. As a matter of fact there is now a VFP style .net class that moves a lot of the wonderful commands internal to VFP to .NET. I think the Fox Dev team created. Cursor Technology, Rushmore Speed and many other things have moved there way into not only Access but SQL Server and ADO. Due to the fact that each part of a table is its own file. .DBF is the table. .FPT is the Memo field .CDX is the index. The file size limitation of the OS of 2 gig is at the individual file level. In Access everything is stored in the same file (you could break up but not really meant to) so the 2 gig file size is limited to the app and data which is more than likely in the same file. I have dealt with lots of situations where the .DBF was 1.8 gig, the index was 1.2 gig and the FPT was another 1+ gig size. Indexes are stored in a .CDX file. A .CDX file can have as many as 255 indexes (take into account 2 gig file size). Each open table can have 10 open CDX's so you can have 2550 indexes on a table. Very Robust SQL pass Through for back end databases. There is nothing out there as fast as VFP for pure raw speed. SQL 2000 gets close but not quite there, the advantage to SQL as far speed goes is it does not bog down under load. Load means 25 + heavy users. As far as speed goes I have seen the return of queries on tables as large as 21 million records within seconds and that was pulling data across a 10 meg network with Foxpro For DOS. United We Stand (remember Ross Perot) member/prospect database. Sounds a little dated but the point is its been that way in Fox for a long time. Fox and VFP managed/tracked the military assets to the Persian Gulf and is till in use. Manages the flow of info for Chunnel. It is far more prevalent than most realize. Very good OOP. It seems that VFP is becoming known for the best language that can really implement the "Abstract Factory Pattern" Very good interface. Rich Native Controls (No OCX) and does very well with OCX's. Easy Distribution. (Drop a couple of DLLS into system directory not reg) Rich Debugger. Can access any data ODBC, ADO or ADO.Net can access. Internal XML. Select Result set from SQL into a local cursor then use CURSORTOXML(). With the XMLTOCCURSOR() and CURSORTOXML() commands it is very easy to build thin wire apps. Bind the interface to the cursor. I can try any and all commands from the command prompt and even from within a debugging suspend. Pretty much interrogate the entire system at hand very easily from a suspend. Many options for hanging VFP behind IIS and ISAPI. You can create com objects and run behind other languages even from within SQL Server or visa versa. One of the most robust SOUNDEX/Fuzzy Search add-ons available with the PHDbase Library. You can index memo fields and do 2 - 3 second searches on huge amounts of memo data. Best Table Repair Libraries that I am aware of are available. Error trapping has been far superior to VB and a lot of languages since the Fox 2.0 days (1992). Last but not least http://www.universalthread.com. Great support from all over the world. obsolete...hmmmmm maybe lack of exposure or conflicting marketing problems with MS owning Access, SQL and Fox but certainly not obsolete. -----Original Message----- From: activepython-admin at listserv.ActiveState.com [mailto:activepython-admin at listserv.ActiveState.com]On Behalf Of Sathish Chandrasekaran (S) Sent: Thursday, September 05, 2002 9:24 AM To: printers at sendme.cz; python-list at python.org; tutor at python.org; activepython at listserv.activestate.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: RE: What database should I use In that case MS-access will be better on the size issue. But on the other hand if u want ur application to be flexible and ease of use I would rather suggest FoxPro (though it's it considered obsolete now-a-days). Here Is A Test To Know Whether The Mission Of Your Life Is Over . If You Are Alive It Isn't . Sathish C Infra-Amdocs -----Original Message----- From: A [mailto:printers at sendme.cz] Sent: 05 September 2002 15:21 To: python-list at python.org; tutor at python.org; activepython at listserv.ActiveState.com; python-help at python.org Cc: db-sig at python.org; wx-users at lists.wxwindows.org Subject: What database should I use Hello, I am going to program a small application (in Python and wxPython) which consists about 2000 - 3000 records . Can you please recommend which database is the best for that. I use Windows. Maybe MS Access or FoxPro or MySQL or better? I want to keep the program as small as possible. Thanks Ladislav _______________________________________________ ActivePython mailing list ActivePython at listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython _______________________________________________ ActivePython mailing list ActivePython at listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython _______________________________________________ ActivePython mailing list ActivePython at listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs Other options: http://listserv.ActiveState.com/mailman/listinfo/ActivePython From cliechti at gmx.net Sat Sep 7 16:32:57 2002 From: cliechti at gmx.net (Chris Liechti) Date: 7 Sep 2002 22:32:57 +0200 Subject: getting clients ip address References: Message-ID: "Leader" wrote in news:r0te9.25654$6W3.867995 at weber.videotron.net: > Hello, I am using Python for my website, more specifically > Spyce+mod_python, what I want to do is print out the clients ip > address on the site so it can say something like "your ip > is:xxx.xxx.xxx.xxx" basicly the python version of getenv("REMOTE_ADDR"); ?> I'm sure I saw something a while ago while > browsing through the module docs but I can't find it anymore. something like: >>> import os >>> print os.environ["REMOTE_ADDR"] HTH, chris -- Chris From Padraig at Linux.ie Wed Sep 11 07:04:15 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Wed, 11 Sep 2002 11:04:15 GMT Subject: regular expression for space seperated quoted string Message-ID: Hi, I'm trying to split a string that is seperated by spaces and also contains double quoted words which can contain spaces: For e.g. using: re.split('[ ]*"?([^"]*)"?[ ]*', s1) on this string: s1='1 "2" "thre e"' gives: ['', '1 ', '', '2', '', 'thre e', ''] Problem with this is the '' entries, but this isn't too bad. However using the above re with: s2='1 2 "th ree"' I get: ['', '1 2 ', '', 'th ree', ''] any ideas? thanks, P?draig. From aahz at pythoncraft.com Mon Sep 23 21:55:59 2002 From: aahz at pythoncraft.com (Aahz) Date: 23 Sep 2002 21:55:59 -0400 Subject: Can't suspend a thread? References: Message-ID: In article , Robert Oschler wrote: > >I was hoping to have a master thread that woke up and suspended several >other threads dynamically, as needed. From the books I have, that seems to >be impossible in Python? Is this true? If so, is there a workaround? Threads suspend themselves; they can be woken up by other threads. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From anthony at computronix.com Mon Sep 30 12:55:36 2002 From: anthony at computronix.com (Anthony Tuininga) Date: 30 Sep 2002 10:55:36 -0600 Subject: redhat8 In-Reply-To: <873crr4fy6.fsf@flibuste.net> References: <873crr4fy6.fsf@flibuste.net> Message-ID: <1033404937.1946.25.camel@chl0151.edmonton.computronix.com> According to the release documentation: Python 2.2.1 is on the CD. Finally.... :-) On Mon, 2002-09-30 at 10:09, William wrote: > hi, > > anybody know wich version of python is /usr/bin/python on the new redhat > release ? > > -- > William Dod? - flibuste.net > http://wikipython.tuxfamily.org > -- > http://mail.python.org/mailman/listinfo/python-list -- Anthony Tuininga anthony at computronix.com Computronix Distinctive Software. Real People. Suite 200, 10216 - 124 Street NW Edmonton, AB, Canada T5N 4A3 Phone: (780) 454-3700 Fax: (780) 454-3838 http://www.computronix.com From nm at bolas.clara.co.uk Thu Sep 26 06:12:49 2002 From: nm at bolas.clara.co.uk (Nick B) Date: Thu, 26 Sep 2002 11:12:49 +0100 Subject: Multiple file open dialog Message-ID: <3d92dce4$0$1286$cc9e4d1f@news.dial.pipex.com> Hi, Can anyone advise on how to get a list of multiple file names from a GUI dialog. I am working exclusively in Win32 but so far only have GUI experience with Tkinter. What I would like is access to the standard Win32 shift-click and control-click conventions. Tkinter's askopenfilename can only return a single filename (?). Pythonwin's win32gui.GetOpenFileName looks like it could do the job, but a simple example would really help. Other ideas ? Any help appreciated, Nick From chris.walsh at real-sense.com Fri Sep 6 11:46:41 2002 From: chris.walsh at real-sense.com (Chris Walsh) Date: 6 Sep 2002 08:46:41 -0700 Subject: Embedding - Local dictionaries for local scripts Message-ID: <1691b372.0209060746.55b8cf1@posting.google.com> Hi, I am embedding Python into a 3D renderer and for each "object" in the environment, I want some local script which can get run. Each object will have it's own local variables which must persist between calls to it's script there I believe I want to create a local dictionary for each object which gets passed into the function: PyObject* PyRun_String( char *str, int start, PyObject *globals, PyObject *locals); I have seen some stuff in comp.lang.python about creating a dict and adding the __builtin__ module but I have been searching now for an hour and cannot find it. Can anyone point me to some code which creates this dictionary? Kind Regards, Chris. "God is Real, unless declared Integer" From wesc at deirdre.org Thu Sep 5 02:25:35 2002 From: wesc at deirdre.org (wesc at deirdre.org) Date: Wed, 4 Sep 2002 23:25:35 -0700 (PDT) Subject: ANN: BayPIGgies mtg Wed 9/11 7:30pm Message-ID: <200209050625.g856PZx20521@alpha.ece.ucsb.edu> BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group Agenda: Using a New MVC Architecture to Create a Pythonic XML-based Web Application Framework When: September 11, 2002 @ 7:30pm Where: Stanford University, Palo Alto, CA Speakers: Paul McGavin, Donovan Preston, Sam Penrose from InterSight We will discuss how we are applying a new Python-based MVC architecture to create an efficient, Pythonic web application framework that separates presentation templates from the Python source code with DOMTemplate. The framework componentizes behavior into reusable objects with DOMWidgets and DOMHandlers. After creating web applications in three separate Python frameworks -- Webware for Python, Zope and Apache/Python cgi -- InterSight decided to create its own MVC framework, based on some of the ideas from IBM and Lutris Enhydra's Barracuda project, to power their automated publishing applications. Their applications enable scalable content: the ability to produce, from a single set of managed data and images, many different marketing communication pieces: press- ready Adobe InDesign and QuarkXPress files, web pages, order sheets, sample stickers, price tags and more. We are actively seeking speakers for BayPIGgies, esp. October 9th! If you would like to give a talk at one of our meetings (any Python- related topic), please contact us! more info including directions: http://www.baypiggies.net hope to see some of you on Wednesday! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, ? 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://www.baypiggies.net wesley.j.chun :: wesc at deirdre.org cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://roadkill.com/~wesc/cyberweb/ From see_reply_address at something.invalid Wed Sep 18 02:21:26 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 18 Sep 2002 18:21:26 +1200 Subject: Stackless Python, eventual merge? References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> <3D87CE0A.9090609@something.invalid> Message-ID: <3D881B66.1080200@something.invalid> Martin v. Loewis wrote: > > They aren't really dangerous, just unconventional. Last I heard, Christian was moving pieces of the C stack while there could be pointers to it in use. That's definitely dangerous, as he discovered when it broke Tk. I'd be very nervous about using Stackless until it stops doing that. > And that cannot be > fixed, as it is essential to operation of Stackless. Seems to me it could be fixed by just copying the C stack as a whole, instead of piecemeal. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From aleax at aleax.it Fri Sep 20 14:45:15 2002 From: aleax at aleax.it (Alex Martelli) Date: Fri, 20 Sep 2002 18:45:15 GMT Subject: Is there a widget or program for a database browsing References: Message-ID: <%0Ki9.140164$pX1.4973236@news2.tin.it> A wrote: > In my program users will search a database and I need to display choosen > record(s ) in a nice graphical way. Is there a module( program), that I > could use together > with Python, that could easily show the database record(s) and take care > of all thinks during browsing? Thanks for help. The latest version of PyQt comes close to these requirements, I think, but I haven't tried out the "SQL-enabled widgets" yet. Alex From lac at strakt.com Thu Sep 26 12:55:26 2002 From: lac at strakt.com (Laura Creighton) Date: Thu, 26 Sep 2002 18:55:26 +0200 Subject: off topic -- spam assassin In-Reply-To: Message from Skip Montanaro of "Thu, 26 Sep 2002 10:49:01 CDT." <15763.11373.573554.830138@12-248-11-90.client.attbi.com> References: <200209261407.g8QE76Wo028975@ratthing-b246.strakt.com> <15763.11373.573554.830138@12-248-11-90.client.attbi.com> Message-ID: <200209261655.g8QGtQo9029577@ratthing-b246.strakt.com> 2.20 is was. Thank you for the recommendation, 2.41 it is now. We'll see how long that holds them. Thanks again, Laura From eric.brunel at pragmadev.com Tue Sep 3 05:16:17 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 3 Sep 2002 11:16:17 +0200 Subject: what about things like __*** ? References: <7153651c.0209021927.16a3efaf@posting.google.com> <3d746df6$0$222$4d4ebb8e@news.nl.uu.net> Message-ID: Gumuz wrote: > ah great, I found asking this myself last night, too. > > isn't this the same for: __methodName(self, parm) which makes it a > private method? Yep! class C: def __m(self): print 'spam' def __init__(self): self.__m() # Works o = C() o.__m() # Does not work -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From gumuz at looze.net Wed Sep 4 05:29:15 2002 From: gumuz at looze.net (Gumuz) Date: Wed, 4 Sep 2002 11:29:15 +0200 Subject: encryption (passwords) Message-ID: <3d75d115$0$221$4d4ebb8e@news.nl.uu.net> I am quite a newbie regarding encryption stuff. There are some issues boggling my head and I suppose these come from the fact that I have no clue how to apply encryption in a real-life situation. I am using network-sockets to communicate between two(or more) python applications. I want to encrypt these messages, or at least a part of it e.g. password and such. My limited understanding of encryption tells me that I need a 'key' to decrypt stuff. So I figure that this key will bey written(hard-coded?) somewhere in my Python-script and it needs to be known at both sides in order to encrypt and decrypt. Somehow, I can't believe this is true. I can't get over the idea that if my application becomes open-source anyone could see the key and decrypt my messages. I am fairly certain that it probably doesn't work this way, but I have really no idea. Cann someone clarify this for me? thanx a lot, Guyon From mgerrans at mindspring.com Fri Sep 13 02:12:05 2002 From: mgerrans at mindspring.com (Matt Gerrans) Date: Thu, 12 Sep 2002 23:12:05 -0700 Subject: IDLE References: Message-ID: Amazing that such an inane question could engender so many entertaining answers, but I think this one wins the prize for best chuckle. (...so far...) "Raymond Hettinger" wrote in message news:alk170$pai$1 at bob.news.rcn.net... > > Why won't my IDLE work? > > This is the documented behavior according > to the American Heritage Dictionary: > > idle (intr. verb): To pass time without working > or while avoiding work. From sdeibel at wingide.com Tue Sep 17 10:12:13 2002 From: sdeibel at wingide.com (Stephan R.A. Deibel) Date: Tue, 17 Sep 2002 10:12:13 -0400 (EDT) Subject: O'Reilly Python Success Stories Message-ID: Hi, O'Reilly Associates has agreed to do a Python Success Stories book similar to those that already exist for Perl. This book will be given away for free at bookstores and conferences, and is a great way to showcase what Python can do. If you have a Python success story to tell, please consider contributing to this effort. O'Reilly will do the formatting, cover design, and printing, but the collection and editing of stories is left up to volunteers in the Python community. More information on how to contribute can be found here: http://pythonology.org/successguide While we prefer completed stories, we can also accept responses to the list of questions given in the above URL. Thanks, - Stephan ------------------------------------------------------------------------ Wing IDE for Python Archaeopteryx Software, Inc www.wingide.com Take Flight! From jhorneman at pobox.com Tue Sep 3 06:14:40 2002 From: jhorneman at pobox.com (Jurie Horneman) Date: 3 Sep 2002 03:14:40 -0700 Subject: Which XML parser under Python can handle Unicode? Message-ID: <9ac02e81.0209030214.515d6c0@posting.google.com> XML is complicated (if you dig deep). Python libraries are complicated (if what you want to know is apparently not in the documentation). Unicode is complicated (if you dig deep). Aaahhhh.... Could someone please recommend an XML parser under Python which can handle Unicode? Specifically, most European languages and Asian languages such as Chinese (traditional, simplified), Japanese, Korean and Thai? (Please don't make me look up the actual codetables.) Ideally the parser would use Python's codec system. I'd prefer an event-based parser, although tree-based would not be a huge problem. Thank you thank you Jurie. From gmuller at worldonline.nl Tue Sep 24 15:56:33 2002 From: gmuller at worldonline.nl (GerritM) Date: Tue, 24 Sep 2002 21:56:33 +0200 Subject: How to get memory usage on Windows? References: <3D8EEB7C.C1B2F01F@philips.com> Message-ID: "Gerrit Muller" schreef in bericht news:3D8EEB7C.C1B2F01F at philips.com... > > > Emile van Sebille wrote: > > > > GerritM: > > [snip] > > > how much memory is used per phase and/or per function. Is there any > > function > > > returning this information. I noted that on Unix the resource module > > gives > > > access to this kind of information, but I could not find any Windows > > > alternative. > > > <...snip...> In mxTools a sizeof(object) function is available, which should allow me to reconstruct most memory consumption data via a procedure, although some care should be taken wrt referenced data. http://www.egenix.com/files/python/mxTools.html regards Gerrit > http://www.extra.research.philips.com/natlab/sysarch/index.html From hancock at anansispaceworks.com Tue Sep 3 01:06:00 2002 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 02 Sep 2002 22:06:00 -0700 Subject: Would you like a Snobol pattern matcher? (Re: Making regex suck less) References: <20020903015907.15062.14810.Mailman@mail.python.org> Message-ID: <3D744338.D2E223CC@anansispaceworks.com> From: Greg Ewing > Maybe it's time for me to resurrect the Snobol-style > pattern matching module that I started on a while > back and never got around to releasing. > > Would anyone be interested in this? Its > syntax is similar to that of Plex REs, except that > the primitives are Snobol-like, and it uses a > backtracking matching algorithm that's much more > powerful than a DFA (you can write entire parsers > in it, for example). Some interesting references, possibly? -- http://sourceforge.net/projects/pystemmer/ http://snowball.sourceforge.net These may be more specialized -- Snowball is specifically for algorithmically stemming words, and PyStemmer is an interface to it. I haven't really looked into how it works. The name is related to SNOBOL, but I'm not sure how much Snowball actually resembles it (if at all). I'm using pystemmer as part of a function which converts object titles to (hopefully) mnemonic file names (ids) in Zope. I haven't really looked into how it works. But I though it might be relevant to you. Cheers, Terry -- ------------------------------------------------------ Terry Hancock hancock at anansispaceworks.com Anansi Spaceworks http://www.anansispaceworks.com P.O. Box 60583 Pasadena, CA 91116-6583 ------------------------------------------------------ From tjreedy at udel.edu Fri Sep 6 09:00:16 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 06 Sep 2002 13:00:16 GMT Subject: Python and Jython inconsistencies when encoding strings References: Message-ID: "Andre Michel Descombes" wrote in message news:ala00d$dij$1 at wanadoo.fr... > when I do the following in Python : > > >>> s = u'?' # Alt-0163, pound sign > >>> print s > > I get the following exception, which is a normal exception: > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeError: ASCII encoding error: ordinal not in range(128) ... On Python2.2, Windows >>> s=u'?' # Alt-163: u with acute accent >>> s u'\xa3' >>> print s Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) What surprises me is that I thought that raw expression (interactively) was abbreviation for print expression. Bug here? Terry J. Reedy From pinard at iro.umontreal.ca Tue Sep 3 20:22:38 2002 From: pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) Date: Tue, 03 Sep 2002 20:22:38 -0400 Subject: Pyrex 0.4.4 In-Reply-To: ("Delaney, Timothy"'s message of "Wed, 4 Sep 2002 09:27:10 +1000") References: Message-ID: [Delaney, Timothy] >> From: Greg Ewing >> >> Pyrex 0.4.4 is now available: >> >> http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ > > The Plex package appears to be a shortcut/link, rather than the package ... I noticed too. To get going, I got Plex installed separately, and removed the 'Plex' line in `setup.py' for Pyrex. -- Fran?ois Pinard http://www.iro.umontreal.ca/~pinard From loewis at informatik.hu-berlin.de Mon Sep 9 07:48:31 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 09 Sep 2002 13:48:31 +0200 Subject: xml.minidom is stripping out my CRLF's in attrib values!! References: <3D7C80C4.9070204@NOSPAMbitbuilder.com> Message-ID: Ahmad Baitalmal writes: > What's the deal, is there a setting I can set? XML specifies that line endings must be normalized by a processor, see http://www.w3.org/TR/REC-xml#sec-line-ends There is no option to report anything but #xA to the application. Regards, Martin From see_reply_address at something.invalid Thu Sep 12 21:33:42 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Fri, 13 Sep 2002 13:33:42 +1200 Subject: Piper Pickling? References: Message-ID: <3D814076.9050509@something.invalid> Robert Oschler wrote: > If Peter Piper pickles a peck of Python packages, can he pack the pickled > Python peckers in a proper packing place? > > Translated: Anybody seen a module that can override the standard pickling > process and store and retrieve Python objects to a MySQL database? Well, you can use pickle.dumps() to pickle your objects into strings, and then store the strings in your database. Will such suitably squashed SQLed strings satisfy? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From peter at engcorp.com Mon Sep 2 21:59:38 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Sep 2002 21:59:38 -0400 Subject: RedHat 7.3 and Python2.2.1 References: Message-ID: <3d74176d@news.sentex.net> Kow Kuroda wrote: > > On Monday, September 2, 2002, at 11:43 , Peter Hansen wrote: > >> Doug Farrell wrote: >>> I'm trying to install the latest version of Python >>> (python2-2.2.1-1.i386.rpm) from the www.python.org download page, and >>> I'm having problems. When I run >>> >>> rpm -i python2-2.2.1-1.i386.rpm >>> >>> I get all kinds of conflict messages like this: >>> >>> file /usr/bin/pydoc2 from install of python2-2.2.1-1 conflicts with >>> file from package python2-2.2-16 >> >> Sounds like you already have a previous version of Python2.2 installed. >> You should probably be using the "-U" option to update instead of >> the "-i" option to install... or uninstall the previous one first. > > I just wanted to make a comment on Peter's post. > > I think -U or --upgrade option works, but it's dangerious to uninstall > Python 2.1, which is now part of Red Hat Linux 7.3, unlike in prevous > releases where Python 1.5.2 or something is used for installation scripts. (Note he had a conflict with Python 2.2, not 2.1. It should work fine.) Your comments about RH7.3 don't quite fit with my experience. I just installed it (posting from the machine it's on, in fact) and "python" executes 1.5.2 still, while "python2" executes 2.2, not 2.1. What am I missing? -Peter From aahz at pythoncraft.com Fri Sep 20 10:58:47 2002 From: aahz at pythoncraft.com (Aahz) Date: 20 Sep 2002 10:58:47 -0400 Subject: Destructor never called ??? References: <76710511.0209111450.40999dd8@posting.google.com> <4e8lou018f9uosl5p9mb0tt6691mfivamj@4ax.com> Message-ID: In article , Alex Martelli wrote: >Aahz wrote: >> >> There are several different issues. First of all, __del__ does not get >> called if an object is destroyed by GC (GC gets used to clean up cyclic >> garbage). Secondly, Jython does not use refcounting; it's pure GC, just > >Right, but, I'd put it differently: GC is inhibited from destroying >objects whose types define a __del__ -- rather, it collects them into >gc.garbage, because it can't know that finalizing them is safe. Thanks (and also to Tim) for correcting my sloppy writing. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Project Vote Smart: http://www.vote-smart.org/ From see_reply_address at something.invalid Tue Sep 24 23:23:13 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Wed, 25 Sep 2002 15:23:13 +1200 Subject: Strange values in Accept-Language header? References: <8FWj9.39597$V7.10466682@twister.socal.rr.com> Message-ID: <3D912C21.30109@something.invalid> Jeff Davis wrote: >>Accept-Language: en-us,x-ns1rDGeT4e2FpA,x-ns2f67971hgDw1 >>Accept-Language: x-ns13V8cN8S1Xz9,x-ns2T329gfxKa7d >> >>I have no idea what these could mean Oh, boy, you've done it now. These refer to secret code languages used by the PSU. Now that you've drawn attention to them, the PSU will cut off all your From ehagemann at comcast.net Mon Sep 30 17:28:32 2002 From: ehagemann at comcast.net (Eric Hagemann) Date: Mon, 30 Sep 2002 21:28:32 GMT Subject: help with writing extension References: Message-ID: <4m3m9.331653$216.13979015@bin4.nnrp.aus1.giganews.com> Alex Thanks for another excellent answer. I am going to dig into the Py_TPFLAGS_CHECKTYPES flag as that might just fix my problem. I did not really want to use the __coerce__function but I did not know how to get around it. If adding this flag to the definition will skip the __coerce__ function, that should save me a bunch-o-code. BTW I see references to the CHECKTYPES flag in the Python 2.1 source (Yes - I am still using 2.1) any reason why I need to move to 2.2 ? I eventually (after studying the sources) did find the reason for my "problem". Summarized for any that might want to know..... When you do a binary_op between two objects that are not equal in type the __coerce__ function is called for the first object. If that does not 'coerce' the different objects into compatable ones then the __coerce__ function is called for the second object. If that does not return sucessfully then you are done for. However if that returns sucess then the operation is called using the method defined for the first of the two objects As it turns out I already skipped throught __coerce__ function by just incrementing the references on the two objects and returning success. This worked well when I was doing operations of +int as I would just pass both on to my 'add' function and I delt with the integer in my function. However when working with the arguments in reverse, this method would not work as after the second coerce function I would still have an int+ and it would call the 'add' function for the int, which even after two attempted coercions, would not know what was and the TypeError was generated. What was refreshing was that I could find the root of the problem by studying the source -- says something for how the code was written, nice -- very nice. Cheers "Alex Martelli" wrote in message news:pQYl9.190868$pX1.6828893 at news2.tin.it... > > > Eric Hagemann wrote: > > > I have been handcrafting an extension module creating a new type > > > > I am making use of the numeric methods (+,-,* etc) > > > > I solved the problem of the object interating with other types by working > > through the __coerce__() function and have no issue with operations like > > +2 but I am getting an error on 2-. > > As I understand, __coerce__ is not recommended for new code. You should, > I believe, add Py_TPFLAGS_CHECKTYPES to your tp_flags slot, and be ready > in your numeric functions to deal with types as they come. Sometimes > coercion can be handier, but in general avoiding it is better. > > > > In Beazley's book there are descriptions of functions like __radd__() when > > defining a new type in python, but I cannot find reference to these > > functions in C ? > > If you grep Python's C sources (2.2 or better), you'll find some such > references. Slots nb_add of the PyNumberMethods structure to which > slot tp_as_number of your PyTypeObject structure point supplies both > __add__ and __radd__ (when you call PyType_Ready on your type, suitable > wrappers on that slot are exposed with those two names). > > > > I have checked the doc's (not to say that I did not miss something ;) ) > > I think you still need to complement existing docs with some little > study of the Python sources when you want to design rich and complete > extension types -- and I think that dealing with __radd__ etc in the > right way is part of a "rich and complete" (rather than just a > really minimal) extension type. I think this will still be true > when my "Python in a Nutshell" is finally out, because the chapter > on extending and embedding with C is limited to 40-50 pages (can't > be more precise right now because the book's being edited and I'm > not sure how many of my examples and details the editor will want > to keep -- or if even more will be added), and doing complete justice > to the subject would require about 10 times as much space. > > But I also think that asking here about such issues is just right! > Best place to get help -- and this way the help gets archived (thanks > to google groups and other archivers) and can be pointed to in the > future (which alas doesn't work for other mailing lists such as > python-help, nor, of course, for private mail:-). > > > An example can help -- sorry if it's not very concise, but the > PyTypeObject structure is so large that any examples of its use > are also large, even though most fields are 0. Say I have a > directory ~/extype with a setup.py file such as: > > from distutils.core import setup, Extension > > setup(name = "samp1", > version = "1.0", > description = "Sample extension type", > maintainer = "Alex Martelli", > maintainer_email = "aleaxit at yahoo.com", > > ext_modules = [ Extension('samp1', sources=['samp1.c']) ] > ) > > and a samp1.c file such as: > > #include "Python.h" > > typedef struct { > PyObject_HEAD > } samp1; > > static void > samp1_dealloc(PyObject *op) > { > op->ob_type->tp_free(op); > } > > static PyObject * > samp1_amethod(PyObject *self) > { > Py_INCREF(Py_None); > return Py_None; > } > > static PyObject * > samp1_add(PyObject *self, PyObject *other) > { > PyObject* result = PyTuple_New(2); > if(!result) > return NULL; > Py_INCREF(self); > PyTuple_SET_ITEM(result, 0, self); > Py_INCREF(other); > PyTuple_SET_ITEM(result, 1, other); > return result; > } > > static PyMethodDef samp1_methods[] = { > {"amethod", (PyCFunction)samp1_amethod, METH_NOARGS}, > {NULL, NULL} /* sentinel */ > }; > > static PyNumberMethods samp1_as_number = { > samp1_add, > }; > > static PyTypeObject samp1_t = { > PyObject_HEAD_INIT(0) > 0, > "samp1", > sizeof(samp1), > 0, > samp1_dealloc, > 0, > 0, > 0, > 0, /* tp_compare */ > 0, /* tp_repr */ > &samp1_as_number, /* tp_as_number */ > 0, /* tp_as_sequence */ > 0, /* tp_as_mapping */ > 0, /* tp_hash */ > 0, /* tp_call */ > 0, /* tp_str */ > 0, /* tp_getattro */ > 0, /* tp_setattro */ > 0, /* tp_as_buffer */ > Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES, > "sample extension type", > 0, /* tp_traverse */ > 0, /* tp_clear */ > 0, /* tp_richcompare */ > 0, /* tp_weaklistoffset */ > 0, /* tp_iter */ > 0, /* tp_iternext */ > samp1_methods, /* tp_methods */ > 0, /* tp_members */ > 0, /* tp_getset */ > 0, /* tp_base */ > 0, /* tp_dict */ > 0, /* tp_descr_get */ > 0, /* tp_descr_set */ > 0, /* tp_dictoffset */ > 0, /* tp_init */ > PyType_GenericAlloc, /* tp_alloc */ > PyType_GenericNew, /* tp_new */ > _PyObject_Del, /* tp_free */ > }; > > static PyMethodDef no_methods[] = { {0} }; > > void > initsamp1(void) > { > PyObject* self; > PyType_Ready(&samp1_t); > self = Py_InitModule("samp1", no_methods); > PyObject_SetAttrString(self, "samp1", (PyObject*)&samp1_t); > } > > > Now of course running python setup.py in this dictionary builds > and installs extension module samp1. Let's look at it in action: > > [alex at lancelot extype]$ python > Python 2.2.1 (#2, Jul 15 2002, 17:32:26) > [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import samp1 > >>> examp = samp1.samp1() > >>> examp + 'ciao!' > (, 'ciao!') > >>> 'salute...' + examp > ('salute...', ) > >>> > > See what's going on? Despite the (traditional) argument names, > samp1_add is being called with the LEFT operand of + as the first > argument ('self'), the RIGHT operand as the second argument > ('other') -- your C code can test the types directly to do the > right thing in both the __add__ and __radd__ cases...! > > Sure, you CAN make do with coercion (so have all Python extension > types until about last year), but bypassing it makes things a bit > clearer, I believe. If you do want coercion in some but nor all > of your numeric-methods you can deal with it yourself -- call your > own "coercion-like" function from your methods' code as and where > appropriate. I do think it's simpler than having Python do it for > you and sometimes having to "bypass" it, so to speak... this way > you can still supply a function to be called when the user does an > explicit coerce call, and yet have whatever precise behavior you > want for all operators that look like numeric operators ("look like", > because, for example, sequence concatenation isn't really numeric -- > it just LOOKS LIKE it is, and has to live in PyNumberMethods, but > that's not quite where one might like to place it...). > > > Feel free to keep posting such questions to this list if there is > anything unclear in the above, and/or if you need any more help! > > > Alex > From megabytemonster at hotmail.com Tue Sep 24 15:42:23 2002 From: megabytemonster at hotmail.com (Stuart) Date: 24 Sep 2002 12:42:23 -0700 Subject: Using internet modules to download files Message-ID: <3ab719f7.0209241142.1bf5987@posting.google.com> I have a slight problem. The college which I attend has broadband access for everyone, but unfortunately insists upon placing a firewall between the pupils and downloads, therefore this fast connection is wasted upon retrieving HTML files. I merely want to use the broadband to download a few more python libraries, such as win32all, as my home pc doesn't have internet access. I have been experimenting with Python's internet protocols, in particular with trying to retreive files while bypassing the firewall. I am not sure, however, which modules to use (i am a relative python neophyte). I first tried with urllib, but that unforunately merely routes you throught the webbrowser, which of course, promptly blocks any attempt. Are then any modules which will bypass the browser/firewall, and allow you to download a file directly through the script? Any advice (especially samples of code) would be greatly appreciated. Thanks, Stuart From tjreedy at udel.edu Tue Sep 17 18:31:21 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 17 Sep 2002 22:31:21 GMT Subject: subclassing tuple References: Message-ID: "Douglas Zongker" wrote in message news:H2LMGE.1JBF at beaver.cs.washington.edu... > I could do this with lists instead, but that means changing a lot of > existing code that expects tuples (and I don't want these objects to > be mutable!) You might get what you want by starting with a list, doing your custom modifications, and then 'return tuple(mylist)' or subclass thereof. TJR From Padraig at Linux.ie Fri Sep 13 09:23:35 2002 From: Padraig at Linux.ie (Padraig Brady) Date: Fri, 13 Sep 2002 13:23:35 GMT Subject: [newbie] Buying an introductory/reference text References: Message-ID: <3D81E6B0.3070404@Linux.ie> Brad Fonseca wrote: > Greetings! > > I'm looking for a few opinions on the above subject. I'm a computer > science student who has had some introductory lectures on Python and I've > done some very basic mucking around with. I'm looking for a clear > reference and/or introductory text. I've only been doing python for a few days myself with just online docs, which I find excellent. If you want a treeware reference, have a look @: http://www.accu.org/bookreviews/public/reviews/0sb/python.htm P?draig. From jdavis at empires.org Tue Sep 24 05:41:30 2002 From: jdavis at empires.org (Jeff Davis) Date: Tue, 24 Sep 2002 09:41:30 GMT Subject: Downloading huge files via urllib References: Message-ID: Hi, It's certainly possible. urllib is meant as a high-level interface that hides those kind of details. Perhaps you could find a way to make it work, but I would suggest using the socket module and create a socket and use SSL. Then you can read an arbitrary number of bytes from the socket at a time. That way, you can be sure to never take in more than, say, 500 bytes at a time, preventing your MemoryError. Note that there is a warning in the docs for socket.ssl(): "Warning: This does not do any certificate verification! " I think that just means that it doesn't check with a certificate authority, so you'll have to do your own verification of the certificates involved. But read up if security is a concern of yours (which it is, otherwise you wouldn't be using SSL). Regards, Jeff VanL wrote: > Hello, > > For various reasons, I have to use https to download large (20+ MB) text > files which I then parse. I set up a basic function to do this using > urllib: > > response = urllib.urlretrieve(serverURL, 'run.log') > > However, I then get a MemoryError. Tracking down the source of the > error, I see the offending function in httplib: > > def makefile(self, mode, bufsize=None): > """Return a readable file-like object with data from socket. > > This method offers only partial support for the makefile > interface of a real socket. It only supports modes 'r' and > 'rb' and the bufsize argument is ignored. > > The returned object contains *all* of the file data > """ > > I think the problem is that bufsize argument that is ignored. Does > anyone know if this is correct, and what I can do about it? I would > like to automate the process of downloading this file, but is it > possible? > > Thanks, > > VanL From mal at lemburg.com Thu Sep 19 13:30:20 2002 From: mal at lemburg.com (M.-A. Lemburg) Date: Thu, 19 Sep 2002 19:30:20 +0200 Subject: ANN: eGenix.com mxODBC Python Database Interface Version 2.0.5 Message-ID: <3D8A09AC.5060203@lemburg.com> ________________________________________________________________________ ANNOUNCING: eGenix.com mxODBC Database Interface for Python 1.5.2 - 2.2 Version 2.0.5 Full Source Python extension providing ODBC connectivity to Python applications on Windows, Unix abd Linux ________________________________________________________________________ WHAT IS IT ?: The mxODBC Database Interface allows users to connect from Python to just about any database on the market today, on Windows, Unix and Linux -- using just one interface to program against for all supported databases and platforms. This makes mxODBC the ideal basis for writing cross-platform database programs and utilities. mxODBC is included in the eGenix.com mx COMMERCIAL Extension Package for Python, the commercial part of the eGenix.com mx Extension Series, a collection of professional quality software tools which enhance Python's usability in many important areas such as ODBC database connectivity, fast text processing, date/time processing and web site programming. See http://www.egenix.com/ for details. ________________________________________________________________________ WHAT'S NEW ? The 2.0.5 version introduces work-arounds for bugs in various ODBC drivers to enhance the compatibility of mxODBC with Unicode-aware ODBC drivers such as the latest MS Access and MS SQL Server drivers. ________________________________________________________________________ EGENIX.COM MX COMMERCIAL PACKAGE OVERVIEW: mxODBC - Generic ODBC 2.0-3.5 interface for Python mxODBC is an extension package that provides a Python Database API compliant interface to ODBC capable database drivers and managers. In addition to the capabilities provided through the standard DB API it also gives access to a rich set of catalog methods which allow you to scan the database for tables, procedures, etc. Furthermore, it uses the mxDateTime package for date/time value interfacing eliminating most of the problems these types normally introduce (other in/output formats are available too). mxODBC allows you to interface to more than one database from one process, making inter-database interfacing very flexible and reliable. The source version includes a varity of preconfigured setups for many commonly used databases such as MySQL, Oracle, Informix, Solid, SAP DB, Sybase ASA and ASE, DBMaker and many more. The precompiled versions for Windows and Linux include the interfaces to the standard ODBC manager on these platforms to allow for a more easily configurable setup. More details are available at: http://www.egenix.com/files/python/mxODBC.html ________________________________________________________________________ WHERE CAN I DOWNLOAD IT ? The download archives and instructions for installing the package can be found at: http://www.egenix.com/files/python/eGenix-mx-Extensions.html#Packages Note that in order to use the eGenix.com mx COMMERCIAL package you will first need to install the eGenix.com mx BASE package which can be downloaded from the same location. ________________________________________________________________________ WHERE CAN I BUY LICENSES ? mxODBC is free for non-commercial use. Commercial users have to buy licenses for continued use after a 30-day evaluation period. Special licensing setups are available for commercial product developers. Please see http://www.egenix.com/files/python/eGenix-mx-Extensions.html#BuyLicenses for details. ________________________________________________________________________ WHERE CAN I GET SUPPORT ? Commercial quality support for these packages is available from eGenix.com. Please see http://www.egenix.com/files/python/eGenix-mx-Extensions.html#Support for details about our support offerings. ________________________________________________________________________ Enjoy, -- Marc-Andre Lemburg CEO eGenix.com Software GmbH _______________________________________________________________________ eGenix.com -- Makers of the Python mx Extensions: mxDateTime,mxODBC,... Python Consulting: http://www.egenix.com/ Python Software: http://www.egenix.com/files/python/ From fperez528 at yahoo.com Thu Sep 12 12:09:43 2002 From: fperez528 at yahoo.com (Fernando =?ISO-8859-1?Q?P=E9rez?=) Date: Thu, 12 Sep 2002 10:09:43 -0600 Subject: Anyone got a logfile script? - Help a n00b References: <3D806151.9020707@Linux.ie> Message-ID: Daniel Stuart Kelly wrote: > Thanks for the quick answer P?draig. > > The context grep will pull back all the instances of the variable.. The > variable in this case is a unique user ID. The ID will be in the log file > multiple times for different actions that the user performs which are being > logged.... > > I want to be able to search for specific actions.. Ie connections, > disconnections, config changes. and not for every action that the user has > performed. > > Will Grep do this for me? $ grep ID file | grep action Think of it as an 'AND' grep implemented with a pipe. Cheers, f From marklists at mceahern.com Fri Sep 13 11:43:21 2002 From: marklists at mceahern.com (Mark McEahern) Date: Fri, 13 Sep 2002 10:43:21 -0500 Subject: Restricting methods in derived classes In-Reply-To: Message-ID: Huaiyu, I feel compelled to gently ask, "What's the point of this rigamarole?" Cheers, // m From dsavitsk at e-coli.net Sat Sep 14 22:30:34 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Sun, 15 Sep 2002 02:30:34 GMT Subject: representing a literal single slash References: Message-ID: "Jonathan Claggett" wrote in message news:dd5454fb.0209141828.1ad24260 at posting.google.com... > Here is an easy question (I'm hoping). > > I'm trying to process a string so that all doubled up backslashes (\\) > are replaced with a single backslash (\). > > The obvious approach doesn't work since a single backslash can't end a > string: > > str = str.replace('\\', '\') # broken in the above you are replacing a single slash with, well, with nothing. try >>> str = str.replace('\\\\', '\\') # broken -d From eugene1977 at hotmail.com Sun Sep 15 04:36:30 2002 From: eugene1977 at hotmail.com (eugene kim) Date: Sun, 15 Sep 2002 08:36:30 +0000 Subject: python + java for web development? Message-ID: hi.. i'm a python beginner, used java for about an year we will develop a website for a semester(i'm a student) our group members are all familiar with java, but not python.. probably, our main language will be java.. but java is really painful sometime , like database access and i'd like to use python when python is much easier since java passes objects , not just strings among servlets and jsps i'm wondering if it is possible to mix java and other language.. for example if servlet processes database work, and passes the result as ArrayList type and jsp takes ArrayList to display the results. how python can interact with these servlet/jsp..? thank you a lot From eric.brunel at pragmadev.com Tue Sep 3 03:57:16 2002 From: eric.brunel at pragmadev.com (Eric Brunel) Date: Tue, 3 Sep 2002 09:57:16 +0200 Subject: getch in python References: <75ca4e69.0209022326.4cde72e8@posting.google.com> Message-ID: Venkat Venkataraju wrote: > Hi All > > Is there any function that behaves like getch() function in C? > > Venkat Seems like this is what you want: import sys c = sys.stdin.read(1) On EOF, c is just ''. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From michael at stroeder.com Wed Sep 18 12:00:49 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 18 Sep 2002 18:00:49 +0200 Subject: Python-style license? Message-ID: HI! In some Python modules there's only a note about a "Python-style license". Now I wonder what that means. Any clues? Ciao, Michael. From pedronis at bluewin.ch Wed Sep 4 17:29:44 2002 From: pedronis at bluewin.ch (Samuele Pedroni) Date: Wed, 4 Sep 2002 23:29:44 +0200 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> <3d765ce6_4@news.bluewin.ch> Message-ID: <3d767c4a$1_1@news.bluewin.ch> Robin Becker wrote in message zzKd7KAqhnd9EwxT at jessikat.fsnet.co.uk... > ..... > it, test_pdfbase_ttfonts.py doesn't look as though it's doing anything > particularly odd, certainly I see no references to system/spawn in > there. > -- have you tried my little program with your JVM. If my program work as for me, that means that your py plus jython trigger a bug of the JVM, because anyway and in any case the JVM ought to scream "out of memory" well before eating a 1GB of memory. regards. From gerhard.haering at opus-gmbh.net Thu Sep 19 04:20:21 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 19 Sep 2002 08:20:21 GMT Subject: Code analyser + testing References: Message-ID: Julien Anguenot wrote: > Hi !, > > I'm looking for a code analyser for Python 2.2. PyChecker! > I'm student and I have to find a software (in Python of course) for setting > tests. (unit testing, etc....) Python has two integrated unit testing frameworks in the 'unittest' and 'doctest' modules. I personally use unittest. -- Gerhard From nospam at bigfoot.com Fri Sep 6 19:23:31 2002 From: nospam at bigfoot.com (Gillou) Date: Sat, 7 Sep 2002 01:23:31 +0200 Subject: old ODBC module References: Message-ID: Google for "Mark Hammond win32 python extensions". It's in the package. --Gilles mailto:gilles at pilotsystems.net "ryan" a ?crit dans le message de news: f5ae9.2146$Qx1.35346 at news1.telusplanet.net... > Does anyone know where I can find the old free odbc module? Not the > mxODBC module, but the other (apprently not very well supported) one. > I've been looking for a while without success. Thanks! > > ryan. > From hwlgw at hotmail.com Sun Sep 1 16:47:46 2002 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 1 Sep 2002 13:47:46 -0700 Subject: Dead Man Timer? References: Message-ID: "Graham Ashton" wrote: > > Need to detect a stalled process. > > > There may be a better way, but you could try using signal.alarm() to set > an alarm. Your process should be interrupted by a signal when it is > received. If your write operation works you can cancel the alarm > immediately. > > This will probably work much better on *nix than on windows (for which > there will be better alternatives, I'm sure). I am interested in a Windows solution! Anybody? :: Who does not trust enough will not be trusted. -- Lao Tse From dsavitsk at e-coli.net Wed Sep 11 22:35:12 2002 From: dsavitsk at e-coli.net (dsavitsk) Date: Thu, 12 Sep 2002 02:35:12 GMT Subject: ntpath bug or expected? References: Message-ID: wrote in message news:mailman.1031795954.4770.python-list at python.org... > On Thu, Sep 12, 2002 at 01:18:21AM +0000, dsavitsk wrote: > > python 2.1.3. this is pretty minor ... os.path.join() on win32 fails if the > > first path component is C: (or any other letter). that is, if the first > > component is a drive letter, it must contain either '\\' or '/' or else the > > path is wrong. this makes it the only component which must have slashes. > > > > example > > >>> os.path.join('C:', 'path', 'to', 'file.txt') > > C:path\\to\\file.txt > > Sure. This is the file on drive C which is in the relative path > "path\\to\\file.txt" from the current directory of drive C. > it seems to me, i guess, that being inconsistent here and in os.getcwd in a consistent way is confusing. if getcwd returned C: instead of C:\\ (as it returnes C:\\path and not C:\\path\\) then os.path.join(os.getcwd(), 'path', 'file.txt') with my modification would do the same thing as it now does, but it would have the added bonuses of returning a full file path and removing 2 bits of necessary documentation from the language. i'll go find something better to do now. -doug > Remember, DOS maintains a separate working directory for each drive. > > A first element of C:/ would make the path absolute, and a first element of > C: would make the path relative to the current directory of C. I think > that is why > >>> ntpath.join("C:", "/path", "to", "file.txt") > 'C:/path\\to\\file.txt' > is "correct". This is the one I wonder about, though: > >>> ntpath.join("C:", "/a", "/b", "x.txt") > '/b\\x.txt' > >>> ntpath.join("C:/a", "/b", "x.txt") > '/b\\x.txt' > if the drive letter is preserved in my first example, why isn't it in the > last two? > > Jeff > From mark at mceahern.com Thu Sep 26 20:08:48 2002 From: mark at mceahern.com (Mark McEahern) Date: Thu, 26 Sep 2002 19:08:48 -0500 Subject: well-formed xml Message-ID: I'm obviously missing something because this seemingly innocent chunk of xhtml: from xml.dom import minidom s = "search" # ^ # - seems to be the problem # # maybe it thinks I'm trying to reference the &q entity? doc = minidom.parseString(s) Exception traceback follows. Is there a way for me to tell it to ignore apparent entity references inside attribute values? // m $ python junk.py Traceback (most recent call last): File "junk.py", line 5, in ? doc = minidom.parseString(s) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", line 965, in parseString return _doparse(pulldom.parseString, args, kwargs) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", line 952, in _doparse toktype, rootNode = events.getEvent() File "/usr/lib/python2.2/site-packages/_xmlplus/dom/pulldom.py", line 256, in getEvent self.parser.feed(buf) File "/usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py", line 148, in feed self._err_handler.fatalError(exc) File "/usr/lib/python2.2/site-packages/_xmlplus/sax/handler.py", line 38, in f atalError raise exception xml.sax._exceptions.SAXParseException: :1:41: not well-formed (invalid token) This is with Python 2.2.1 without PyXML installed separately. The same thing happens with PyXML 0.8.1: $ python junk.py Traceback (most recent call last): File "junk.py", line 5, in ? doc = minidom.parseString(s) File "/usr/local/lib/python2.2/site-packages/_xmlplus/dom/minidom.py", line 16 05, in parseString return expatbuilder.parseString(string) File "/usr/local/lib/python2.2/site-packages/_xmlplus/dom/expatbuilder.py", li ne 943, in parseString return builder.parseString(string) File "/usr/local/lib/python2.2/site-packages/_xmlplus/dom/expatbuilder.py", li ne 189, in parseString parser.Parse(string, True) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 41 - From aleax at aleax.it Mon Sep 30 11:19:31 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 30 Sep 2002 15:19:31 GMT Subject: Is there a way to find the name of the method currently being executed? References: Message-ID: <7YZl9.191322$pX1.6844789@news2.tin.it> Craeg K Strong wrote: > Thanks to all who responded! > > I should have known to check the python cookbook... > > One question: the sys._getframe() method is new for Python 2.1-- > how likely do you think it is to change in 2.2+ > releases? The part that worries me is that the > method starts with an underscore. That generally means > "protected/private" or "unpublished" to me. Yes, the name convention does indicate "internal". > I just want to know how safe it is to use for > general business application type programming. Not very: it's intended to be used for debugging and development purposes. If you can cleanly express your application's intent WITHOUT a function needing to know its own name, it's by far preferable to do so. If such self-knowledge is indispensable to cleanly express your application's intent, then sys._getframe is as usable as any other method -- worst case, should it go away one day, you'll have to install it in your own startup code (code to emulate sys._getframe for old Python versions is also available in the Cookbook, and most likely similar code can be cooked up in the future, as long as there's _any_ way to get such to-you-indispensable information). Alex From martin at v.loewis.de Mon Sep 30 02:01:19 2002 From: martin at v.loewis.de (Martin v. Loewis) Date: 30 Sep 2002 08:01:19 +0200 Subject: sizeof PyTypeObject difference References: Message-ID: "Tom Widrick" writes: > I'm trying to make a metatype in C, but there seems to be some difference > between the size of the type object. > > typedef struct { > PyTypeObject type; > } MyMetaObject; > > > and in the tp_basicsize field I place sizeof(MyMetaObject) the value is only > 196. This is a type declararation. In C, you cannot put values into a type declaration. So I assume you are creating a value (an object) of struct MyMetaObject, and you put 196 into this value. If so, you misunderstand the meaning of tp_basicsize: It does not describe the size of the type object, but the size of instances of the type. > This causes a core dump. That is hard to believe. Declaring the typedef alone can't cause a core dump. Defining an object of that type, and putting the value of 196 into it can't cause a core dump, either. You must be doing other things, like using the resulting object in some way, to cause a core dump. > What is the cause of this difference? The type type is really a variable-sized object. You are seeing the size of struct etype, which is hidden in typeobject.c. > And what is the "proper" way to do this? You can't currently declare a type with additional C fields, since type objects are variable-sized. One approach is to put additional things into the type's __dict__. Another approach is to use Christian Tismer's patches to overcome this limitation; I recommend that you contact Christian. Regards, Martin From aleax at aleax.it Mon Sep 23 05:17:48 2002 From: aleax at aleax.it (Alex Martelli) Date: Mon, 23 Sep 2002 09:17:48 GMT Subject: Getting started References: Message-ID: <0%Aj9.129252$ub2.2813083@news1.tin.it> James J. Besemer wrote: > > Alex Martelli wrote: > >>$a = "2.3"; >>$b = 45; >>print $a+$b; >> >>emitting 47.3 is pretty close to what I consider "weak typing". >> > > I don't see why you call this "weak typing". In Perl, the "+" operator > is defined to work with strings or numbers. It's defined to work *INDIFFERENTLY* on numbers, or on strings that look like numbers, "ignoring" the types of the operands. Since most (all?) operations are designed to ignore the operands' types, this makes those types much weaker than they would be in languages where the operands' types are respected. > It may seem more confusing Not at all: to the typical newbie, it seems LESS confusing to be allowed to ignore the differences between numbers and strings, because the significance of the types is so weak. Like so many other aspects of Perl, weak typing is *intended* to be a handy convenience for the user. It turns out NOT to be, IMNSHO (or else I'd still be using Perl, no?-), because it ends up as a collection of trips and pitfalls. E.g., if $b erroneously turns out to be "hello world!", $a+$b silently and transparently masks the error by treating $b just as if its value was 0. By masking all kinds of such errors, weak typing makes debugging large programs a nightmare (in my experience with Perl -- extensive, though old enough to be mostrly pre-Perl 5 -- and in my experience with other weakly typed languages such as Basic dialects). > at first if you expect "+" also to be the string concatenation operator, > which it is not. In the above example, > > print $a . $b; > > will print the string "2.345". String concatenation has little to do with it. I have no special problem against a "stringize and concatenate" operator. I'm not a "strong-typing evangelist" -- I'm a pragmatist and my experience tells me that a "stringize and whatever" operator is not especially error-prone, no more than, say, the rough Python equivalent "%s%s" % (a, b) would be. > This all is no different in principle from Python's: > > a = 2.3 > b = 45L > print a + b Wrong! It *is* VERY different in principle to have a hierarchy of types such that "A is usable where B is required" (often called A IS-A B: a special, type-safe case of polymorphism -- but such an important special case that many modern languages HINGE on it, and almost all languages accept some version of it, possibly limited to numerics), rather than having specific operators that "treat both operands as A" vs "treat both operands as B". The former is NO weakening of typing, in principle. The latter is. I'm somewhat surprised at seeing you make such assertions at obvious variance with type theory -- I thought you had a solid CS background (stronger than my own -- I'm just an engineer, more interested in pragmatics than in theory). We _do_ share the fundamentals, I hope? E.g., my favorite "essential Luca Cardelli bibliography": Cardelli, Wegner, "On understanding types, data abstraction, and polymorphism", ACM Computing Surveys 1985 Cardelli, "Type Systems", in "Handbook of Computer Science and Engineering", CRC Press, 1997. Cardelli, "Typeful programming", in "Formal Description of Programming Concepts", Springer-Verlag, 1989 Abadi, Cardelli, Pierce, Plotkin. "Dynamic typing in a statically-typed language", ACM Transactions on PLS, April 1991 Abadi, Cardelli, Pierce, R?my, "Dynamic typing in polymorphic languages", Journal of Functional Programming, January 1995 Abadi, Cardelli, Viswanathan, "An interpretation of objects and object types", Proceedings POPL 1996 > and getting 47.3. The "+" operator is defined for floats and also for > longs. Since they're all "numbers" it would seem really strange if they > did not interact naturally like this. But fundamentally they're Indeed it would; as far as I know, the CAML dialect of ML (also in the O'Caml extension, last I looked) is one of the very few programming languages that doesn't have a polymorphic + operator -- you have to use + for integers only, +. for floating-point. As I recall some dialects of Forth had a similar lack of polymorphism for the *opposite* reason -- typing so weak that once data was on the stack the system had no idea any more about how it had to be taken, FP or integer -- CAML (but not Standard ML, if I recall correctly) ends up in the same place as a kind of reductio ad absurdum of VERY strong vs weak typing ("the extremes meet":-). "Promotion" rules are (or should be) simple: whenever (e.g.) a float is required, an integer is accepted instead and gets promoted to a float transparently and implicitly (ideally without loss of information -- in practice, since longs are represented by unbounded numbers of bits and floats aren't, the "without loss of information" is only an ideal). Operator / used to be a notable exception -- fortunately, that notable exception is at long last going away. As everybody but CAML's designers seem to acknowledge, such polymorphism in no way weakens typing (in a formal sense, as per the above bibliog, this only holds under the constraint of no-information-loss). Perl's treatment of arithmetic operators cannot be framed this way, nor made consistent with typing theory: it's _weak_ typing, not just _dynamic_ typing. > Anyway, why should "2" + 5 == "7" be all that much stranger than "2" * 5 > == "22222"? If the operation is unambiguous and useful what rule would > it break? As I already said, newbies do appear to like the idea of confusing numbers and strings -- in that sense, such weak typing may be taken as the reverse of "much stranger"... it's what most beginners seem to expect (take a tour of duty on the help hotline to get a very good sample of beginners' misconceptions and problems...:-). But experience with Perl (and other weakly typed languages) shows that such crucial weakening of typing, by hiding mistakes, is a serious burden to bear in developing and maintaining large programs. The rule broken is that the implicit-conversions directed graph must be acyclic -- if type A can be implicitly converted to B, then B cannot be implicitly converted to A. It would (I suppose) be possible to build a consistent (strong) typing system where all strings can be implicitly converted to numbers, but only if no numbers where ever implicitly converted to strings (so, for example, the print statement as it stands in Python today would have to disappear -- more relevantly, so would the %s format specifier's ability to apply to any object). Personally, I think that would be absurd, but I don't think it would break the rules (as long as information loss in the conversion could somehow be contained -- which I think means the conversion rule would have to be something like "treat as a base-256 number with the char's ordinal values as digits"... forget "1.0" being treated as the number 1...!-). Incidentally, the DAG-rule also explains why it's a good idea to have a[b] raise an exception if b is floating -- since ints become floats implicitly, the reverse should not hold. I'm not claiming that Python is 100%-perfect is this (as it's not in information-loss terms, see above), but I think it strikes a roughly reasonable pragmatic compromise. The int/long situation is interesting, and shows why the unification of those two types (currently ongoing) IS most likely a good idea -- we do want them to offer the same "interface" to the rest of the program, with the only diistinction being one of how they're implemented internally; wanting them totally interchangeable means we should thus have just one type (with two different implementations -- no problem with that). I expressed different opinions in the past, but framing things in terms of type theory helps me change my mind:-). Personally, I think Python would be improved slightly by > adding this conversion. It's convenient and there's ample precedent in > other languages (Awk, Snobol, Icon, Perl, etc.). But I am sure that > notion will provoke howls of protest from the True Believers. The only reason I'm sniggering rather than howling is that I'm confident that this (expletive deleted) proposal will never be implemented in Python. > There are a lot of reasons why Python is better than Perl but strongly > vs. weakly typed is not one of them. I don't see a material difference > in the "strength," per se, of typing between Perl and Python. They're Then you are not looking at things in the right way. Maybe you do need to refresh your knowledge on type theory. Python (and Smalltalk) are much more suitable than Perl (awk, Snobol, etc) to implement large programs, apart from all other differences, exactly *because* typing is stronger in Python and Smalltalk than in those other languages. > Getting back to the original question, the quintessential example of > "weak typing" is in old C or Fortran where you can define a function to > take, say, a string argument but are allowed instead pass in a real or a In the Fortran language (Fortran IV and Fortran 77 -- the versions of Fortran of which I had to become a guru: I have no deep knowledge of earlier or later versions) you are NOT allowed to pass a real to a function that wants (e.g.) an integer (no strings in Fortran IV). If you do so, your program's behavior becomes undefined. No compilers that I know of actually *diagnosed* this programming mistake (hmmm, perhaps Waterloo Fortran did -- that WOULD be quite consistent with its didactic orientation -- but it's been too many years since I last used it, so I don't recall), but that's quite another issue compared to how the LANGUAGE is defined. "Old C" was never precisely specified, so that knowing what was in fact an error leading to undefined behavior which a given compiler could not diagnose is harder; taking lint as part and parcel of the language, as I recall was advised by C's authors and/or main practitioners, then again we can say that such mismatches were NOT allowed. > pointer to a struct and get garbled results or even corrupt the program: > > printf( "%s\n", 2.5 ); // possible program fault Variadics are indeed a problem (gcc diagnoses this -- but wouldn't if you didn't use a constant as the format). > Another example is all too familiar to MFC programmers: > > CEdit* edit = (CEdit*)GetDialogItem( ID_FOO ); > > GetDialogItem() essentially returns a raw pointer. The programmer is > required to explicitly cast the pointer into the proper type, the same > type as the dialog item identified by the numeric ID. However, if the > dialog item itself changes, say, from an Edit box to a List box then the > cast becomes wrong, some operations on edit may fail catestrophically, > and -- worst of all -- the compiler cannot detect and diagnose this > error for you. > > These types of errors are not possible in Python or Perl, which > illustrates that they're both "strong". Yes, this is a good example of the dangers of (old-style) casting. Of course, you could (and probably should) just assign to a plain CWnd* (no raw pointer involved: it's a pointer to the base class), then check it's indeed a CEdit* before you proceed, but in practice programmers DO perform unchecked downcasts and come to grief thereby. > Curiously, in Python > > print "%s" % 2.5 > > prints the string "2.5" instead of, say, raising an exception. So > there's some small precedent for treating numbers as strings in a string > "context" even in Python. See above: in a sense, it's exactly BECAUSE we _want_ to have operations that "transform into a string then ...", that theory tells us the _reverse_ (making the types-DAG into a graph with loops) is a disaster. Incidentally, Java (strongly AND statically typed) does that, for strings specifically, too (using the toString method, like Python uses __str__). > I'll go out on a limb and say that most "dynamic typed" languages are > also "strong" by necessity. If the user isn't keeping track of the > types then the system HAS to. An exception I can think of would be an > ancient dialect of Lisp where integers also were machine addresses and > thus callable without restriction. E.g., if a function name evaluated > to a number the interpreter performed a subroutine call to that address > instead of, say, applying a lambda. It was the mechanism through which > system builtins were accessed. However, nothing prevented a user from > "calling" an arbitrary integer and leaping off into never never land. Yep, that's pretty weak typing indeed -- Forth-ish, I would say. But you miss the essential distinction: what DRIVES typical ops, the types of the objects involved, or the operators &c that the programmer has coded? In a strongly-typed language, types drive. In a weakly-typed language, operators (or the equivalent thereof) drive. It's not a black-and-white issue, but it's the key distinction. In your "weak Lisp" example, the "call this thing" operator (so to speak: not _syntactically_ an operator, but that matters not) drives. Recall your question up above...? > If the operation is unambiguous and useful what rule would > it break? I think you've given a good example of why, even though the definition WAS unambiguous (if it's an integer, unambiguously this happens) AND useful (e.g. to call system builtins), this weak Lisp was not optimally designed for practical use, particularly in the development and maintenance of large programs. >>find it very hard to produce substantial, large programs using >>weakly-typed languages. >> > Given my definition of "weakly typed," I agree it's more difficult than > in strongly typed languages. > > On the other hand, isn't it the case that much of Python is implemented > in C, which is weakly typed? So "weakly typed" makes it harder but not > impossible, at least not for some. Why, sure. HUGE programs have indeed been developed even in assembly language, after all (they may be riddled with so many bugs to put an ant-hill to shame, maybe, but they're still in use:-). C has been used (IS still in use today) to develop more and larger programs than other languages. That most of them could have been developed and could be maintained with 1/10 the effort in Python is another issue. Human ingenuity (and stubbornness) is strong enough that any claim that some intellectual-work endeavour is "impossible" (to a sufficient number of sufficiently-motivated human beings, with unbounded amounts of cash to keep them going:-) had better be backed by a very solid mathematical proof...:-). >> Python is strongly, albeit dynamically, typed, >> > FWIW, so is Perl. Nope: see all of the above. Alex From just at xs4all.nl Thu Sep 12 05:09:27 2002 From: just at xs4all.nl (Just) Date: Thu, 12 Sep 2002 11:09:27 +0200 Subject: iterators and generators, is this the Python Way??? References: <3D7FF921.2040305@one.net> <3D804B79.9070003@one.net> Message-ID: In article <3D804B79.9070003 at one.net>, Michael Schneider wrote: > Thank you very much, I like this approach. > > I was under the mistaken impression what the > iterator needed to do. Hm, I didn't think so: __iter__ needs to return an iterator, and that's exactly what you did. It's just that I find it a really nice idiom to have __iter__ *be* a generator, it's really nice and compact. Just From fgeiger at datec.at Thu Sep 19 01:55:08 2002 From: fgeiger at datec.at (F. GEIGER) Date: Thu, 19 Sep 2002 07:55:08 +0200 Subject: Need advice on choosing the technology for intranet based application References: <3d88fd1e@news.ivm.net> Message-ID: <3d8966ab@news.swissonline.ch> "Nenad Propadovic" schrieb im Newsbeitrag news:3d88fd1e at news.ivm.net... > So I kindly ask for knowledgeable opinions on the following question: > -which web/application server? I'm considering Zope (seams rather BIG when > you download & unpack it, and it seams all possible web applications have > been written for it) and twisted (smaller, seams lower lewel and somewhat > easier to learn), and I'm wondering if there is something else out there, > which is both powerfull and flexible and easy to learn and complete. Oh yes, Probably you should consider Webware too. It was written by and for people, who have been frustrated by Zope. In Webware you get results pretty fast. There is an rel/obj mapper (MiddleKit), which makes DB handling very easy. Regards Franz From phr-n2002b at NOSPAMnightsong.com Mon Sep 30 02:36:50 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 29 Sep 2002 23:36:50 -0700 Subject: Decimal arithmatic, was Re: Python GUI app to impress the boss? References: <7xd6qwqtgz.fsf@ruckus.brouhaha.com> <7xelbcgo56.fsf@ruckus.brouhaha.com> <7x65woks0i.fsf@ruckus.brouhaha.com> Message-ID: <7xit0oj859.fsf@ruckus.brouhaha.com> "Chris Gonnerman" writes: > > With decimal arithmetic, you get $2.97 the first way and > > $3.00 the second way. > > Excellent example, wrong focus. The business user (in this > case, the retail store owner/manager) would define which > method, and which results, are right. The second mode is > the "canonical" way in the manual system, but lately I've > realized that many (most?) retail POS systems can do it "both" > ways, handling single items by a variation of method 1 which gives answers > consistent with method 2. > > I'm glad I didn't have to write and debug that code. I'm really skeptical that any "business user" can specify a set of rules that gets all this stuff straight for a complex business involving cents-off coupons, percentage advertising discounts, etc. It sounds much more complicated than what we usually call software implementation, and it sounds like it has to be done differently for every business situation. They're almost certainly better off using some method that gives consistent results at the end. I worked on one business application where the vendor felt that any floating point roundoff errors were unacceptable. He had me implement exact rational arithmetic (easy in Python using the gmpy package). All intermediate results were represented as exact integer ratios, so you were guaranteed that 3 * (1/3) == 1. This was not the same as decimal arithmetic. You would never get $2.97 as an answer for the banana problem. But I don't think any customers complained. From whisper at oz.net Sat Sep 28 04:17:12 2002 From: whisper at oz.net (David LeBlanc) Date: Sat, 28 Sep 2002 01:17:12 -0700 Subject: Dirt simple tkinter editor example Message-ID: Can someone point me at one? Ideally, it would support a few text styles (bold, italic...) and not much else. I'm looking for a working howto example. TIA, David LeBlanc Seattle, WA USA From tdelaney at avaya.com Wed Sep 25 19:50:41 2002 From: tdelaney at avaya.com (Delaney, Timothy) Date: Thu, 26 Sep 2002 09:50:41 +1000 Subject: Decimal arithmatic, was Re: Python GUI app to impress the bos s? Message-ID: > From: danb_83 at yahoo.com [mailto:danb_83 at yahoo.com] > > "Stuart D. Gathman" wrote in message > news:... > >... > > There ought to be severe penalties for idiots that use > floating point > > dollars for financial applications. If forced to use floating point > > (e.g. because customer demands BASIC), then keep money amounts in > > whole pennies (or whatever the smallest currency unit for > the country > > is), and divide by 100 (or whatever) for printing only (or > just add the > > decimal point yourself). > > That's exactly how things were done at my old workplace, except that > cents were also used for user input. Most of the time. It's called Fixed Point arithmetic, and strangely enough, Tim Peters wrote an excellent implementation ... Tim Delaney From ark at research.att.com Mon Sep 2 10:40:23 2002 From: ark at research.att.com (Andrew Koenig) Date: Mon, 2 Sep 2002 14:40:23 GMT Subject: stylistic question -- optional return value References: <20020828145828.19131.h014.c001.wm@mail.dougfort.net.criticalpath.net> Message-ID: Bengt> If added information is the exception (;-) rather than the Bengt> rule, you might want to consider using an exception to return Bengt> the unusual bag of data. Unfortunately, it's not. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From loewis at informatik.hu-berlin.de Sun Sep 15 15:27:04 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 15 Sep 2002 21:27:04 +0200 Subject: Will xml.dom work with HTML docs? References: <877khntzvt.fsf@pokey.henrik-motakef.de> <871y7vnm9q.fsf@pokey.henrik-motakef.de> Message-ID: Henrik Motakef writes: > Does it do so by using an actual DTD, or is HTML-specific knowledge > hardcoded in it? > > I.e. could this feature be used with other document types? It's hard-coded (for HTML 4). The support code is generated (as a set of dictionaries), so you could probably port it to another DTD; I believe there are constraints to the DTD (i.e. you might need to losen the content model). Regards, Martin From brueckd at tbye.com Mon Sep 9 11:02:57 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Mon, 9 Sep 2002 08:02:57 -0700 (PDT) Subject: Larry Wall's comment on python... In-Reply-To: Message-ID: On 8 Sep 2002, Brian Slesinsky wrote: > He's repeating the standard newbie complaint. However, I think the > fact that so many people have repeated this for so long is > significant. Long-term Python programmers tend to forget how weird it > is to some newcomers to end a function or class just by *stopping*. > It feels abrupt and rather fragile, particularly when you don't have a > firm grasp of the language. If newbies have complained for this long, > the complaint's not going away, and if we're serious about making > Python easy to pick up it might be good to listen. Yes, the fact that so many newbies complain about it is very significant. Perhaps we need to do a better job of presenting the concept. For example, instead of tossing it out there and then defending against complaints perhaps it would be better to take the offensive: first make a case for why the "normal" way to delimit blocks has its drawbacks, and then present the Python way as a solution to a problem. But just because people consistently complain about something does not mean the answer is to bow to their wishes. From an arrogant point of view, they're newbies, so what do they know? ;-) Seriously though, I enjoy Python because it _is_ different - and I usually derive benefit from the ways in which it is different (i.e. - it's not different for arbitrary or random reasons). It's significant that lots of newbies complain about "no curly braces", but it's as least as significant that once people use it for awhile they tend to end up liking it. > Of course it's unnecessary and should be entirely optional. Putting > an "end" after every block would certainly be overly verbose and bad > style. But ending major blocks in a way that's syntax-checkable might > catch the occasional indentation error and/or make error messages Well, as you know you can always do an "# end" comment which really gives much of the same benefit. At the bottom of my Emacs window it tells me which block I'm closing (e.g. "Closes block: ...try:"), other editors probably do the same. Also, it seems like whenever it's not readily apparent which block I'm in, then the _real_ problem is sloppy code on my part. -Dave From christophe.grimault at sacet.com Tue Sep 3 06:40:07 2002 From: christophe.grimault at sacet.com (Christophe Grimault) Date: Tue, 03 Sep 2002 10:40:07 +0000 Subject: Pb with libglade and gtk Message-ID: <3D749187.F2F1A61E@sacet.com> Hi all, I 've a UI created with glade, and when I try to run it [python2 on redhat7.3] I get : Traceback (most recent call last): File "./run.py", line 3, in ? import libglade File "/usr/lib/python1.5/site-packages/libglade.py", line 11, in ? class GladeXML(_gtk.GtkData): AttributeError: 'module' object has no attribute 'GtkData' A fix for this problem ? Thanks in advance CG -------------- next part -------------- A non-text attachment was scrubbed... Name: christophe.grimault.vcf Type: text/x-vcard Size: 271 bytes Desc: Carte pour Christophe Grimault URL: From ark at research.att.com Tue Sep 3 09:20:50 2002 From: ark at research.att.com (Andrew Koenig) Date: Tue, 3 Sep 2002 13:20:50 GMT Subject: stylistic question -- optional return value References: <30292041.0209012344.ab2d4@posting.google.com> Message-ID: Bengt> What about defining a class to represent the "data structure," Bengt> and passing a reference to an instance of that to your various Bengt> routines, so that they can populate the structure themselves Bengt> (via methods/attributes/properties as convenient) instead of Bengt> returning data for a caller to do the populating with? That's certainly a possibility, but it's a little heavyweight. Of the various alternatives I've heard so far, the one I like best is simply using None to represent the optional information. That is, I return either (x, y) or (x, None) depending on whether y exists. Bengt> BTW, you mentioned recursion in another part of the thread. Is Bengt> that as in recursive descent? An exception is an interesting Bengt> alternative way to return a first match, with no need to return Bengt> anything from unsuccessful visits. Yes, it is a species of recursive descent. What I'm doing, though, is returning generators at each stage. That way I cover all of the possibilities. -- Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark From peter at engcorp.com Mon Sep 2 18:52:01 2002 From: peter at engcorp.com (Peter Hansen) Date: Mon, 02 Sep 2002 18:52:01 -0400 Subject: Why it is so dramatical? References: <200209021107.25761.b.maryniuk@forbis.lt> <3D73E035.2040300@nospam.attbi.com> Message-ID: <3d73eb74@news.sentex.net> djw wrote: > holger krekel wrote: > >> If you have something like this in a loop it's often >> *much* better to work with a list and later do a >> "".join(stringlist) >> >> As you observed yourself this is around 100-1000 times faster. >> And consider: if strings were not immutable but modified in-place >> (like lists) you couldn't use them as dictionary keys. >> if-it-hurts-don't-do-it-ly, yours Holger >> > > Stupid question: It's only a stupid question if you didn't expect this relatively common answer to such questions: "feel free to contribute a patch"... :-) > If ""join() is 100-1000 X faster, why doesn't the Python interperter > translate s = s1 + s2 + ... into s = "".join( [ s1, s2, ... ] ) > automatically? In cases like this, you need to know that Python is so dynamic that the compiler cannot know that the items being added are strings until runtime. The "".join() convention does not work well if the items in the sequence are not already strings. If you feel compelled to suggest that the compiler could at least do that for constant strings, see my first point above. :-) -Peter From bokr at oz.net Tue Sep 17 14:56:50 2002 From: bokr at oz.net (Bengt Richter) Date: 17 Sep 2002 18:56:50 GMT Subject: raw post data References: Message-ID: On Tue, 17 Sep 2002 06:52:08 GMT, Alex Martelli wrote: >:B nerdy wrote: > >> how could i make it so when i read the stdin it still is there.. cause i >> use cgi.FormVariables() also > >When you instantiate class cgi.FieldStorage (there's no such >thing as cgi.FormVariables, so I'm just guessing at what it IS >that you want!) you can pass it an optional first parameter >that is a file object open for reading -- it uses sys.stdin >as the default if you don't pass the first parameter. > >Thus, the following should work (untested!): > >import cgi, sys, cStringIO > >copyInput = cStringIO.StringIO(sys.stdin.read()) >fieldStorage = cgi.FieldStorage(copyInput) > > >The raw posted data are now available as the string returned >by calling copyInput.getvalue(), and are also parsed by cgi to >obtain fieldStorage. > A nit, but it might be good to check that the environment variable REQUEST_METHOD exists and == 'POST', and to attempt to read not more than the most you expect to be able to handle, and to check that what you get with your max read is what it's supposed to be, e.g., (untested!) (you specify MAX_I_HANDLE) (inside appropriate try/except) import os ... if os.environ.get('REQUEST_METHOD') is None or os.environ.get('REQUEST_METHOD') != 'POST': raise ValueError, 'Request method not POST' if os.environ.get('CONTENT_LENGTH') is None: raise ValueError, 'Content length unspecified' content_length = int(os.environ.get('CONTENT_LENGTH')) if content_length == 0: raise ValueError, 'Content length zero' elif content_length > MAX_I_HANDLE: raise valueError, 'Content length too great: %s' % content_length copyInput = cStringIO.StringIO(sys.stdin.read(MAX_I_HANDLE)) if len(copyInput) != content_length: raise IOError, 'Data bytes read (%s) not == CONTENT_LENGTH (%s)' % (len(copyInput), content_length) ... Regards, Bengt Richter From rjones at ekit-inc.com Sat Sep 7 01:56:05 2002 From: rjones at ekit-inc.com (Richard Jones) Date: Sat, 7 Sep 2002 15:56:05 +1000 Subject: Sequence or Identity in gadfly In-Reply-To: References: Message-ID: <200209071556.05327.rjones@ekit-inc.com> On Sat, 7 Sep 2002 1:21 pm, Jeff Kowalczyk wrote: > I don't expect that it does (it would make more sense to do it in your > python code), but is there a Sequence type in gadfly so that I can make an > autonumber for ID columns similar this postgres code?: There's no sequence support built in - you'll have to write a little bit of Python code to generate the sequence an hook it into gadfly. This was asked a while ago, and Anthony Baxter replied: http://groups.google.com/groups?selm=mailman.1030335699.8153.python-list%40python.org Richard From borcis at removethis.infomaniak.andthis.ch Fri Sep 20 11:50:52 2002 From: borcis at removethis.infomaniak.andthis.ch (Boris) Date: Fri, 20 Sep 2002 17:50:52 +0200 Subject: Python expression (Re: Iraq's offer to readmit arms inspectors) References: <3D86FF01.FE0CECC5@geneva-link.ch> <3d87069c.34652637@news.rcn.com> <3D871316.AA1E8FFC@geneva-link.ch> <3d882cd4.9181792@news.rcn.com> <3f74f974.0209180713.27889f74@posting.google.com> <3d88c258$0$707$5402220f@news.sunrise.ch> <3d89be92$0$707$5402220f@news.sunrise.ch> <3d89ee85$0$712$5402220f@news.sunrise.ch> Message-ID: <3d8b4498$0$717$5402220f@news.sunrise.ch> Terry Reedy a ?crit dans le message : B8pi9.149307$5r1.6007886 at bin5.nnrp.aus1.giganews.com... > Please remove (as I did) comp.lang.python from the list of newsgroups > for this thread. It is wildly off-topic here comp.lang.python was added because the post contained a python expression filter(lambda W : W not in 'ILLITERATE','BULLSHIT') with the miraculous property of being runnable and producing the name of the US president, Mr Bush, when executed; together with being readable as a metaphor of human behavior illustrated by "Malev" - the person that the post was responding to. Such dual interpretation of executable code is witness that Python is closer to Prolog than you would think, an interesting fact by itself for the python community. > and should never have been added. That's a dogmatic opinion that I believe lacking in justification. if-Iraq-ends-up-Waco-like-what-will-mimic-Oklahoma-City-ly yours, Boris Borcic -- assert BOA not in BAOBAB, "Paradise Mismatch Error" From newt_e at blueyonder.co.uk Thu Sep 26 17:20:31 2002 From: newt_e at blueyonder.co.uk (Newt) Date: Thu, 26 Sep 2002 21:20:31 GMT Subject: toplevel Message-ID: Hi, silly question time! In TCL, I would use set win ".win_goo_skills" toplevel $win to create a new window. How do I do the same using python/Tkinter? The toplevel command doesn't seem to accept this. Thanks, Newt From bokr at oz.net Sat Sep 7 15:27:07 2002 From: bokr at oz.net (Bengt Richter) Date: 7 Sep 2002 19:27:07 GMT Subject: None or 0 References: Message-ID: On Sat, 07 Sep 2002 17:23:00 +0200, =?ISO-8859-1?Q?Michael_Str=F6der?= wrote: >HI! > >I'm using the idiom > >a = a or b > >to get rid of statements like > >if a is None: > a = b > >Now I wonder what happens if both a and b have zero-length values. > >Trying in Python 2.2.1 reveals: > > >>> repr(0 or None) >'None' > >>> repr(None or 0) >'0' > >>> repr('' or None) >'None' > >>> repr(None or '') >"''" > >>> > >Is it guaranteed to work like this or should that be avoided? > If you want a statement that sets a to a if a is not None and otherwise b, a = a or b is not good, as you can infer from what you show above. a = (a, b)[a is None] should do it, but if a is None: a = b is better as a statement. If you need it in expression context, you could use the (a, b)[a is None] # alternatively, [a, b][a is None] or maybe def myAorB(a, b): if a is None: return b return a ... myAorB(a, b) For the following combinations, a or b obviously (when they're distinguishable ;-) always produces b, and (a,b)[a is None] always produces a except when a is None, in which case it produces b. >>> for a in [None, 0, '', [], (), {}]: ... for b in [None, 0, '', [], (), {}]: ... print 'a=%-5s b=%-8s a or b => %-8s (a,b)[a is None] => %s' % ( ... `a`, `b`, `a or b`, `(a, b)[a is None]` ... ) ... a=None b=None a or b => None (a,b)[a is None] => None a=None b=0 a or b => 0 (a,b)[a is None] => 0 a=None b='' a or b => '' (a,b)[a is None] => '' a=None b=[] a or b => [] (a,b)[a is None] => [] a=None b=() a or b => () (a,b)[a is None] => () a=None b={} a or b => {} (a,b)[a is None] => {} a=0 b=None a or b => None (a,b)[a is None] => 0 a=0 b=0 a or b => 0 (a,b)[a is None] => 0 a=0 b='' a or b => '' (a,b)[a is None] => 0 a=0 b=[] a or b => [] (a,b)[a is None] => 0 a=0 b=() a or b => () (a,b)[a is None] => 0 a=0 b={} a or b => {} (a,b)[a is None] => 0 a='' b=None a or b => None (a,b)[a is None] => '' a='' b=0 a or b => 0 (a,b)[a is None] => '' a='' b='' a or b => '' (a,b)[a is None] => '' a='' b=[] a or b => [] (a,b)[a is None] => '' a='' b=() a or b => () (a,b)[a is None] => '' a='' b={} a or b => {} (a,b)[a is None] => '' a=[] b=None a or b => None (a,b)[a is None] => [] a=[] b=0 a or b => 0 (a,b)[a is None] => [] a=[] b='' a or b => '' (a,b)[a is None] => [] a=[] b=[] a or b => [] (a,b)[a is None] => [] a=[] b=() a or b => () (a,b)[a is None] => [] a=[] b={} a or b => {} (a,b)[a is None] => [] a=() b=None a or b => None (a,b)[a is None] => () a=() b=0 a or b => 0 (a,b)[a is None] => () a=() b='' a or b => '' (a,b)[a is None] => () a=() b=[] a or b => [] (a,b)[a is None] => () a=() b=() a or b => () (a,b)[a is None] => () a=() b={} a or b => {} (a,b)[a is None] => () a={} b=None a or b => None (a,b)[a is None] => {} a={} b=0 a or b => 0 (a,b)[a is None] => {} a={} b='' a or b => '' (a,b)[a is None] => {} a={} b=[] a or b => [] (a,b)[a is None] => {} a={} b=() a or b => () (a,b)[a is None] => {} a={} b={} a or b => {} (a,b)[a is None] => {} Regards, Bengt Richter From loewis at informatik.hu-berlin.de Tue Sep 17 12:59:34 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 17 Sep 2002 18:59:34 +0200 Subject: Detecting IPv6 support References: <3D854B7D.1060209@one.net> <1032242013.2443.1329.camel@dsl-65-184-205-5.telocity.com> Message-ID: Pekka Pessi writes: > Speaking of IPv6: is the IPv6 enabled on the Pythonlabs Windows > distribution by default (sorry, I don't have a Windows box in my > use at the moment)? Does Python support the older IPv6 stacks > for NT4 and W2K? No. It requires routines that are not available in the "stock" winsock2.dll. When Pythonlabs Python 2.2 was released, it also required an installation of the preview IPv6 release, which could not be redistributed freely. At the moment, you need CVS Python, and VC.NET, to get IPv6 suport on Windows. This then works both with the released XP, and the MS research IPv6 stack. > What is the recommended method of finding out if Python and > the underlying OS support IPv6? I can, for instance, create an > IPv6 socket with a Python version that does *not* support > IPv6. What system is this? If you can create an IPv6 socket, why does it not support IPv6 (i.e. how do you know it does not support IPv6)? If you do .listen(), .getsockname() on that socket, what does it tell you? Regards, Martin From shalehperry at attbi.com Thu Sep 5 15:44:17 2002 From: shalehperry at attbi.com (Sean 'Shaleh' Perry) Date: Thu, 5 Sep 2002 12:44:17 -0700 Subject: Psycos and Pyros don't seem to play well together In-Reply-To: <72F73B808A78D511A73600034771D9FF717EB7@dc_exchange2.howrey.com> References: <72F73B808A78D511A73600034771D9FF717EB7@dc_exchange2.howrey.com> Message-ID: <200209051244.17210.shalehperry@attbi.com> On Thursday 05 September 2002 11:22, PoulsenL at capanalysis.com wrote: > I am working on a distributed application using Pyro that I thought would > benefit from Psyco. All is well until I add "from psyco.classes import *" > and then it gives me some Pyro based error messages (be happy to send them > along if requested) when I launch the client. I am using the "quickstart" > method to get my objects up and running on Pyro quickly. Anyone try to use > these two modules together before? What were your results? > > Thanks, > > Loren and this is why 'from foo import *' is a bad idea. You should just do 'import psyco' because you are probably seeing a name conflict. From aleax at aleax.it Wed Sep 25 10:51:21 2002 From: aleax at aleax.it (Alex Martelli) Date: Wed, 25 Sep 2002 14:51:21 GMT Subject: problem with dictionaries within lists References: Message-ID: Grant Hallam wrote: > The problem with blanking out the dictionary with dict{} is that it wipes > the keys out. As the loop goes through it assigns the matching second > half of the list to a matching key. If you insert a print statement on > the dict you can see the values in the dict are changing. Thus while it > is the same dict the key values within the dict are different. Thats why > I'm somewhat confused as to why its the same dic value. As for the tabs, It's the same dict object because you didn't copy it. You just appended many references to it to the list. So, just use: >> webdatabaselist.append(dict.copy()) appending *copies* of the dict to the list, and you should be OK. BTW, avoid naming your own variables like builtins -- list, dict, file, int, str, &c -- you'll come to grief eventually when you do that and then some other piece of your code tries to use the builtin in the normal way. It's always possible to find a more significant name, anyway, so avoiding the types' names is no burden. (This has nothing to do with your specific problem -- it's just general advice). Alex From timr at probo.com Wed Sep 18 02:22:47 2002 From: timr at probo.com (Tim Roberts) Date: Tue, 17 Sep 2002 23:22:47 -0700 Subject: hexacodes in python? References: Message-ID: <9n6gou8haak3o8njn8h38g55s6bn5gdapc@4ax.com> jubafre at brturbo.com wrote: >what is the hexacode for '?' in python? >where can i take the hexacodes? This is somewhat operating-system dependent, but it is not really Python-dependent. In Windows, "lower case C with cedilla" is hex E7, decimal 231. In Unicode, it is U+00E7. I used the Windows 'charmap' application to look this up. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From j_r_ashley at MAKGifts.com Wed Sep 4 13:45:57 2002 From: j_r_ashley at MAKGifts.com (James Ashley) Date: Wed, 04 Sep 2002 17:45:57 GMT Subject: maximum number of threads? References: <3d75b761$0$26216$afc38c87@news.optusnet.com.au> Message-ID: In article <3d75b761$0$26216$afc38c87 at news.optusnet.com.au>, Steven wrote: > Basically its a voice server, or rather a voice to text server, so > information produced might be sporadic, or fairly continuous. Up until about a year ago, I worked for a company which did "speech recognition applications." I shuddered when I saw this--my initial assumption was that you're trying to do both "dictation-style" and "small, formal, grammar-based" ASR at the same time, or some such. It scared me . But, then, to actually be on topic: > Is there a maximum number of threads, and any opinions on whether the GIL > and context switching in the interpreter is liable to make it unworkable (or > a case of 'build and see')? I think it really depends on your expected server load. If you're going to start out with just a few clients, it might be best to just start out with python threads. I think you might be better served starting out using jython, though. That depends, of course, on a lot of other factors (like any issues getting JNI going with the actual speech recognition engine...I'm guessing you're doing some embedding). When I left that company, we were moving into a situation with hundreds of clients using "one server." At that point, we had to create a distributed network cluster and use that for the backend. The speech recognition part wasn't much of a problem...it had been designed with that in mind from the ground up. Ironically enough, our biggest problem (or, rather, the piece that took the most work) was the database backend (it turns out that Access could only handle about a dozen clients). And that's far more than enough. I presume one of the threading gurus around here is much more qualified than I to give you actual advice about threading. Regards, James From robin at jessikat.fsnet.co.uk Wed Sep 18 14:56:06 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 18 Sep 2002 19:56:06 +0100 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: In article , Dennis Reinhardt writes ....... > >Would he be impressed by a user interface that powers 2.1 BILLION web >documents? (ref: alltheweb.com) > >I am about 2 weeks away from releasing HTUIL, an integrated client for >Windows, hosting Python, Perl, and/or native PLD2 displaying in a standard >web browser. See www.dair.com/hellopy.exe for a "hello" program written in >Python and distributed as a standalone EXE on Windows. > >-- > >Dennis Reinhardt Well hoping Dennis is genuine and has better control over virii than my outdated anti-virals I tried running this 360k hello world. Now I'm confused, I have K-Meleon 0.6 installed as my standard, but hellopy.exe tries to use Netscape 4.78 (also installed on my machine) and fails to display anything properly (I see the source in the browser window). Probably one of those pesky registry settings over which only Billy Goats has any control. -- Robin Becker From oren-py-l at hishome.net Sun Sep 22 02:47:00 2002 From: oren-py-l at hishome.net (Oren Tirosh) Date: Sun, 22 Sep 2002 02:47:00 -0400 Subject: "time" module under AIX? In-Reply-To: References: Message-ID: <20020922064700.GA4436@hishome.net> On Sun, Sep 22, 2002 at 01:34:36AM -0400, marco wrote: > marco writes: > > > I've just compiled python 2.2.1 under AIX and all seemed > > to go well. However, I'm having some trouble importing > > a few modules such as "time" and "math" e.g. > > OK, it seems it was a permission problem. I compile/install > stuff as a non-privileged user and then change ownership. > However, it turns out that "make install" doesn't use the > "install" command consistently and sometimes just copies > stuff (without setting any permissions). Please submit a bug report at http://sourceforge.net/bugs/?group_id=5470 If you also submit a patch it will be great! Oren From robin at jessikat.fsnet.co.uk Wed Sep 4 14:39:16 2002 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Wed, 4 Sep 2002 19:39:16 +0100 Subject: jython memory usage References: <3d76366a$1_5@news.bluewin.ch> <3d76494d$1_5@news.bluewin.ch> Message-ID: In article <3d76494d$1_5 at news.bluewin.ch>, Samuele Pedroni writes ..... >> > >> > >> well actually we're running with the default jython.bat which doesn't >> seem to specify a memory, 1Gig is probably the default or maybe I ran >> out of page space. The python process never gets over 90Mb grrrhhhh. > >then maybe I'm puzzled, > >have you checked process memory usage or is just that you get >an "out of memory" and are estimating based on your total memory. > >Because the normal jython.bat uses the JVM default which is >to scream "out of memory" after 64Mb of object memory has >been allocated, see -Xmx here > >http://java.sun.com/j2se/1.4/docs/tooldocs/windows/java.html#options > >regards. ...... we're watching it on the task monitor/performance. No other process running, this particular thing just eats up the world. -- Robin Becker From djc at object-craft.com.au Fri Sep 20 22:57:07 2002 From: djc at object-craft.com.au (Dave Cole) Date: 21 Sep 2002 12:57:07 +1000 Subject: Python Sybase slow compared to Perl? References: Message-ID: > I have always written my database scripts in Perl. I am very > interested in Python, and would like to start using it for all my > scripting. I am not trying to start a flame war, I'd just like to > understand why a particular script I wrote runs so much faster under > Perl. The script in question takes roughly 3 times as long to run > under Python. It is very possible that there is a faster way to do > this under Python. [snip] > Here is the Perl code snippet: [snip] > while ( @data = $sth->fetchrow_array() ) { [snip] > and here is the Python code snippet: [snip] > while 1: > row = c.fetchone() snip] > No matter what table how many records there are, the Python script > always takes longer to run (usually by a facter of 3 or more). I suspect that some of the difference is due to the fact that you are fetching an array of rows using Perl but only a single row at a time in Python. Having said that, the current implementation of the Python module does not do array binding for cursors. The Sybase.py module is built on top of an extension module called sybasect which does support array binding. To find out if that is the problem (until I get around to fixing the cursor to do array binding) you could try doing this: # output the actual data num_recs = 0 if os.path.isfile( "%s.gz" % dumpfile ): os.remove( "%s.gz" % dumpfile ) file = os.popen( "gzip -c > %s.gz" % dumpfile, "w" ) result_sets = db.execute( "SELECT %s FROM %s" % ( select, table ) ) for row in result_sets[0]: line = [] for i in range( len( row ) ): line.append( "%-*s" % ( lengths[i], row[i] ) ) print >> file, "".join( line ) num_recs += 1 file.close() c.close() Note that the c.fetchone() method retrieves rows one at a time from the server so does not consume much memory when there are a huge number of rows returned. The db.execute() array binds a buffer for 16 rows so retrieves the entire result 16 rows at a time before returning. It will use a large amount of memory if there are a large number of rows returned. > I am still a Python newbie, so I may be doing something wrong. Has anyone > else experienced similar results? Is this due to a poorly optimized > Sybase module? I really want to use Python, and I don't mind giving up a > little speed, but this is more than I can accept. > > I ran the Python script using the profiler and the output is below. Any > help would be much appreciated. Thanks. > profile output: > > Ordered by: standard name > > ncalls tottime percall cumtime percall filename:lineno(function) > 1 0.000 0.000 1230.540 1230.540 :1(?) > 4 0.000 0.000 0.000 0.000 Sybase.py:114(_get_diag) > 2 0.000 0.000 0.000 0.000 Sybase.py:141(_ct_errors) > 3 0.000 0.000 0.000 0.000 Sybase.py:148(_row_bind) > 900345 96.240 0.000 96.240 0.000 Sybase.py:166(_extract_row) > 900348 177.670 0.000 273.910 0.000 Sybase.py:180(_fetch_rows) > 3 0.000 0.000 0.010 0.003 Sybase.py:229(__init__) > 3 0.000 0.000 0.000 0.000 Sybase.py:246(__del__) > 900361 83.230 0.000 267.090 0.000 Sybase.py:258(_lock) > 900361 86.720 0.000 269.000 0.000 Sybase.py:262(_unlock) > 3 0.000 0.000 0.010 0.003 Sybase.py:312(close) > 3 0.000 0.000 0.000 0.000 Sybase.py:328(execute) > 900348 178.280 0.000 988.260 0.001 Sybase.py:365(fetchone) [snip] The other thing which may be causing some of the slowness is the locking. The module allows threads to share connections which requires a fair amount of lock maintenance. - Dave -- http://www.object-craft.com.au From andymac at bullseye.apana.org.au Fri Sep 6 00:25:31 2002 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 6 Sep 2002 14:25:31 +1000 (EST) Subject: Python "compiler" is too slow for processing large data files??? In-Reply-To: <3d6d097d$0$321$e2e8da3@nntp.cts.com> Message-ID: <20020906141327.S86922-100000@bullseye.apana.org.au> [posted and mailed] On Wed, 28 Aug 2002, Ron Horn wrote: {...} > Simple example - I can import or exec this file to load my data (my real app > has int, float, and string data): > ------ try5a3.py -------- > list1 = [ > (323, 870, 46, ), > (810, 336, 271, ), > (572, 55, 596, ), > (337, 256, 629, ), > (31, 702, 16, ), > ] > print len(list1) > --------------------------- > > Anyway, as my data files went from just a few lines, up to about 8000 lines > (with 10 values in each line for total of about 450KB of text), the time to > 'exec' the file became too slow (e.g. 15 seconds) and used too much memory > (e.g. 50MB) (using ms-windows, python 2.2.1). It is the "compile" phase, > because if I re-run, and there is *.pyc file available, the import goes very > fast (no compilation required). Hmmm... Your problem looks familiar. A change to Python's parser was checked in to CVS by Tim Peters on both the head (2.3 to be) and 2.2 maintenance branches, which works around malloc()/realloc()/free() issues on several platforms in the face of very long expressions - see test_longexp.py in Python's regression test suite. The symptoms include gross memory consumption and/or very long runtimes for test_longexp.py. The fix will be available in 2.2.2 as well as 2.3 when released. -- 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 loewis at informatik.hu-berlin.de Wed Sep 18 02:50:14 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 18 Sep 2002 08:50:14 +0200 Subject: How to make a C extension module backwards compatible? References: Message-ID: Andrew McNamara writes: > That's a good question - this is more of a learning exercise than a > project with a real need. I guess the most useful attribute would be > sub-classing. I see. In that case, there is no way around ifdefs - the type object has grown extra fields, which the compiler will complain about if you are using an older version of Python. Regards, Martin From pieroul at attglobal.net Mon Sep 30 19:10:17 2002 From: pieroul at attglobal.net (Pierre Rouleau) Date: Mon, 30 Sep 2002 19:10:17 -0400 Subject: Is there a docutils / reStructuredText system for C++ source code available? Message-ID: <3D98D9D9.8000009@attglobal.net> I have been using docutil and reStructuredText for Python code and it works great. Pydoc does a superb job of helping in setting up an internal web site that provides documentation for our Python code, let alone the ability to run doctest test and show auto testing of python documentation on line! That works great for our Python code. Now i want to do the same thing for our C++ code. Since Python has been partly implemented in C / C++ i tough there might already exist some tools for parsing C++ and some comments (given some formatting conventions) and generate the same kind of output the html tool of docutil does. Does any one know any thing that resembles that? Thanks -- Pierre Rouleau From Oschler at earthlink.net Wed Sep 11 19:55:47 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Wed, 11 Sep 2002 23:55:47 GMT Subject: SpamBayes PIK file? Message-ID: <7KQf9.1760$Lg2.232748@news2.news.adelphia.net> I want to look at the SpamBayes project so I downloaded the zip file from source forge. Inside there's just a PIK file. How do I read a PIK file? thx From mennosimons at gmx.net Tue Sep 17 05:52:47 2002 From: mennosimons at gmx.net (Ulli Stein) Date: Tue, 17 Sep 2002 11:52:47 +0200 Subject: faster way for adding many strings Message-ID: Hi, What is the faster way: appending many strings to a list and then joining them, or writing to StringIO and then getvalue()? willi From sismex01 at hebmex.com Wed Sep 25 12:40:22 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 25 Sep 2002 11:40:22 -0500 Subject: Larry Wall's comment on python... Message-ID: > > Alan Daniels wrote: > > >Sometimes I wonder if Guido would have saved a lot of debate > > by declaring, long ago, that Python code would never allow > > tabs in it, period. Which may be a bit extreme, I'll admit. :-) Actually, it's the only universally-workable solution to this "problem". > Ironically, Guido originally ruled (in the style guide, IIRC) > that thou shalt use tabs and tabs are 8 spaces, "as god > intentended them to be." Yeesh! Why in God's name would he say such a dumb thing? I mean, even ancient mechanical typewriters have movable tab settings. Rigid, 8-char tabs is just so... neolithical. > > Unfortunately, he later changed position to the present, > unsatisfying, compromise position. And so, we all lose. > -- > James J. Besemer 503-280-0838 voice > 2727 NE Skidmore St. 503-280-0375 fax > Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com > http://cascade-sys.com > -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From jafo at tummy.com Wed Sep 18 13:19:00 2002 From: jafo at tummy.com (Sean Reifschneider) Date: Wed, 18 Sep 2002 11:19:00 -0600 Subject: New RPMs at python.org Message-ID: <20020918171900.GB13272@tummy.com> I've just released a new .src.rpm and binary RPMs for Red Hat 7.3. Included in the new release is a Makefile.pre.in (in the -devel package) for use with building Zope, and inclusion of /usr/bin/python2.2 to better operate with the source and Red Hat releases. The lack of it was a hold-over from previous 2.x RPMs. Find them at: http://python.org/2.2.1/rpms.html Sean -- What no spouse of a programmer can ever understand is that a programmer is working when he's staring out the window. Sean Reifschneider, Inimitably Superfluous tummy.com, ltd. - Linux Consulting since 1995. Qmail, Python, SysAdmin From dhein at acm.org Mon Sep 9 09:01:40 2002 From: dhein at acm.org (Coot) Date: 9 Sep 2002 06:01:40 -0700 Subject: Running IDLE from within a Tkinter application Message-ID: Is there any way to start an IDLE "Python Shell" window from within an executing Tkinter application _AND_ have the shell see the global variables of the main application??? I can launch IDLE from within the application, but I cannot figure out how to do so in such a way that it sees the global variables of the application. From michael at stroeder.com Tue Sep 24 07:35:25 2002 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 24 Sep 2002 13:35:25 +0200 Subject: Sessionhandling References: Message-ID: Lutz Schroeer wrote: > Michael Str?der wrote: > : Most users do *not* configure their browsers anyway. Therefore it's > : almost useless to use HTTP_ACCEPT_LANGUAGE or similar env vars. > > Well, at least you can try. As you can see in PyWebLib I did. I'm also using it in web2ldap to determine the preferred language for HTML templates. Guess what? Most german users see the english HTML output... > My solution to the orignal poster's problem > would be to detect the browser's language configuration and additionally > offer the possibility to change the language and store it in a (maybe > persistent) cookie. Note that someone suggested to use HTTP_ACCEPT_LANGUAGE for the orignal poster's problem to avoid session handling at all. Ciao, Michael. From sandskyfly at hotmail.com Sat Sep 14 04:02:17 2002 From: sandskyfly at hotmail.com (Sandy Norton) Date: 14 Sep 2002 01:02:17 -0700 Subject: Argh! Python 2.2 + threading + sockets = trouble References: Message-ID: Freddie wrote in message news:... > Hi, > > I'm a fairly new Python programmer, but I've written a decent sized > project (threaded IRC offer bot), and I wrote a threaded IPv6 capable > IRC bouncer yesterday. Of course, it doesn't work quite as I expected. > > MadCowOffer (offerbot) has rarely works properly with Python 2.2. It > will sometimes manage to start all the threads, then it's fine, but it > will usually just stop working after the IRC connection thread is started. A more precise description of your problem will often help others help you; more specifically, stating that an app 'just stops working' is not a great problem description. Localize the problem and someone may be able to point you in the right direction. cia, Sandy From iqbal at colorado.edu Wed Sep 4 14:44:02 2002 From: iqbal at colorado.edu (Naveed Iqbal) Date: 4 Sep 2002 11:44:02 -0700 Subject: How do i print to a printer using python? Message-ID: <6afb9d2c.0209041044.43c5f5f1@posting.google.com> I have to print to a standard printer. I take the data from the keyboard and print it using the printer. Please help me....my job depends on this!!!! thanks naveed From sandorlevi at yahoo.com Fri Sep 27 16:11:58 2002 From: sandorlevi at yahoo.com (Levente Sandor) Date: 27 Sep 2002 13:11:58 -0700 Subject: Problem with ClientCookie References: <3d946d0f$0$10364@echo-01.iinet.net.au> Message-ID: <8b5e42a6.0209271211.4f0c6d9f@posting.google.com> Probably the error is caused by the "secure" word in the set-cookie headers, because it doesn't contain "=", so it cannot be split by re.split(r"\s*=\s*", param, 1). I never used the ClientCookie package, but you may try to replace line 627 in the source with the following one: if '=' in param: k, v = re.split(r"\s*=\s*", param, 1) (be sure to retain the original indentation of the line) ---- levi "Rob Hall" wrote in message news:<3d946d0f$0$10364 at echo-01.iinet.net.au>... > I am trying to use ClientCookie to access a HTTPS website under Win98. I > have installed the W32 SSL wrappers. > > The code I have is similar to as follows (have removed authorisation > detail): > > import urllib > import ClientCookie > > if __name__ == '__main__': > urllib.URLopener.version = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows > NT 5.0)' > print 'Logging on...' > request = > urllib2.Request('https://www.quicktrade.com.au/cgi-bin/login?USERNAME=myUser > Name&PASSWORD=myPassword') > result = ClientCookie.urlopen(request) > > I have set HTTP_DEBUG = 1 in _ClientCookie.py > > I get the following response... > > > Logging on... > Page requested... > send: 'GET /cgi-bin/login?USERNAME=myUserName&PASSWORD=myPassword > HTTP/1.0\r\n' > send: 'Host: www.quicktrade.com.au\r\n' > send: 'User-agent: Python-urllib/2.0a1\r\n' > send: '\r\n' > reply: 'HTTP/1.1 200 OK\r\n' > header: Date: Fri, 27 Sep 2002 14:21:31 GMT > > header: Server: Stronghold/2.4.2 Apache/1.3.6 C2NetEU/2410 (Unix) > > header: set-cookie: > key=Kpfz5sbkkPrwsM7eng5ihtfuKq6sAlSdwTXhn/jUiEOSOCYJAC5r/Vlq+5uS9wqkpHJzOWHi > m4v+^Va7SldrYP9Vqea2vDKtZWnOiP7Ff5ckrrM61DDM+tIGO44jUyKPt2yof5Uz7lvUu0ErVqJk > DWAYX^7x66TxqZ2esB823pOue6zNxcmhY1SiS7pPTd5w3X/5ncX3njMZs_^; Path=/; secure > header: set-cookie: acct=myUserName STGBNET; Path=/; secure > header: set-cookie: level=1; Path=/; Domain=.quicktrade.com.au; secure > header: set-cookie: ID=1802009989; Path=/; Domain=.quicktrade.com.au; secure > header: set-cookie: w1=None; Path=/; secure > header: P3P: CP="NON DSP ADMa OUR IND UNI FIN" > header: Connection: close > header: Content-Type: text/html > > Traceback (most recent call last): > File > "C:\WINDOWS\Desktop\backup\uni\project\development\htmlProcessor\htmlProcess > or.py", line 22, in ? > result = ClientCookie.urlopen(request) > File "C:\PYTHON22\lib\site-packages\ClientCookie\_ClientCookie.py", line > 1387, in urlopen > return _opener.open(url, data) > File "C:\PYTHON22\lib\urllib2.py", line 322, in open > '_open', req) > File "C:\PYTHON22\lib\urllib2.py", line 301, in _call_chain > result = func(*args) > File "C:\PYTHON22\lib\site-packages\ClientCookie\_ClientCookie.py", line > 1334, in https_open > return self.do_open(httplib.HTTPS, req) > File "C:\PYTHON22\lib\site-packages\ClientCookie\_ClientCookie.py", line > 1319, in do_open > self.c.extract_cookies(result, req, redirect=redirect) > File "C:\PYTHON22\lib\site-packages\ClientCookie\_ClientCookie.py", line > 627, in extract_cookies > k, v = re.split(r"\s*=\s*", param, 1) > ValueError: unpack list of wrong size > > I can't find anything to help me debug this. Is the error because the web > server is returning more than one cookie? or is it just returning a bad > format? > > Any help is greatly appreciated. > > Rob From sismex01 at hebmex.com Wed Sep 25 10:31:43 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 25 Sep 2002 09:31:43 -0500 Subject: Newbie References Question Message-ID: > > Hi, > > let say I have: > i1 = 1 > i2 = 2 > and > p = [i1,i2] > > How can I have: > p=[*i1,*i2] > rather than > p=[**i1,**i2] as it is curently ? > > ( Sorry for this nasty hybrid syntax ) > > Textualy, how if I want that p[0] refere to the 'i1' > container, and not to > the refererence it contains ? > > What I want is that if now I set: > i1 = 4 > that automaticaly: > p -> [4,2] > and not keeping [1,2] > > Thanks in advance. > > -- > guy rabiller > 3d animator / td > grabiller at 3dvf.net > http://grabiller.3dvf.net > Repeat after me: "there is no spoon" Really though; you're chasing a ghost; the "container" you're looking for is (in the case of CPython) an element in a dictionary, any definition in a namespace is a definition in the dictionary which implements said namespace. Also, when you do a "i1 = 4", you're actually deleting the previous binding for the name "i1", and rebinding it to the object "int(4)". Why not tell us what you're trying to do, and maybe someone can come with a scheme to let you do it. :-) Good luck! -gus Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From see_reply_address at something.invalid Sun Sep 22 20:46:52 2002 From: see_reply_address at something.invalid (Greg Ewing) Date: Mon, 23 Sep 2002 12:46:52 +1200 Subject: Destructor never called ??? References: Message-ID: <3D8E647C.8010707@something.invalid> Aahz wrote: > I'm of the opinion that I understand roughly half of what you're talking > about and if I count as half a person, you can just round up. Except in situations where the law requires us to round you down. :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From loewis at informatik.hu-berlin.de Wed Sep 4 12:50:40 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 04 Sep 2002 18:50:40 +0200 Subject: Tkinter report_callback_exception? 'module' object has no attribute 'print_exception' ? References: <2621b014.0209040715.1bf9fce3@posting.google.com> Message-ID: schull at digitalgoods.com (Jon Schull) writes: > As I interpret this message, the environment is telling me that > traceback has no "print_exception." But of course, it does. That is indeed surprising. I'd check whether traceback really is what you think it is, at that point: print traceback.__filename__ print dir(traceback) HTH, Martin From peeryc at hotmail.com Fri Sep 27 10:29:02 2002 From: peeryc at hotmail.com (Christopher Peery) Date: 27 Sep 2002 07:29:02 -0700 Subject: Python Process that can survive Message-ID: <571739c3.0209270629.10575f47@posting.google.com> Alright... I love python but I think I may have found a definite problem. I can't seem to run a python process, kick it to the back-ground, and then kill the terminal that started it. With most other things, the python process would keep running in the back-ground regardless. For me, the process always dies with the terminal. So my question: is there a way to separate a python script from the underlying terminal so that this will not happen. I'm hoping for some scheme that's supported by the language. I've found a few hacks on-line where the python process is daemonized but this requires shutting down all the standard io streams. There's got to be a better way especially since it can be done in Perl very easily with no special tricks. By the way, I'm doing this on a linux box. Chris From bokr at oz.net Mon Sep 2 19:37:34 2002 From: bokr at oz.net (Bengt Richter) Date: 2 Sep 2002 23:37:34 GMT Subject: stylistic question -- optional return value References: <30292041.0209012344.ab2d4@posting.google.com> Message-ID: On Mon, 2 Sep 2002 14:41:57 GMT, Andrew Koenig wrote: >Sebastian> Why not create an additional optional *argument* (say a list, or a >Sebastian> function), to which you optionally provide your debug information? > >It's not debug information. I used that term only as an analogy. > >Anyway, I don't want to separate the optional information from the >rest of it because everything needs to go into the same data structure >eventually. > What about defining a class to represent the "data structure," and passing a reference to an instance of that to your various routines, so that they can populate the structure themselves (via methods/attributes/properties as convenient) instead of returning data for a caller to do the populating with? BTW, you mentioned recursion in another part of the thread. Is that as in recursive descent? An exception is an interesting alternative way to return a first match, with no need to return anything from unsuccessful visits. Regards, Bengt Richter From sismex01 at hebmex.com Wed Sep 25 10:00:48 2002 From: sismex01 at hebmex.com (sismex01 at hebmex.com) Date: Wed, 25 Sep 2002 09:00:48 -0500 Subject: Decimal arithmatic, was Re: Python GUI app to impress the bos s? Message-ID: > > > > There ought to be severe penalties for idiots that use > > floating point dollars for financial applications. > > If forced to use floating point (e.g. because customer > > demands BASIC), then keep money amounts in whole pennies > > (or whatever the smallest currency unit for the country > > is), and divide by 100 (or whatever) for printing only (or > > just add the decimal point yourself). > > > > In many circumstances this is exactly what you can't do. > The minute you need to calculate percentages you will get in to > the things like .0001254 of a cent, no matter what is you > smallest unit of currency. > > I worked for a insurance company (using Business Basic) many > years ago on MAI and Prime gear, and we did everything as floats > with 14 places after the decimal point,and only rounded when > a human needed to see a number, and then used standard accounting > practices for rounding, > > Rgds > > Tim > OK, so don't use whole pennies (or smallest currency) as your base, use 10,000ths of a penny, but still use integer arithmetic for your calculations. Floating point has too many rounding errors to be trustworthy; or, looking at it from another angle, floating-point calculations cannot be 100% accurate because of the way it's implemented. -gustavo Advertencia: La informacion contenida en este mensaje es confidencial y restringida y esta destinada unicamente para el uso de la persona arriba indicada, Esta comunicacion representa la opinion personal del remitente y no refleja necesariamente la opinion de la Compa?ia. Se le notifica que esta estrictamente prohibida cualquier difusion, distribucion o copia de este mensaje. Si ha recibido esta comunicacion o copia de este mensaje por error, o si hay problemas en la transmision, favor de comunicarse con el remitente. Todo el correo electr?nico enviado para o desde esta direcci?n ser? procesado por el sistema de correo corporativo de HEB. Tal correo electr?nico esta sujeto a ser almacenado y puede ser revisado por alguien ajeno al recipiente autorizado con el prop?sito de monitorear que se cumplan las normas de seguridad de la empresa. From syver-en+usenet at online.no Fri Sep 6 13:32:25 2002 From: syver-en+usenet at online.no (Syver Enstad) Date: Fri, 06 Sep 2002 17:32:25 GMT Subject: Windows NT login script References: <3D781715.5070505@nowhere.com> Message-ID: c writes: > I am a newbie to Python and I'm wondering how difficult it would be to > > write a Windows NT/2000 login script using Python? > > Can anyone think of a good way to do it? I am not really into this, but couldn't you start a python script from a windows batch file (.bat or .cmd) Like this: bla bla batch stuff net use bla bla python myScript.py withAnArgument orTwo bla bla batch stuff -- Vennlig hilsen Syver Enstad From fgibbons at hms.harvard.edu Fri Sep 20 13:56:21 2002 From: fgibbons at hms.harvard.edu (Frank Gibbons) Date: Fri, 20 Sep 2002 13:56:21 -0400 Subject: saving state in Python/CGI Message-ID: <5.0.0.25.2.20020920134912.00ad3230@hms.harvard.edu> Hi, I've been using Python (and Jython) for about 5 months now. So far, so great. I'm building a CGI app that has about 5 different stages, and I need to maintain state between them. Specifically, it's a scientific tool that requires the user to upload a (possibly quite large) datafile, processes it, does some computation, then hands it back (formatted) with results. I need access to the data on each page, yet don't want to pass it as a hidden field, because of its potential size. In Perl, I could just use the save() method from CGI.pm to save the form on the server side, pass a session key in a hidden field, then retrieve the data using the key. For the life of me, I can't find an equivalent way in Python. cgiFormStorage looks like a dictionary, but it's immutable, so you can't retrieve data from disk and add it to the form. cgi.py appears to have no analog to CGI.pm's save() method, at least not that I've been able to find. I've tried pickling the form, but that doesn't work either (it saves something to disk alright, but not the large data retrieved from a multi-part form file upload). Perhaps I've missed something. Maybe that's just not how you do things in Python. Can anyone help? Thanks, -Frank Gibbons PhD, Computational Biologist, Harvard Medical School BCMP/SGM-322, 250 Longwood Ave, Boston MA 02115, USA. Tel: 617-432-3555 Fax: 617-432-3557 http://llama.med.harvard.edu/~fgibbons From sholden at holdenweb.com Thu Sep 12 11:57:00 2002 From: sholden at holdenweb.com (Steve Holden) Date: Thu, 12 Sep 2002 11:57:00 -0400 Subject: class variable won't icrement! References: <3d8054ef$0$234$4d4ebb8e@news.nl.uu.net> Message-ID: "Aahz" wrote in message news:alq9hf$bn$1 at panix1.panix.com... > In article , > Eric Brunel wrote: > > > >I always found that inheritance of class attributes to instance attributes > >was really misleading, and I even think it would be better if it were > >simply removed from Python. IMHO, it would far more conform to the > >"explicit is better than implicit" rule that is one of the basis of Python. > > If I think of it as "scope resolution" rather than "inheritance", I find > that it makes more sense. It works exactly the same way as hiding a > global with a local. Well, not quite exactly the same way. If a local hides a global then there's no way to access the global without explicit use of a namespace. A class variable is available by instance-qualified name up until the time the instance variable with the same name is created, which is why statements like self.var += 1 can be so confusing. Especially when you compare operations that give different results for mutable and immutable objects. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From richard.papworth at bbsrc.ac.uk Tue Sep 3 05:07:29 2002 From: richard.papworth at bbsrc.ac.uk (Richard Papworth) Date: 3 Sep 2002 02:07:29 -0700 Subject: Core dump on Tru-64 when using 2.2 Message-ID: <695dd93e.0209030107.7ba70082@posting.google.com> Does anyone know the source of the following error message? exception system: exiting due to multiple internal errors: exception dispatch or unwind stuck in infinite loop exception dispatch or unwind stuck in infinite loop exception system: exiting due to multiple internal errors: exception dispatch or unwind stuck in infinite loop exception dispatch or unwind stuck in infinite loop Abort process (core dumped) Build information: Python 2.2 (#2, Feb 20 2002, 11:44:40) [GCC 2.95 19990728 (release)] on osf1V4 I've only experienced this problem over the past couple of days. Firstly when attempting to use minidom to parse a string, then when using the help system under the interactive interpreter. I'm puzzled 'cos I'm sure these are activities I've carried out without a hitch over the past few months. So why the problem now? Any suggestions? Thanks in advance Richard From deltapigz at telocity.com Tue Sep 10 13:18:21 2002 From: deltapigz at telocity.com (Adonis) Date: Tue, 10 Sep 2002 13:18:21 -0400 Subject: test (ignore) Message-ID: <3d7e2957$1_2@nopics.sjc> just a test, please ignore. Adonis From mmaddox at hcsmail.com Fri Sep 6 23:28:20 2002 From: mmaddox at hcsmail.com (mmaddox at hcsmail.com) Date: Fri, 6 Sep 2002 23:28:20 -0400 (EDT) Subject: Larry Wall's comment on python... Message-ID: <200209070328.g873SKVm012455@mail.hcsmail.com> You're right. The PLACEMENT of blocks in my style is arbitrary. My intention was to indicate the STYLE of block delimiting was arbitrary (Nehemiah Jordan: when a task is not seen in meaningful context it is experienced as being arbitrary). This is not totally in line with my intentions either, as all programming language rules could be deemed arbitrary by someone unwilling to accept the context in which they exist. Now, I LOVE Python. I also love C++. Smalltalk and Lisp are interesting. Perl is useful to someone somewhere. I said some things that are not as precise as I would have liked, and I don't want to explore the semantics of this mailing list and each individual post. Python is cool. Let's talk about Python. -Michael peter at engcorp.com wrote: > mmaddox at hcsmail.com wrote: > > Although I grant the Python structure and the column-based > > structures are not completely analogous, they BOTH burden the programmer > > with arbitrary rules to govern the physical layout of the code. Although > > this layout may be considered more elegant from a readability standpoint, > > it's the enforcement of the layout that is irritating to the more > > Libertarian of us. > > I think you have the wrong meaning for "arbitrary". From the > sounds of it, you have exactly reversed which is arbitrary (your > own "libertarian" coding style) and which is "governed by fixed > rules" (Python layout). > > > Having read Wall's comments on Slashdot, I think he is really just mildly > > complaining about ridiculously long page-widths in his editor, not really > > slashing Python seriously. He's just giving some props to his own baby at > > the expense of another. (He had to say something, right?) You must agree > > that Python can lead you to horizontal scrolling in your editor - the bane > > of user interface design. > > I agree with the comments about Larry "having" to say something like this. > > I definitely don't understand how Python, more or less than any other > language, leads to more horizontal scrolling. Pretty much all > Python code I've ever seen (though I haven't seen yours yet :-) is > roughly 80 characters max, and mine own has been about that since I > started writing C code 16 years ago. > > Do you mean there is something special about Python not delimiting > blocks in the traditional ways which somehow leads you to write > much wider lines of code? > > -Peter > > -- > http://mail.python.org/mailman/listinfo/python-list > > ? -- Michael F. Maddox Senior Software Engineer Hayes Tallahassee, FL, USA From donn at drizzle.com Sat Sep 21 02:06:43 2002 From: donn at drizzle.com (Donn Cave) Date: Sat, 21 Sep 2002 06:06:43 -0000 Subject: Python threading? References: Message-ID: <1032588401.625298@yasure> Quoth Trent Mick : | [Robert Oschler wrote] |> How can I tell if the version of Python I am running is thread-enabled? | | Run Lib/test/test_thread.py with your Python build. If you are on any | common platform then Python, unless specifically crippled, is | thread-enabled. I think you know that doesn't include NetBSD, and I believe it doesn't include MacOS either. I'd call both of those common platforms, though you can draw that line anywhere you want. |> Also, what is a reasonable number of threads to expect to be able to run |> before context switching overhead becomes a problem (I'm using a PIII 500 |> Mhz with 512MB ram if that helps). | | I have no experience putting that many threads to use. Of course it would depend, too, on what "a problem" means, and on what operating system the application is hosted on. And it might be worth mentioning that the Python parts of the application will not execute in parallel, anyway, thanks to a global interpreter lock that can be held by only one thread at a time. Donn Cave, donn at drizzle.com From jubafre at brturbo.com Sun Sep 8 13:56:26 2002 From: jubafre at brturbo.com (jubafre at brturbo.com) Date: Sun, 8 Sep 2002 14:56:26 -0300 (GMT-03:00) Subject: transform a list of lists in a lit of strtings??? Message-ID: <-1588066870.1031507786228.JavaMail.nobody@webmail2.brturbo.com> I have a list of lists like this: labels=[['D1'], ['D2'], ['D3']] and i want to transform ia a list of strings labels2==[ 'D1' , 'D2' , 'D3' ] <<<<<<<----------- how i can get it???? Juliano Freitas www.gebrasil.hpg.com.br From pyth at devel.trillke.net Thu Sep 19 09:40:00 2002 From: pyth at devel.trillke.net (holger krekel) Date: Thu, 19 Sep 2002 15:40:00 +0200 Subject: Getting started In-Reply-To: ; from lbrannma@cablespeed.com on Thu, Sep 19, 2002 at 06:03:25AM -0700 References: Message-ID: <20020919154000.B30315@prim.han.de> Lance wrote: > Hi All, > > Last night I attended a Weak typing, C++ Templates, and Python talk by Bruce > Eckel. It was great, my introduction to Python. > > I'm sold on Python and weak typing. I am not. But i much prefer dynamic over static typing :-) What is 'weak typing' supposed to mean, anyway? I have heard that a couple of times from java-people because they tend to think that python is not strongly typed. > Would you be able to suggest an indispensable learning Python book? David Beazley wrote "Python essential reference" which is a very good book for programmers. It doesn't cover the most recent developments but it still is one of the best IMO. holger From python-list at hendel.net Wed Sep 25 03:06:55 2002 From: python-list at hendel.net (Manuel Hendel) Date: Wed, 25 Sep 2002 09:06:55 +0200 Subject: problems defining an empty list Message-ID: <20020925070654.GB57911@partagas.as.de.cw.net> This is what I'm trying to do: # empty list for lines per domain linesperdomain = [] linesperdomain = [domain, domainlines] print linesperdomain domainlines is also a list. Error: linesperdomain = [] ^ IndentationError: unindent does not match any outer indentation level I've done it the same way in the same script several times before, what's wrong here. I don't understand this error. Can someone help. Thanks, Manuel -- This American system of ours, call it Americanism, call it capitalism, call it what you will, gives each and every one of us a great opportunity if we only seize it with both hands and make the most of it. -Al Capone From s_gherman at yahoo.com Tue Sep 10 15:22:31 2002 From: s_gherman at yahoo.com (Sorin Gherman) Date: 10 Sep 2002 12:22:31 -0700 Subject: web crawler help? References: Message-ID: "koko" wrote in message news:... > is there any sample for basic web crawler, that ask for a starting url and > log the url and extract the hyperlinks? > thx It's a very simple one in Mark Pilgrim's "Dive into Python" book, whose text is freely available at: http://diveintopython.org/ Check the "HTML processing" chapter. It contains a urllister.py 9 lines program, followed by a 7 lines usage example which does just that: given a URL for a HTML file, it lists the hyperlinks inside it. /sorin gherman From max at alcyone.com Mon Sep 2 14:59:12 2002 From: max at alcyone.com (Erik Max Francis) Date: Mon, 02 Sep 2002 11:59:12 -0700 Subject: How to parse over a Python expr? References: <8sjvmugochmuvo4fnfaelq4m59plj6lg0r@4ax.com> <3D6FD585.111E32AE@alcyone.com> <3D7002C4.22DD2AB3@alcyone.com> Message-ID: <3D73B500.D1304D13@alcyone.com> Stefan Franke wrote: > Are you sure? I think a TQS with a single quote inside would be > sufficient to miss the right TQS end: > > '''That's all''' > > These a 7 single quotes. Parsed as single-quote strings, the last one > opens a string until EOF. Yep, you're right (provided the triple-quoted string is the same kind that appears within it). I realized that after I posted. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE / \ There is nothing so subject to the inconstancy of fortune as war. \__/ Miguel de Cervantes Church / http://www.alcyone.com/pyos/church/ A lambda calculus explorer in Python. From bloke at ii.net Tue Sep 17 21:19:36 2002 From: bloke at ii.net (Rob Hall) Date: Wed, 18 Sep 2002 09:19:36 +0800 Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> Message-ID: <3d87d495$0$28699@echo-01.iinet.net.au> > Actually both may be a solution. I've recently had good success at > developing an with a VB (not .net) front end and doing most of the > work in Python. Use each for what it's best at. Based on my experience with > project, I'd say that Python take about 25% of the code of VB to accomplish > the same objective. Plus Python objects tend to do what is expected so that > you can often guess at the syntax and be right whereas this is seldom true > with > VB objects. Interesting... Can you point me to any links that may give me some pointers in doing the same? Rob From Doc at goodweb.de Wed Sep 4 11:18:03 2002 From: Doc at goodweb.de (Thomas Korb) Date: 04 Sep 2002 17:18:03 +0200 Subject: 4Suite / McMillan Installer / py2exe Message-ID: Hi! I am using the XSLT-Processor from 4Suite (0.12.0a2), i.e. from Ft.Xml.Xslt.Processor import Processor from Ft.Xml.InputSource import DefaultFactory from Ft.Xml import ReaderException On Linux, I can use McMillan's Installer to create a distribution; on Windows, it fails (problems with a Math.py-module in the 4Suite package). And py2exe complains about missing modules. I can overcome the py2exe-problem by importing everything from Ft.Xml.Xslt, i.e. import Ft.Xml.Xslt.ApplyImportsElement import Ft.Xml.Xslt.ApplyTemplatesElement etc. etc. (a lot of etc. :-) (Too many module to include them on the commmand line with py2exe's '-p' option; more than 1024 characters!) After that, py2exe still complains about missing modules (some of which even do not exist on the system; I think at least some of them are Mac-specific!), but it works (as far as I could check up to now). But now the program takes quite a time to start (many imports), and I actually do not really trust this solution. Moreover, I would have to check and test all the above imports with each new version of 4Suite. Does someone know how to use 4Suite with the McMillan Installer or py2exe on Windows? Any help or hints would be highly appreciated! -- ----------------- Dr. Thomas Korb - G O O D W E B . D E s i g n --- ----------------- DOMAIN: www.goodweb.de / E-MAIL: Doc at goodweb.de --- From =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= Thu Sep 19 08:08:25 2002 From: =?iso-8859-5?Q?=DF=D5=DD=D3=E3=D8=DD=D8=E1=E2=D0?= at =?iso-8859-5?Q?=DC=D0=D8=DB?=.=?iso-8859-5?Q?=DD=D5=E2?=.=?iso-8859-5?Q?=DC=DA?= (=?iso-8859-5?Q?=B4=D0=DC=F8=D0=DD_=B3=2E?=) Date: Thu, 19 Sep 2002 14:08:25 +0200 Subject: RegEx editors References: Message-ID: <3d89be32$1@news.mt.net.mk> > Does anybody know of any good graphical regex editors out there? As of KDE 3.0 its a standard option in (most) every find dialog. It is also part of QT 3 I think. -- ?????? hundred-and-one symptoms of being an internet addict: 21. Your dog has its own home page. From erikprice at mac.com Wed Sep 4 11:42:05 2002 From: erikprice at mac.com (Erik Price) Date: Wed, 4 Sep 2002 11:42:05 -0400 Subject: quick question about generator.next() Message-ID: A quick question about generators: If I have a generator object, the first value produced by the generator object does not actually get produced until the first time I call generator_object.next() , correct? In other words, simply instantiating the generator object doesn't "activate" the generator function, rather it just creates it -- only when the next() method is called does the generator's internal logic "activate", right? (Where are generator objects getting their next() method from anyway... is it implicitly inherited behind the scenes when I use the "yield" keyword to turn a function into a generator?) Thank you, Erik -- Erik Price email: erikprice at mac.com jabber: erikprice at jabber.org From magnus at thinkware.se Fri Sep 20 09:34:29 2002 From: magnus at thinkware.se (=?ISO-8859-1?Q?Magnus_Lyck=E5?=) Date: Fri, 20 Sep 2002 15:34:29 +0200 Subject: isFloat: Without Exception-Handling References: Message-ID: <3D8B23E5.3040005@thinkware.se> Thomas Guettler wrote: > Is there a way to write the following > method without using exceptions? > > def isFloat(string): > is_float=1 > try: > float(string) > except: > is_float=0 > return is_float Something like this perhaps: import re def isFloat(S): floatRE = r"^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$" return re.match(floatRE, str(S)) is not None I'm not sure it's faster though. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus at thinkware.se From david.abrahams at rcn.com Mon Sep 30 16:22:55 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Mon, 30 Sep 2002 16:22:55 -0400 Subject: SWIG - C++ - Inheritance References: Message-ID: "news1.sympatico.ca" wrote in message news:d31m9.3742$Qh1.491539 at news20.bellglobal.com... > Hello, > > The problem comes when I come to create a new class in python that inherits > from CThread. Here is the python code sample > =============== test.py ================= > import my_module > > class MyThread(my_module.CThread): > def __init__(self): > pass > def process(self): > print "hey" > > a = MyThread() > a.run() > ============================================ > my_module is exposed to Python using SWIG. When I try to execute this, I > get the following error : > > ############################################# > Traceback (most recent call last): > File "U:\Alexandra\test\pythontool\martin.py", line 14, in ? > a.run() > File "U:\Alexandra\test\pythontool\hector.py", line 649, in run > def run(*args): return apply(_hector.CThread_run,args) > TypeError: Type error. Expected _p_CThread > ############################################# > > It appears that the swig module does not recognize the a variable as a > CThread. I guess there is something I am doing wrong. It does not even > call the process function so the problem does not appear to be with the pure > virtual function. Anybody can help ? It would be really appreciated. I don't know much about SWIG, but if it's anything like Boost.Python the problem is that you've shielded the base class __init__ function. Something has to create the C++ CThread object, and it would make sense if CThread.__init__ were responsible for that job. Just remove the __init__ function from MyThread, or have it call CThread.__init__(self) and you should be OK. -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From just at xs4all.nl Mon Sep 9 18:46:54 2002 From: just at xs4all.nl (Just) Date: Tue, 10 Sep 2002 00:46:54 +0200 Subject: Windows/DOS: double clicking a .py file References: Message-ID: [Just] > > impossible to actually see the exception... Is there a way > > to keep the dos prompt window in this case? [Bjorn Pettersen] > Try something like the following... We've had much success with > automatically emailing the traceback back to the developer using the > cgitb module -- you can never trust users to give you good error reports > besides the cgitb module provides much more context than the > standard exceptions... Let me know if you'd like the code... > > try: > your code here > except: > import msvcrt, traceback > traceback.print exc() > print 'Hit a key to exit' > while not msvcrt.kbhit(): > pass Ah, that looks like a good trick, I will try that. Thanks for your code offer, but in most cases I will have to ask for the input data anyway, so a simple traceback is good enough for now. Just From hbl at st-andrews.ac.uk Tue Sep 17 14:46:21 2002 From: hbl at st-andrews.ac.uk (Hamish Lawson) Date: Tue, 17 Sep 2002 19:46:21 +0100 Subject: Will "Python in a Nutshell" be too short? Message-ID: <5.1.1.6.0.20020917181205.035d0a58@spey.st-andrews.ac.uk> O'Reilly doesn't yet list the forthcoming "Python in a Nutshell" by Alex Martelli, but according to Amazon.com's page for the book, it will have 400 pages. Is that indeed the plan? I know that O'Reilly aims to keep fat out of its books, and that Alex is striving to be comprehensive yet concise, but I worry that the book's proposed length will simply be too short to cover the material I'm hoping will be included. I regularly consult David Beazley's "Python Essential Reference", but the usefulness to me of this otherwise excellent book is compromised by the number of (platform-independent and not obsolescent) standard modules and packages that had to be left out of the book's 380 pages (htmllib, telnetlib, urllib2, CongigParser, unittest, tkinter, xml, etc.). Many of us were hoping that "Python in a Nutshell" would not only be a comprehensive reference of pretty much all of the modules in the standard library that aren't obsolescent or platform-specific, but would also cover some of the most popular third-party libraries - e.g. DB-API, PIL, mxDateTime, Numeric, win32all, wxPython, mod_python, ReportLab. My congratulations to Alex and O'Reilly if they reckon they can somehow manage to fit this all into just 400 pages; but if this won't be possible, as I worry must be the case, then may I make a plea for the book's length to be reconsidered. It would be good to have a one-stop Python reference book that would be a suitable companion to the task-oriented "Python Cookbook" - I'm hoping "Python in a Nutshell" can still be that book. By comparison, O'Reilly's "Perl in a Nutshell" is 800 pages and has the following chapters: Introduction to Perl; Installing Perl; The Perl Executable; The Perl Language; Function Reference; Debugging; Packages, Modules, and Objects; Standard Modules; CGI Overview; The CGI.pm Module; Web Server Programming with mod_perl; Databases and Perl; XML and Perl; SOAP; Sockets; Email Connectivity; Usenet News; FTP; Lightweight Directory Access with Net::LDAP; The LWP Library; Perl/Tk; Win32 Modules and Extensions; OLE Automation; ODBC Extension for Win32. Hamish Lawson From gregoryk at futures.wharton.upenn.edu Wed Sep 18 18:21:01 2002 From: gregoryk at futures.wharton.upenn.edu (GREGORY KNESER) Date: 18 Sep 2002 22:21:01 GMT Subject: Calling function from command line References: Message-ID: GREGORY KNESER (gregoryk at futures.wharton.upenn.edu) wrote: Thanks to those who followed up. I also got referred to an article at http://www.linuxjournal.com/article.php?sid=3946 involving: import sys sys.argv[1] that was helpful. Thanks again, Greg From gua81 at XXXyahoo.com Thu Sep 26 07:15:03 2002 From: gua81 at XXXyahoo.com (CheapSkate) Date: Thu, 26 Sep 2002 21:15:03 +1000 Subject: Getting last char in string. References: Message-ID: "Daniel Dittmar" wrote in message news:amuna6$erv$1 at news1.wdf.sap-ag.de... > >>> s = '' > >>> s [-1] > Traceback (innermost last): > File "", line 1, in ? > IndexError: string index out of range > >>> s [-1:] > '' > s [-1] returns a single element, s [-1:] returns a sequence. But in the > current Python definition (implementation?), single characters are strings > of length 1. > > Daniel if s[-1] returns a single element, why woulnd't it return " ? Single character are strings of length 1(as u said) and " is single character right? From christopher.saunter at durham.ac.uk Mon Sep 23 12:46:17 2002 From: christopher.saunter at durham.ac.uk (Christopher Saunter) Date: Mon, 23 Sep 2002 16:46:17 +0000 (UTC) Subject: How to call a procedure in exe file References: <4rEj9.225917$z91.9596261@bin3.nnrp.aus1.giganews.com> Message-ID: Terry Reedy (tjreedy at udel.edu) wrote: : IF you can start download with keys instead of just mouse, and if : program takes keypresses through generic standard input functions : (like C getchar()) rather than specific getkey function, start it at : the other end of a pipe. : IF you can find (or write or modify open-source code to make) a : mouse-click simulator program thats responds to dynamic input via : stdin (rather than only responding to prewritten script read as : startup), use that. A rather neater and less trouble prone way of scripting things (when you are reduced to sendkeys etc....) is Girder, and application designed to interface IR remotes to PCs. There is decent support for trapping and replaying windows messages, and it can be commanded from network sockets as well as IR etc. So you can use it as a sort of network controlled version of Win31's macro recorder (whatever happend to that?...) --- cds From loewis at informatik.hu-berlin.de Mon Sep 16 04:46:55 2002 From: loewis at informatik.hu-berlin.de (Martin v. =?iso-8859-1?q?L=F6wis?=) Date: 16 Sep 2002 10:46:55 +0200 Subject: [xml] convert funny chars to char entites? References: Message-ID: ":B nerdy" writes: > Traceback (most recent call last): > File "./batch-maid.py", line 85, in ? > generate_browse_options() > File "./batch-maid.py", line 70, in generate_browse_options > f.write(options_composer) > UnicodeError: ASCII encoding error: ordinal not in range(128) > > whats going on? You should start with telling us what f is, and what options_composer is. How are we supposed to know? > how can i fix it? I assume f is a file object, and options_composer is a Unicode object. In that case, you need to determine the encoding you want to use, and encode the Unicode object, e.g. with f.write(options_composer.encode("utf-8")) Regards, Martin From gerhard.haering at opus-gmbh.net Wed Sep 18 11:42:11 2002 From: gerhard.haering at opus-gmbh.net (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 18 Sep 2002 15:42:11 GMT Subject: Python GUI app to impress the boss? References: <96904b50.0209171305.6d65f574@posting.google.com> <6_Ph9.479711$q53.16315681@twister.austin.rr.com> <3d8868b1$0$28683@echo-01.iinet.net.au> <1Y0i9.508708$UU1.84704@sccrnsc03> Message-ID: "bap" wrote: > Does wx work with ActiveState Python? Works for me (wxPython 2.3.2.1, Python 2.2.1 from ActiveState, Windows 2000 SP3). -- Gerhard From Oschler at earthlink.net Wed Sep 11 19:38:02 2002 From: Oschler at earthlink.net (Robert Oschler) Date: Wed, 11 Sep 2002 23:38:02 GMT Subject: SuSE 7.3 Yast2-able Python 2.2.1? References: Message-ID: "Martin v. Loewis" wrote in message news:m3k7lsgnb2.fsf at mira.informatik.hu-berlin.de... > "Robert Oschler" writes: > > > If you can't satisfy the dependencies, you can try installing building > the source RPM. > Martin, I'm waiting for 8.3 :). Regarding the source RPM's, I tried installing it with kpackage and with rpm and got the same dependency problems. I guess I'll have to use the vanilla tarball. thx From anthony at computronix.com Fri Sep 13 12:55:21 2002 From: anthony at computronix.com (Anthony Tuininga) Date: 13 Sep 2002 10:55:21 -0600 Subject: calling Oracle functions In-Reply-To: <3d8210a3@news.mt.net.mk> References: <3d81f811$1@news.mt.net.mk> <3d8210a3@news.mt.net.mk> Message-ID: <1031936122.472.95.camel@chl0151.edmonton.computronix.com> On Fri, 2002-09-13 at 10:22, ?????? ?. wrote: > > > Oracle differentiates between functions and procedures so you must > > identify that you are calling a function, not a procedure. The DB API > > does not allow for this, so you must use an anonymous PL/SQL block and > > some non DB API code. The way to do this is as follows: > > ok. I also tried that, I mean a PL/SQL block... but > > > Replace the data types as appropriate. > > > v_Vars = v_Cursor.setinputsizes(p_Result = cx_Oracle.NUMBER) > > didn't know about this :)) thanks. You're welcome. > ... > > If anyone has suggestions about how to improve this, fire away... :-) > > yes, put it in the documentation. > Actually is there any documentation about cx_Oracle, past the README > file? Bits and pieces in a variety of places. The assumption (to date) has been that the DB API is sufficient for almost everything and that you really shouldn't use extensions.... :-) However, over the couple of years that I have been using the DB API I have discovered a fair number of deficiencies with respect to Oracle, in particular when it comes to performance and quirks of Oracle. It hasn't been a problem for me since I wrote cx_Oracle, but it has been my desire to consolidate the DB API document with descriptions of the extensions used by cx_Oracle -- I hope to do something about this in the next month or so. > Now a simpler question: > is it possible to specify the data source name directly not through > the alias defined in tnsnames.ora. In perl DBD I can specify a > connection string like cs = "dbi:Oracle:host=1.10.100.200;sid=TEST"? cx_Oracle is passing the string directly to Oracle, so whatever it accepts, cx_Oracle will accept. Specifically, you can take the entire string that is in your tnsnames.ora file and pass it directly as in v_TNS = (DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=opus)(PORT=1521)))(CONNECT_DATA=(SID=DEV))) v_Connection = cx_Oracle.connect("user", "pw", v_TNS) and that works just fine. Does that answer your question? -- Anthony Tuininga anthony at computronix.com Computronix Distinctive Software. Real People. Suite 200, 10216 - 124 Street NW Edmonton, AB, Canada T5N 4A3 Phone: (780) 454-3700 Fax: (780) 454-3838 http://www.computronix.com From sholden at holdenweb.com Wed Sep 11 21:39:42 2002 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 11 Sep 2002 21:39:42 -0400 Subject: [FEEDBACK] Is this script efficient...is there a better way? References: <4ZRf9.1782$Lg2.248733@news2.news.adelphia.net> Message-ID: <3hSf9.168947$l_4.98525@atlpnn01.usenetserver.com> "Bob X" wrote in message news:4ZRf9.1782$Lg2.248733 at news2.news.adelphia.net... [ ... ] > Thank you very much...as a follow up: > > #1 Can I use the same sys.exit("message here") on the IO errors as well? Sure. I assumed you would generalize the first example to the rest ... > #2 For the "print looks like a debugging statement"...how would it be > done different...in the context of my script and not a total re-write? I simply thought that since you were writing the output to the outFile anyway it seems a bit redundant to be printing it. Plus the readlines() includes the line ending, so you'd get double-spaced output fom the print statements anyway. > #3 I will test your shorter one as I have stayed away from RE till now. Well, obviously there may be problems if the keywords contains any characters special to regular expressions. Nut my example whould wqork for testing purposes. > #4 On your shorter one should xreadlines still be done for memory sake? Yes. This is a general improvement. regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From sam at localhost.localdomain Wed Sep 11 17:32:10 2002 From: sam at localhost.localdomain (newbie) Date: Wed, 11 Sep 2002 22:32:10 +0100 Subject: I must be an idiot, please pity me! Message-ID: Hello all. I'm getting very desperate now, so I have to ask for some help. I'm working on a small project and have slipped into what must be namespace hell. I have a few controlling CGI scripts that use functions from other modules to build parts of a page. Each function in these other modules contains the SQL processing and HTML building code grouped by related data. The idea being I can reuse the functions in the other scripts. All works fine, providing each modules connects to the database as a stand alone job, or I pass a database connection object thing to each and every function. I suspect that both of these are wrong, due to the ugliness or nasty system overhead of the datbase connections. What I thought I should be able to do is: CGI1.py: import mod1, mod2 connect to database create part of page using mod1.functiona create part of page using mod1.functionb create part of page using mod2.functionz close database But it doesn't seem to work like that. I've trawled though google and deja for days (plus a couple of new rider books), and no one seems to hit this problem. I must have a HUGE misunderstanding somewhere. I know mod1 and mod2 cannot see CGI.py namespace, but there must be a way of sharing the database connection, mustn't there? Help or a kick up the bottom would be really appreciated here! Sammy. From dwelch91 at nospam.attbi.com Sat Sep 21 01:51:05 2002 From: dwelch91 at nospam.attbi.com (dwelch) Date: Sat, 21 Sep 2002 05:51:05 GMT Subject: PyQt setup on Linux Mandrake 8.2 Message-ID: <3D8B4898.20808@nospam.attbi.com> I would like to setup PyQt 3.4 on my Mandrake 8.2 box. I am having difficulty, and I am worried that if I do the wrong thing, KDE will go belly-up on me since it is Qt based. First, question is: why isn't QTDIR defined by default? Is QTDIR a runtime setting or a development setting? So I set QTDIR to /usr/lib/qt2 (that seems to be where the libqt2 RPMs files are). Next question is: Since I have libqt2 already on my system, how do I add the Qt development pieces without screwing up Qt/KDE? Is /usr/lib/qt2 even the correct location? When I run SIP 3.4 build.py, it complains about tmake not being available. Is tmake included with Qt2 development files? SIP doesn't seem to have any docs, so I'm not sure how to proceed. Also, my RPM manager says that I have libqt2-devel (2.3.1-29mdk) installed. No tmake listed in the files, though. And, PyQt-devel (2.5-1mdk) is also listed as installed, but there aren't any .py files included, only .sip files (I found this curious). Installing software on Linux makes me feel like such an idiot! Any help or pointers would be much appreciated. Don From ken at hotmail.com Fri Sep 20 20:41:43 2002 From: ken at hotmail.com (Ken) Date: Sat, 21 Sep 2002 10:41:43 +1000 Subject: Python question on cgi Message-ID: Hi all, how do I pass parameters to a backend C++ program and how do I know when does the C++ program ends so that I can read the output file produced by the C++ program and print to the HTML interface? Thanks From info at voidhobo.de Tue Sep 17 14:04:15 2002 From: info at voidhobo.de (John D. Boy) Date: 17 Sep 2002 18:04:15 GMT Subject: CGI question Message-ID: Hello there! I am working on a simple CGI script to use as a framework for a website of mine. Basically, I want it to work as follows: When somebody accesses the site, a CGI (called e.g. index.py) is run. It takes an html-template and fills it with content from another file, called e.g. index.dat, and returns the completed html-document. When I want to present another page, I want the url to look like this: http://my.domain.name/?page. In that case, index.py would fill the same template with the content of a file called e.g. page.dat. Now, my problem is to find out what follows behind the question mark in my CGI script. Unless the key has a value (http://my.domain.name/?key=value), it is not in the cgi.FieldStorage dictionary. Is it simply impossible, or am I not using the right function calls? Any help is appreciated. Thanks, John -- John D. Boy "Information Superhighway" is email just an anagram for "I'm on hypertext a huge wispy rhino fart." From tjreedy at udel.edu Wed Sep 25 00:45:38 2002 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Sep 2002 04:45:38 GMT Subject: Getting started References: Message-ID: "Adam Taylor" wrote in message news:mailman.1032917851.23864.python-list at python.org... > Based on this definition, it seems to me that Python _is_ untyped, > since the type of a variable can change arbitrarily in mid-program. Python types objects and their values rather than names and the fixed chunks of memory that names usually refer to in name-typed languages. Given a definition of type that sees typeness as inhering only in names rather than objects, then yes, Python is 'untyped'. But how useful is such a viewpoint? It obscures a real difference between data models. If a language has nested scopes and allows the type of a variable to be different in different scopes, then the type associated with a particular name can change arbitrarily in mid-program (at scope changes) even if the name is strongly and statically typed within each scope. One can say that the name represents different variables in the different contexts (scopes), but the net result is similar to what Python does. Ie, one can view the rebinding of a name to an object of different type as implicitly defining a new scope with respect to that name. Terry J. Reedy From phr-n2002b at NOSPAMnightsong.com Fri Sep 20 18:42:53 2002 From: phr-n2002b at NOSPAMnightsong.com (Paul Rubin) Date: 20 Sep 2002 15:42:53 -0700 Subject: e vs exp()? References: <3a838998.0209191933.1f22e977@posting.google.com> Message-ID: <7xy99wqo42.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > At least two of us expected x**y == pow(x,y) == exp(y*log(x)) (a > standard method, and the only one I could find in Abrahamowitz and > Stegun, Handbook of Mathematical Functions) but there must be a more > direct method being used at least in some C libraries now. I would expect that the C library just uses the machine instructions for exp and pow, if they are available. All x86 processors with an FPU have these instructions. It's actually possible that an AMD Athlon could give slightly different results than an Intel Pentium. From bdesth at nospam.free.fr Sun Sep 8 21:54:14 2002 From: bdesth at nospam.free.fr (laotseu) Date: Sun, 08 Sep 2002 21:54:14 -0400 Subject: Larry Wall's comment on python... References: <3D7958DB.50903@nospam.free.fr> Message-ID: <3D7BFF46.6020306@nospam.free.fr> Thorsten Kampe wrote: > * laotseu > >>Rod Stephenson wrote: >> >>>Slashdot has a list of questions posed to Larry Wall (perl). When >>>asked his thoughts on other scripting languages, he makes the >>>following observation about python >>> >>>"Python is cool to look at small bits of, but I think the "outline" >>>syntax breaks down with larger chunks of code. I'm with Aristotle on >>>the structure of discourse--a story should have a beginning, and >>>middle, and an end. So should blocks" >>>[...] >> >>def fun(args): >>#BEGIN >> if ceci or cela: >> #BEGIN >> do_this(with_that) >> [snip a lot of code] >> #END >>#END >> >>So what the problem with blocks ? > > > Nope. Bad, bad readability, sorry. > > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*BEGINS*_! > def fun(args): > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*BEGINS*_! > if ceci or cela: > do_this(with_that) > [snip a lot of code] > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*ENDS*_! > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*ENDS*_! > > > Thorsten Ho my ! Isn't it a little bit too much ?-) laotseu From dummy1 at net-es.dk Sun Sep 8 16:22:00 2002 From: dummy1 at net-es.dk (Per Jensen) Date: Sun, 08 Sep 2002 22:22:00 +0200 Subject: [ANN] gallery2.py now useful Message-ID: gallery2.py makes static galleries from directories with pictures. It is not the final version, but beta 10 is very useful for me. New features in version 2 are 'sourcedir' and 'destdir' options along with extraction of EXIF timestamp. 'Date', 'Where', 'Who' and 'What' properties can be written in a xml file and included on the html pages. Feel free to check it out on http://www.net-es.dk/~pj/python /Per From peter at engcorp.com Fri Sep 13 21:33:17 2002 From: peter at engcorp.com (Peter Hansen) Date: Fri, 13 Sep 2002 21:33:17 -0400 Subject: Larry Wall's comment on python... References: <3D7958DB.50903@nospam.free.fr> Message-ID: <3d8291cc@news.sentex.net> Ken Seehof wrote: > Definitely not. Too wide by far. You need to reduce the indent to one > space. > > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*BEGINS*_! > def fun(args): > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*BEGINS*_! > if ceci or cela: > do_this(with_that) > [snip a lot of code] > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE IF-CLAUSE _*ENDS*_! > #||<--- LOOK HERE, LARRY, THIS IS WHERE THE FUNCTION _*ENDS*_! Oh, I didn't recognize this until now. It's COBOL! Everything with a leading # is executable code, right? ;-) -Peter From david.abrahams at rcn.com Fri Sep 27 18:59:15 2002 From: david.abrahams at rcn.com (David Abrahams) Date: Fri, 27 Sep 2002 18:59:15 -0400 Subject: Is Boost Python version 2 ready? References: Message-ID: "Robert Oschler" wrote in message news:MvZk9.12124$Lg2.3584877 at news2.news.adelphia.net... > Is Boost Python version 2 ready for primetime yet? I'd say so, except for docs. We're not making any interface-breaking changes at this point, so anything you write will continue to work for some time to come. I'm finishing the last feature before release as we speak, and everything's been passing all tests on a wide range of platforms for quite a while. Docs will be finished over the next week or so. If you want a reasonably stable version, you might try checking out the RC_1_29_0 branch of Boost. Also, the C++-sig is the best place to ask further questions (http://www.python.org/sigs/c++-sig/) -- ----------------------------------------------------------- David Abrahams * Boost Consulting dave at boost-consulting.com * http://www.boost-consulting.com From python-list at hendel.net Wed Sep 11 17:54:23 2002 From: python-list at hendel.net (Manuel Hendel) Date: Wed, 11 Sep 2002 23:54:23 +0200 Subject: problem with lists Message-ID: <20020911215423.GA30455@habana.easygolucky.de> I want to create a list of domains, every domain only once. So long I did the following, but it didn't work: #!/usr/bin/env python # import sys, string, re inputfile = open(sys.argv[-1], "r") lines = inputfile.readlines() lines = lines[3:] for line in lines: line = string.strip(line)[1:-1] fields = string.split(line, "|") domains = [] if not domains.index(fields[3:4]): domains.append(fields[3:4]) print domains This brings the following error message: :!./pop3create.py pop3data [No write since last change] Traceback (most recent call last): File "./pop3create.py", line 22, in ? if domains.index(fields[3:4]): ValueError: list.index(x): x not in list Can someone explain this to me? Thanks, Manuel -- Immature love says, "I love you because I need you." Mature love says, "I need you because I love you." -Erich Fromm From cnetzer at mail.arc.nasa.gov Sat Sep 28 00:23:47 2002 From: cnetzer at mail.arc.nasa.gov (Chad Netzer) Date: Fri, 27 Sep 2002 21:23:47 -0700 Subject: Help please with menubars In-Reply-To: <3d9516b3$1_7@goliath.newsgroups.com> References: <3d9516b3$1_7@goliath.newsgroups.com> Message-ID: <200209280423.VAA20949@mail.arc.nasa.gov> On Friday 27 September 2002 20:54, mongo57a at comcast.net wrote: > Specifically: I have > an "exit" item on the menubar and if the user clicks on "exit", the > window should be closed. What I don't want is a pulldown with "exit" > as a button option. I'm assuming you are talking about Tkinter here: If so, your 'menubar' is a Tk menu, with cascade buttons in it. It is also possible to attach a "command" button to it: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import Tkinter Tk = Tkinter def output_func(): print "T.I.S.M. is a fine Aussie band." return root = Tk.Tk() #This opens a Toplevel() menubar = Tk.Menu( root ) menubar.add_command( label='T.I.S.M.', command=output_func ) root.configure( menu=menubar ) #Attach menubar to the Toplevel root.mainloop() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ And if that doesn't work for you, then use the 'bind' command on the button or widget that you want to trigger the exit, and look for "" events. Attach that to an exit function. Other window toolkits should have analogous methods of doing this. P.S. In my version, I just reuse the root Toplevel; you can also attach a menubar at creation time. -- Chad Netzer cnetzer at mail.arc.nasa.gov From ajs at ix.netcom.com Mon Sep 16 20:20:18 2002 From: ajs at ix.netcom.com (Arthur) Date: Mon, 16 Sep 2002 20:20:18 -0400 Subject: Not sure how to phrase this question Message-ID: <000b01c25de0$010816c0$9865fea9@arthur> I wrote - >I'll certainly take a simple solution to my problem - though I think some elucidation of the behavior in my original post might >be of some interest to folks other than just myself, in any case. Is the simple solution that the factory should be a function, not a class? Art From sholden at holdenweb.com Sun Sep 8 14:52:12 2002 From: sholden at holdenweb.com (Steve Holden) Date: Sun, 8 Sep 2002 14:52:12 -0400 Subject: Larry Wall's comment on python... References: Message-ID: wrote ... [ ... ] > Having read Wall's comments on Slashdot, I think he is really just mildly > complaining about ridiculously long page-widths in his editor, not really > slashing Python seriously. He's just giving some props to his own baby at > the expense of another. (He had to say something, right?) You must agree > that Python can lead you to horizontal scrolling in your editor - the bane > of user interface design. > Well, using a four-space indent helps a lot -- tabs are passe nowadays. Further, lines can easily be broken and continued, which helps to make long lines more manageable. lastly, of course, if your code has nine levels of indentation it might well be time to refactor it for improved readbility. > Yes, I am new here. Hi, everyone. Hi, and welcome! regards ----------------------------------------------------------------------- Steve Holden http://www.holdenweb.com/ Python Web Programming pydish.holdenweb.com/pwp/ Previous .sig file retired to www.homeforoldsigs.com ----------------------------------------------------------------------- From matt at mondoinfo.com Wed Sep 25 14:58:54 2002 From: matt at mondoinfo.com (Matthew Dixon Cowles) Date: Wed, 25 Sep 2002 18:58:54 GMT Subject: combining mailbox and email modules References: Message-ID: On Wed, 25 Sep 2002 06:36:29 GMT, Bob Horvath wrote: > I am having trouble figuring out how to get the mailbox and email > modules to play together so that I can use email module functions on > every mail in the mailbox. Is there a way to feed a factory from > the email module to mailbox module? Yes, there is: >>> import mailbox >>> import email >>> i=mailbox.Maildir("Mail/testmail",email.message_from_file) >>> i.next() >>> i.next() Regards, Matt From huxley1 at westnet.com.au Tue Sep 24 07:15:28 2002 From: huxley1 at westnet.com.au (Jeremy Rew) Date: Tue, 24 Sep 2002 19:15:28 +0800 Subject: Copying Elements using PyXML Message-ID: <5.1.1.6.0.20020924190151.00b96068@localhost> I have 2 XML documents. I would like to copy the entire structure of one document into a child element of the other, but i cannot copy the root node across: I get the following error from Zope: Error Type: HierarchyRequestErr Error Value: Node manipulation results in invalid parent/child relationship. the structures are as follows:
and would like to copy this into the following format:
I have written all the code to build 'xformimport','docID' and 'document', but just need to copy 'person' across. I figure i may be missing an easy solution here, so any help/ideas will be appreciated. I am using PyXML 0.8.1 and python 2.1.3. thanks Jeremy From brueckd at tbye.com Wed Sep 18 12:31:41 2002 From: brueckd at tbye.com (brueckd at tbye.com) Date: Wed, 18 Sep 2002 09:31:41 -0700 (PDT) Subject: Earing money with Python software (was: More on Protecting Source Code) In-Reply-To: Message-ID: On Wed, 18 Sep 2002, Michael Str?der wrote: > brueckd at tbye.com wrote: > > free-for-personal-use-but-companies-must-pay approach when possible. > > The problem with getting some bucks from a company is the amount of time > spent during decision taking and ordering process. For you to earn 300 > bucks for your software the company spends another 500+ bucks for > working time until the money gets out. Well, it really varies by company of course. Most places I've worked only require that much bureaucracy for larger purchases. For small stuff (under a few hundred dollars) it usually amounts to me informing a superior that tool X is needed and worthwhile. After that I just buy it myself and turn in a simple expense report. > IMHO that's why it's so hard to > sell small packages of rather cheap software to big companies. That's why you don't sell it for $300. Seriously: if it's a small and cheap package then $300 (I'm assuming US$300) is often too high for small businesses and many individuals anyway, and for large companies it might be expensive enough to trigger more purchasing overhead (at my current job that price could go either way). So... you sell your product with a single seat license for, say, $100 and then offer a site license for e.g. $500 as well as a renewable support package for $1000 a year or whatever. You also give 'em discounts when you release a new version next year. -Dave From bob at eleaston.com Fri Sep 6 20:50:45 2002 From: bob at eleaston.com (Bob Easton) Date: Fri, 6 Sep 2002 20:50:45 -0400 Subject: Interrupting Python References: Message-ID: OS = Win2000 Python = 2.2 Python execution environment = PythonWin Using catchCtlC.py in a command line environment works as you expect. When I hit Ctrl-Break, Windows displays "^C" and then a command prompt. If I hit Ctrl-C, the exception handler catches it and displays the results as specified in catchCtlC/py However, my preferred execution environment is PythonWin, not a command prompt. There, neither Ctrl-break, not Ctrl-C have any effect. That could easily be a bug with PythonWin. -- Bob Easton "Bengt Richter" wrote in message news:albel2$7te$0 at 216.39.172.122... > On Fri, 6 Sep 2002 17:38:55 -0400, "Bob Easton" wrote: > > >Thanks to all. My system is Win2K. Python simply ignores Ctrl-c and > >Ctrl-break. I think I'll fall back to using file existence as a simple > If this were true as generally as you put it, we should be looking for a bug. > > Would you put the following listed catchCtlC.py file in a convenient directory, > and then go there with **a plain "DOS" command window**, and type the command > > catchCtlC.py 1000 > > It should complete in a short time. Then try it again, hitting Ctrl-C before > it finishes. If you have a fast machine and need more time, add another zero > to the 1000. Let us know if no interrupt is reported for either Ctrl-C or Ctrl-Break. > > Then tell us what's different about your program. > > ---< catchCtlC.py >------------------ > i=x=0 > def foo(n): > global i,x > for i in xrange(n): > x = i**100 > > if __name__ == '__main__': > import sys > try: > foo(int(sys.argv[1])) # call your thing here instead > except KeyboardInterrupt: > print 'Interrupted by Ctrl-C' > else: > print 'Exited w/o interrupt' > print 'FHOI, the last i**100 x value: %s**100 = %s' % (i, x) > ---< catchCtlC.py >------------------ > > >semaphore. That will be good enough and cheap enough for this application. > > > > >-- > >Bob Easton > > > > > >"David LeBlanc" wrote in message > >news:mailman.1031345649.9840.python-list at python.org... > >> > I have a script that can run, accessing network resources, for > >> > several days. > >> > Since the script does not normally need keyed input, exception > >processing > >> > does not raise the keyboard exception until after the program > >> > ends normally. > >> > I would like to be able to interrupt if from the keyboard, but have not > >> > learned the trick. How can I do this? > >> > > >> > -- > >> > Bob Easton > >> > >> I have had the experience of Python progs not responding to ctrl-c or > >ctrl-d > >> on Windows, but I found that ctrl-break works every time. > >> > >> Dave LeBlanc > >> > >> > Also, please post responses below what you are responding to ;-) > > Regards, > Bengt Richter From hst at empolis.co.uk Fri Sep 13 12:47:11 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Fri, 13 Sep 2002 17:47:11 +0100 Subject: Help with regular expression using findall and .*? Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB04F417@hendrix.empolisuk.com> czrpb wrote > > Harvey: > > Great thanks!! And thanks for sticking to my question's > requirements. > > Ok, this is what we thought around here. But what I do not > understand is why any backtracking data is being kept? The > '?' in '.*?' means it is non-greedy right? When would > backtracking ever occur using '.*?'? What am I missing? > > < > > On Fri, 13 Sep 2002, Harvey Thomas wrote: > > > czrpb wrote > > > > > > Could anyone help out with rewriting (still using regular > expressions) > > > the following so that it does not cause an exception: > > > > > > import re > > > > > > s1=('macro\n'+'a'*200+'\norcam\n')*10 > > > s2=('macro\n'+'a'*20000+'\norcam\n')*10 > > > > > > p=re.compile(r'macro.*?orcam',re.DOTALL) > > > > > > for x in re.findall(p,s1): > > > print x > > > > > > for x in re.findall(p,s2): > > > print x > > > > > > thanks!! Quentin Crain > > > > > > > You need to be very careful about using .*? as the engine > "only" allows 10,000 backtracks > > > > Try this > > > > p = re.compile('macro(?:[^o]+|o(?!rcam))*orcam') > > for x in p.findall(s2): > > print x > > > > HTH > > > > Harvey > > Don't think I, or even Mr. Friedl can explain this concisely. If you are interested in knowing about the mechanics of REs, the best reference book is the 2nd edition of "Mastering Regular Expressions" by Jeffrey Friedl ISBN 0-596-00289-0. A good tip though is to try and use negated character classes whenever possible rather than use "." Harvey _____________________________________________________________________ This message has been checked for all known viruses by the MessageLabs Virus Scanning Service. From erno-news at erno.iki.fi Tue Sep 10 07:52:52 2002 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 10 Sep 2002 14:52:52 +0300 Subject: UNIX processes References: Message-ID: In article , "Bo M. Maryniuck" writes: | Hi, all. | Somebody know how to list all the processes in RIGHT way on Linux/UNIX? | I need to find the zombies, stopped processes etc. use the ps program (ps -e works on linux). there is no other standard api for it. -- erno From steven_shaw at adc.com Wed Sep 11 19:54:00 2002 From: steven_shaw at adc.com (Steven Shaw) Date: 11 Sep 2002 16:54:00 -0700 Subject: dynamism References: <66715c02.0209091923.265fe77e@posting.google.com> <3d7e209a_1@news.iprimus.com.au> Message-ID: <66715c02.0209111554.48aeedc8@posting.google.com> Michael Chermside wrote in message news:... > Steven Shaw wrote: > >>An object of a builtin type, or with __slots__ defined in the class and > >>all base classes does not have a __dict__ attribute. > > > > > > Does this mean that the attributes are stored in a more efficient way? > > > > Is there a way to implement "record-based" object layout rather than > > "associative-array based" object layout? > > In short, YES. Excellent. > > See http://python.org/doc/2.2.1/whatsnew/sect-rellinks.html . > Unfortunately, http://www.python.org/peps/pep-0253.html doesn't give > full details since they haven't been written up yet. Thanks for the links. From bslesins at best.com Mon Sep 9 01:42:46 2002 From: bslesins at best.com (Brian Slesinsky) Date: 8 Sep 2002 22:42:46 -0700 Subject: Larry Wall's comment on python... References: Message-ID: Rod Stephenson wrote in message news:... > Slashdot has a list of questions posed to Larry Wall (perl). When > asked his thoughts on other scripting languages, he makes the > following observation about python > > "Python is cool to look at small bits of, but I think the "outline" > syntax breaks down with larger chunks of code. I'm with Aristotle on > the structure of discourse--a story should have a beginning, and > middle, and an end. So should blocks" > > I'm not quite sure what he's trying to get at here - I guess that for > a long heavily indented chunk of code, you could lose track of the > overall structure, but I don't write code this way. > > Any comments? He's repeating the standard newbie complaint. However, I think the fact that so many people have repeated this for so long is significant. Long-term Python programmers tend to forget how weird it is to some newcomers to end a function or class just by *stopping*. It feels abrupt and rather fragile, particularly when you don't have a firm grasp of the language. If newbies have complained for this long, the complaint's not going away, and if we're serious about making Python easy to pick up it might be good to listen. I've long thought that Python would be improved by an optional "end" statement. Example: class Foo: def bar(self, x): # ... # (imagine 20 more short methods definitions here) end Foo # or "end class Foo", or "end class", or, just "end" Of course it's unnecessary and should be entirely optional. Putting an "end" after every block would certainly be overly verbose and bad style. But ending major blocks in a way that's syntax-checkable might catch the occasional indentation error and/or make error messages clearer. The main drawback is another reserved word, but it's one that's reserved in several other programming languages. I also think there would be a certain satisfaction in having a proper ending, even for folks who are entirely comfortable with Python's indentation. It's like "Q.E.D." at the end of a proof, or "The End" at the end of children's book, or signing a message even though the "From" header line makes it entirely redundant. - Brian Slesinsky From hst at empolis.co.uk Mon Sep 2 07:06:08 2002 From: hst at empolis.co.uk (Harvey Thomas) Date: Mon, 2 Sep 2002 12:06:08 +0100 Subject: Making regex suck less Message-ID: <8FC4E7C302A6A64AAD5DB1FA0E825DEB220CF9@hendrix.empolisuk.com> John La Rooy wrote > > Carl Banks wrote: > > Gerhard H?ring wrote: > > > >>>which means the real time is not spent in the compile() > function, but > >>>in the match or find function. So basically, couldn't one > come up with > >>>a *human readable* syntax for re, and compile that instead? > >> > >>That's equally powerful? Most probably not. > > > > > > Why not? It won't be as fast, but it should be able to do > anything a > > regexp can do, and would be much more versatile. > > > > > I think the main problem is that *human readable* doesn't map really > well onto regular expressions. > > What would the equivalent of r"(.)(.)(.)\3\2\1" > This means a "palindrome of 6 characters" > But it is unlikely that the human readable processor would understand > that (isn't it??) > > It would be more likely to look like this (I haven't put too much > thought into this) > "anything,anything,anything,same_as_3rd,same_as_2nd,same_as_1st" > or would you like to suggest something else? > > palindrome_6 = re.compile(r"(.)(.)(.)\3\2\1") > palindrome_6 = > re.compile("anything,anything,anything,same_as_3rd,same_as_2nd > ,same_as_1st") > > Sure there are some cases where the re is loaded with meta > characters... > > hmmm > OK is this about writing maintainable code or people not wanting to > learn all the ins and outs of re's? > > John I used to use OmniMark a lot when it was free. With OmniMark's equivalent of REs, the palindrome would be any => char1 any => char2 any => char3 char3 char2 char1 I selected a non-trivial OmniMark RE from old code at random and came up with (' a.whole (white-space+ "SYSTEM"? white-space* '"' upto-inc('"'))? The (untested) Python RE equivalent is something like """(?P Hi all. I installed quite a few packages trying to upgrade to Gnome 2.0 and got a problem in another area. Tried to run eRoaster again, and the the following message: ------- Traceback (most recent call last): File "/usr/local/bin/eroaster", line 9, in ? from main import Application File "/usr/local/lib/eroaster/main.py", line 49, in ? from gnome.ui import GnomeApp, GnomeFileEntry, GnomeErrorDialog, GnomeAbout, GnomeOkDialog File "/opt/gnome/lib/python2.2/site-packages/gtk-1.2/gnome/ui.py", line 3, in ? import _gnomeui ImportError: /opt/gnome/lib/libgnome.so.32: undefined symbol: libiconv_open ------- I checked libgnome, and didn't find any reference to libiconv in it (using ldd). So, I wonder why is libgnome needing libiconv_open at all? Sorry - this is maybe a gnome problem, but I didn't find any ref at all to this on the 'net, and this may have something to with the python config? John BTW, I separated the 'import _gnomeui, gnome' from ui.py in two lines to detect which was the one failing. From e_fax_t at hotmail._ZAPME_.com Thu Sep 26 16:36:19 2002 From: e_fax_t at hotmail._ZAPME_.com (Justin) Date: Thu, 26 Sep 2002 22:36:19 +0200 Subject: readlines() and "binary" files References: <3d90cacf$0$30457$afc38c87@sisyphus.news.be.easynet.net> <9r8k9.46422$V7.11170409@twister.socal.rr.com> <3d91de2d$0$30457$afc38c87@sisyphus.news.be.easynet.net> <9yqk9.143972$ub2.3161265@news1.tin.it> Message-ID: <3d936f05$0$30456$afc38c87@sisyphus.news.be.easynet.net> > Pity you ruled out defining your own iterator -- I had ruled it out by laziness, but since you were kind enough to provide an implementation, I'll definitely use it! Thanks a lot, it works nicely. Gee I can't wait for that nutshell to crack !-} Regards, Justin. From unendliche at hanmail.net Fri Sep 13 09:44:19 2002 From: unendliche at hanmail.net (Seo Sanghyeon) Date: 13 Sep 2002 06:44:19 -0700 Subject: Python evaluator via Javascript Message-ID: <45e6545c.0209130544.1664d78f@posting.google.com> Python FAQ Entry 4.15. Is it possible to write obfuscated one-liners in Python? (http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.015.htp) As we know from the FAQ, Python is a nice language for writing obfuscated one-liners. (wink) Now you can test your one-liners on the web -- using 'Python evaluator via Javascript'. Since it is for one-liners, you should type a expression. No statement allowed. Try the following: (taken from the FAQ) # without newline filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0, map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000))) Mysteriously, it works. I couldn't believe it. Copy the following 116 lines (2825 bytes) and execute. It took about 3 hours for me to write. Perhaps I have too much free time in my hands. Tested on Win 98, Python 2.2.1, MSIE 6.0. ---- Python evaluator via Javascript ---- def prepare(): import os if not os.path.exists('httpd'): os.mkdir('httpd') if not os.path.exists('httpd/cgi-bin'): os.mkdir('httpd/cgi-bin') fp = open('httpd/eval.htm', 'w') fp.write(dhtml) fp.close() fp = open('httpd/cgi-bin/eval.py', 'w') fp.write(pycgi) fp.close() def server(): import os os.chdir('httpd') from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler serv = HTTPServer(('', 1234), CGIHTTPRequestHandler) serv.serve_forever() def main(): import thread thread.start_new_thread(server, ()) import time time.sleep(10) import webbrowser webbrowser.open('http://localhost:1234/eval.htm') def idle(): while 1: pass dhtml = ''' Python Evaluator via Javascript
>>>