From mwilson at the-wire.com Mon Apr 7 08:26:24 2003 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 07 Apr 2003 08:26:24 -0400 Subject: nntplib, huge xover object References: <443s8v8mehlrhapp0d6af7k0ps22k2tvii@4ax.com> <09is8votcf3116a94euite6vhdfffgefko@4ax.com> Message-ID: In article , Mike Meyer wrote: >Robin Munn writes: >> xover(start, end, open('foo.txt', 'w')) >> >> See? File-like object gets created, passed to your function, and then >> automatically garbage-collected (and thus closed) when your function >> returns. > >The garbage collection happening when your function returns is >implementation specific. It works that way in CPython, but not >Jython. You should always explicitly close files to make sure they get >closed - and the output flushed, in this case - when you're done with >them. That's why I prefer to think of Jython as a different language. The idea of a service that can clean up and quit when the last client stops using it is just too appealing. Regards. Mel. From robin at jessikat.fsnet.co.uk Thu Apr 17 19:06:47 2003 From: robin at jessikat.fsnet.co.uk (Robin Becker) Date: Fri, 18 Apr 2003 00:06:47 +0100 Subject: How many of you are Extreme Programmers? References: <3E9EA707.4DB53582@engcorp.com> Message-ID: In article , Jp Calderone writes ...... > > Only if you direct the evolution in the wrong way >:) > > Jp ..... well if you know how to direct the solution the problem is solved (in principle at least) :) -- Robin Becker From peter at engcorp.com Tue Apr 22 05:22:25 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 22 Apr 2003 05:22:25 -0400 Subject: Python implementation for a web spider \ site mirroring References: <662cede5.0304220114.54e4dd10@posting.google.com> Message-ID: <3EA509D1.EDCA8733@engcorp.com> Tzahi wrote: > > I need to copy complete web sites form the web. > > I think Python is a natural fit for this task, with the intensive HTML > and HTTP support. Being lazy, I would rather have someone else's > implementation, so that I do not start from scratch. Perhaps you could use Tools/websucker.py from the standard distribution. -Peter From km-news1 at onlinehome.de Tue Apr 22 09:31:40 2003 From: km-news1 at onlinehome.de (Klaus Meyer) Date: Tue, 22 Apr 2003 15:31:40 +0200 Subject: Pythonwin don't show the complete list in interactiv window!? References: Message-ID: >> The interactive windows shows only a part of the list (last value 771). >> (Win2000) > > It is a Scintilla bug or limitation. Newer versions of Scintilla don't > stop at 771 but there are still limits. Thanks. For a Python beginner it's a little frustrating to search bugs in my own code but could not find and then later find out, that it was a tools bug. Because Idle also has bugs (for example, after a little working time won't save my source file so i lost the new source-version!) i switched to ConTEXT (http://www.fixedsys.com/context/). -- Gru? - regards Klaus :-) From max at alcyone.com Fri Apr 11 23:59:12 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 11 Apr 2003 20:59:12 -0700 Subject: Singletons References: Message-ID: <3E978F10.6EA61594@alcyone.com> Roy Smith wrote: > It seems like a pretty reasonable implementation, but I don't > understand > one thing about it. What is the point of: > > # Store instance reference as the only member in the handle > self.__dict__[ '_Singleton__instance' ] = Singleton.__instance > > I don't see that it does anything useful. Is there something subtle > that I'm missing? I presume you're confused about the '_Singleton__instance' key? It's because a double underscore for a class or instance attribute is mangled. For instance: >>> class C: ... def __init__(self): ... self.__x = 123 ... >>> 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' >>> c._C__x 123 So this pattern is really just diddling with the new object and assigning something to a "private" attribute (e.g., one prefixed with a double underscore). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ When you talk to her / Talk to her \__/ India Arie WebVal / http://www.alcyone.com/pyos/webval/ URL scanner, maintainer, and validator in Python. From nikolai.kirsebom.NOJUNK at siemens.no Thu Apr 24 07:29:44 2003 From: nikolai.kirsebom.NOJUNK at siemens.no (Nikolai Kirsebom) Date: Thu, 24 Apr 2003 13:29:44 +0200 Subject: Question about accessing class-attributes. Message-ID: <0kifav8dfcbu0t8j4qrrkq6ag7gcg1s062@4ax.com> Given the following class hierarchy: class A(object): InstCount = 0 def __init__(self): self.__class__.__dict__['InstCount'] += 1 class B(A): InstCount = 0 class C(A): InstCount = 0 Is the syntax used for incrementing the class-attribute for every instanciation 'the way' it should be done ? Nikolai Kirsebom From andrew-pythonlist at puzzling.org Sat Apr 19 13:10:22 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sun, 20 Apr 2003 03:10:22 +1000 Subject: Parent references: hot or not? In-Reply-To: <1050772061.14712.55.camel@ida.dylanreinhardt.com> References: <1050763980.14721.41.camel@ida.dylanreinhardt.com> <20030419145756.GA25916@meson.dyndns.org> <1050771656.14717.48.camel@ida.dylanreinhardt.com> <1050772061.14712.55.camel@ida.dylanreinhardt.com> Message-ID: <20030419171022.GC1316@frobozz.local> On Sat, Apr 19, 2003 at 10:07:41AM -0700, Dylan Reinhardt wrote: > On Sat, 2003-04-19 at 10:00, Dylan Reinhardt wrote: > > > Sounds like I should be sure to write a __del__ method for Container > > that ensures things work correctly. > > And upon re-reading your post you say *not* to do that... :-) > > I'd like to understand that a bit better. What would be wrong with: > > class Container: > > def __del__(self): > # ensure all Items are deleted first > for item in self.items.keys(): > del self.items[item] Calling self.items.clear() would be simpler than looping. But it's redundant. The garbage collector will collect cycles for you automatically, so don't waste your time doing unnecessary house-keeping -- particularly because if you *do* define __del__, but somehow accidentally end out with that object in a reference cycle anyway, it can't be collected. See http://python.org/doc/current/lib/module-gc.html#l2h-312 for a brief explanation. There are very few reasons to define __del__ in modern versions of Python. -Andrew. From martin at v.loewis.de Sun Apr 6 17:40:25 2003 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 06 Apr 2003 23:40:25 +0200 Subject: Debugging embedded python In-Reply-To: References: Message-ID: Syver Enstad wrote: > I have the python interpreter embedded in a daemon/service (this is > win2k so it's a service). I'd really like to be able to debug the > python code that is running. I was thinking of popping up a console > window to be able to run pdb, how does one go about it to accomplish > this? Are there any code doing similar things or articles. I recommend that you find a non-daemon mode of operation, and support debugging there. This has tradition on Unix (atleast): many daemons support a do-not-fork-into-background-do-not-fork-many-processes mode, to simplify debugging. If you find you must study the running service, use print statements. There can be very advanced forms of print statements, like the cgitb module for CGIs (which are also a form of embedding). Regards, Martin From max at alcyone.com Mon Apr 21 15:45:35 2003 From: max at alcyone.com (Erik Max Francis) Date: Mon, 21 Apr 2003 12:45:35 -0700 Subject: coverting list back to string References: <3cf72d52.0304211132.799d8afb@posting.google.com> Message-ID: <3EA44A5F.6ADA09B8@alcyone.com> scn wrote: > my quest: i know that output.write(remove) is not correct. you > cannot use the 'write' method on a list. Presumably you want to join the list back into a string, with something like: ' '.join(remove) or in general S.join(L) where S is a delimiter string and L is a sequence. Note that this may have an surprising effect since L.split() with no argument will split on _any_ block of whitespace, whereas ' '.join(L) will only join the parts back with a single space: >>> L = 'this has a lot of spaces'.split() >>> ' '.join(L) 'this has a lot of spaces' This may not bother you, but I thought I'd point it out as a clear difference. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ The revolution will not televised \__/ Public Enemy Maths reference / http://www.alcyone.com/max/reference/maths/ A mathematics reference. From claird at lairds.com Mon Apr 14 17:39:16 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 14 Apr 2003 21:39:16 -0000 Subject: inserting Python commands into HTML documents References: <6-CdnUrJoLKFkQajXTWcqA@comcast.com> Message-ID: In article <6-CdnUrJoLKFkQajXTWcqA at comcast.com>, Em wrote: >These options all seem to require me to install 3rd party software onto >the server of this company, and I believe that to be outside of the >scope of the test project. > >The only issue is that I want it to be invisible that I'm pulling from a >CGI script (I don't want the URL bar to say >"www.mywebsite.com/cgi-bin/myProj.py?page=projects", I want it to simply >say "www.mywebsite.com/projects.html" or "www.mywebsite.com/projects.php"). > >Is there a way for me to send my output to /index.html, /projects.html, >etc.? . . . We're using words in different ways. Crudely, yes, all the usual active page methods can pass data either visibly (".../myProj.py?page=projects") or not-so-visibly (".../myProj.py")--withOUT regard to whether CGI is involved or not. And equally without regard to language; PHP can do just as much and just as little, in this regard. Given this, I conclude I have no idea what you mean by "send my output to /index.html ..." and so on. I'm reasonably confident Python can do it, whatever it is. The problem remains ill-specified. One of the things is that we'll need to know about the Web server avail- able. If someone has asked you, "Demonstrate how to use a Web server that only supports PHP but without using PHP", then my summary will be that he's hazing you. -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From sean at activeprime.com Tue Apr 29 16:42:40 2003 From: sean at activeprime.com (Sean) Date: 29 Apr 2003 13:42:40 -0700 Subject: Determining Unicode encoding. Message-ID: I'm really new to dealing with unicode, so please bear with me. I'm trying to add unicode support to a program I'm working on, and I'm getting stuck a little when printing a unicode string to a file. I know I have to encode the string using an encoding (UTF-8, UTF-16, latin-1, etc). The problem is that I don't know how to determine what the *right* encoding to use on a particular string is. The way I understand it, utf-8 will handle any unicode data, but it will translate characters not in the standard ASCII set to fit within the 8-bit character table. My problem is I'm handling data from a lot of different encodings (latin, eastern, asian, etc) and I can't allow data in the strings to be changed. I also can't (at least I don't know how to) determine what encodings the strings are using. IE, I don't know what strings are from what languages. Is there any way to determine, from the unicode string itself, what encoding I need to use to prevent data loss? Or do I need to find a way to determine beforehand what encoding they are using when they are read in? Am I even asking the right questions? I'm really pretty lost and my O'Reilly books arn't helping very much. -Sean From xxdigitalhellxx at hotmail.com Mon Apr 7 15:18:43 2003 From: xxdigitalhellxx at hotmail.com (sik0fewl) Date: Mon, 07 Apr 2003 13:18:43 -0600 Subject: super question In-Reply-To: References: Message-ID: Danra wrote: > Hi, > > I must be doing something wrong, but it seems that the typical use for > the 'super' function, suggested in its help and in the python library > refernce, does not work for me. > > Here's my experience with 'super': > > >>>>class b: > > pass > > >>>>class c(b): > > pass > > >>>>super(c) > > Traceback (most recent call last): > File "", line 1, in ? > super(c) > TypeError: super() argument 1 must be type, not classobj > > >>>>super(c,c()) > > Traceback (most recent call last): > File "", line 1, in ? > super(c,c()) > TypeError: super() argument 1 must be type, not classobj > > What am I doing wrong? > > P.S. pardon the pun in the question's subject :) I'm not sure if this is what you're looking for, but here it is... >>> class b: ... pass ... >>> class c(b): ... pass ... >>> super(type(c)) , NULL> >>> super(type(c), c) , > I'm not even familiar with the function and didn't even look it up, but maybe this is what you're looking for :) -- Ryan From b.maryniuk at forbis.lt Thu Apr 24 08:06:20 2003 From: b.maryniuk at forbis.lt (Bo M. Maryniuck) Date: Thu, 24 Apr 2003 14:06:20 +0200 Subject: What means exactly "Memory error"? Message-ID: <200304241406.20833.b.maryniuk@forbis.lt> Hello, all. I made an application which uses 4DOM. I have a big (~10M) autogenerated HTML file from an Oracle tool. The problem is to public it. Nobody want to open 10MB HTML file in their browser. OK, so the main idea was to split it using frequently repeated
tag. Then I got ~1500 parts. OK, now I parse each part with HtmlLib and keep it tree somewhere in the variable (in memory). Then after each part is parsed I want to do a lot of changes inside the document to adapt it to using with Zope in the cycle. Using this idea with the files up to 2-3M -- no problem. But when I took biggest one, it crashes with strange weird stuff I can't exaplain. Somebody knows what "Memory error" might appear and how to avoid (if possible) it? Used software: Python 2.2 4Suite (from the CVS) latest PyXML. OS Linux SuSE 7.1 Pro with it originally compiled kernel 2.4.0-64GB-SMP Hardware: Four CPU machine: Pentium III (Cascades) 700Mhz RAM (size): 4GB A lot of free space on hard disks... Full traceback is here: -----------------------8<------------------------------------- Traceback (most recent call last): File "./mono2chunk.py", line 244, in ? mc.processDocument() File "./mono2chunk.py", line 138, in processDocument self.__doc_complete[_ref] = self._evaluateChunk(self.__parseHtmlDoc(partData), _ref) File "./mono2chunk.py", line 67, in __parseHtmlDoc doc = HtmlLib.FromHtml(''.join([Mono2Chunks.__html_header_, File "/usr/lib/python2.2/site-packages/_xmlplus/dom/ext/reader/HtmlLib.py", line 89, in FromHtml return Reader().fromString(text, ownerDoc, charset) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/ext/reader/HtmlLib.py", line 70, in fromString return self.fromStream(stream, ownerDoc, charset) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/ext/reader/HtmlLib.py", line 28, in fromStream self.parser.parse(stream) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/ext/reader/Sgmlop.py", line 57, in parse self._parser.parse(stream.read()) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/ext/reader/Sgmlop.py", line 166, in finish_starttag parent.appendChild(element) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/FtNode.py", line 256, in appendChild newChild._4dom_fireMutationEvent('DOMNodeInserted',relatedNode=self) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/FtNode.py", line 378, in _4dom_fireMutationEvent relatedNode,prevValue,newValue,attrName) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/Event.py", line 120, in initMutationEvent Event.initEvent(self,eventTypeArg, canBubbleArg, cancelableArg) File "/usr/lib/python2.2/site-packages/_xmlplus/dom/Event.py", line 93, in initEvent self.bubbles = canBubbleArg MemoryError -----------------------8<------------------------------------- -- Regards, Bogdan A witty saying proves nothing. -- Voltaire From rcook at llnl.gov Tue Apr 1 23:05:17 2003 From: rcook at llnl.gov (Richard Cook) Date: Tue, 1 Apr 2003 20:05:17 -0800 Subject: PyObject_CallFunction with keywords? In-Reply-To: References: Message-ID: Never mind, duh: PyEval_CallObjectWithKeywords seems like it may do the trick. :-) At 6:39 PM -0800 4/1/03, Richard Cook wrote: >Hi, >Short question: >Is it possible to pass keywords to a function with PyObject_CallObject()? > > >Long question: >I am using an embedded Python interpreter in our C program to >execute a method from a Python module (pexpect, to be exact). At a >certain point, I wish to do the equivalent of the following Python >code in my C code: > >result = obj.expect("hello", timeout=50); > >So I have a PyObject *f which points to obj.expect, and a PyObject >*s which is a list containing the string "hello". I figure I have >to do: >PyObject_CallObject(f, s, k) >where k is the timeout parameter, but this does not match the param >list for PyObject_CallObject(). > >My question is, how can I pass keyword parameters such as the >timeout parameter in my example to a function which accepts them? >The documentation for PyObject_CallObject says it is equivalent to >apply(o, args), but says nothing about the actual apply syntax: >apply(o, args, keywords) >where keywords is a dictionary. > >-- >Richard Cook >Lawrence Livermore National Laboratory >Bldg-451 Rm-2043, Mail Stop L-561 >7000 East Avenue, Livermore, CA, 94550, USA >phone (925) 423-9605 (work) fax (925) 423-8704 >--- >Information Management & Graphics Grp., Services & Development Div., >Integrated Computing & Communications Dept. >(opinions expressed herein are mine and not those of LLNL) -- Richard Cook Lawrence Livermore National Laboratory Bldg-451 Rm-2043, Mail Stop L-561 7000 East Avenue, Livermore, CA, 94550, USA phone (925) 423-9605 (work) fax (925) 423-8704 --- Information Management & Graphics Grp., Services & Development Div., Integrated Computing & Communications Dept. (opinions expressed herein are mine and not those of LLNL) From mcclaine at comcast.net Mon Apr 14 01:56:37 2003 From: mcclaine at comcast.net (Em) Date: Mon, 14 Apr 2003 01:56:37 -0400 Subject: Inserting Python commands into HTML documents Message-ID: Hello, I am an extremely new member of the Python family. I had a job interview where they charged me with the task of creating a (fake) corporate website using Python in ten days--with two left now. The problem is that what I have read seems to say Python is a CGI language... Am I remiss in believing that my website is going to be completely run from inside a couple .PY files in the CGI-BIN? Is there a way for it to act more like PHP, as in run Python commands from inside the (index|contacts|about|etc).html or at least simulate that behavior? (This is on a linux server and I am not to use PHP, FYI.) Thank you all for any assistance! From gh at ghaering.de Tue Apr 8 04:49:43 2003 From: gh at ghaering.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 8 Apr 2003 08:49:43 GMT Subject: Datagrid-Widget for Python? References: Message-ID: Rainer Klueting wrote: > [...] > I had already seen that there is another GUI toolkit called wxWindow, > and I even had downloaded it. But my impression was, that Tkinter is > kind of a GUI-standard for Python, and I tried to stick to the > standard. > > Is that true? Tkinter is "standard" in the sense that it is shipped with Python. No more, no less. > Do you have any information about how widespread the use of > wxWindows is? I don't want to steer into a dead-end-road. For the usage of wxPython, the only reliable number you'll likely get is the traffic on the wxPython mailing list. It'll show you that it is widely used among Python programmers. [1] -- Gerhard [1] Those that do GUIs, anyway. From rmunn at pobox.com Wed Apr 2 12:26:23 2003 From: rmunn at pobox.com (Robin Munn) Date: Wed, 02 Apr 2003 17:26:23 GMT Subject: Slicing in Python 2.3a2 References: Message-ID: S?bastien Keim wrote: > I have some troubles to understand how work slicing in python 2.3. > In my examples, I will use the following list: > >>> A = range(10) > > Python 2.3 add a new argument to slice wich can for sample be used to > get only the items at positive indexes: > >>> A[::2] > [0, 2, 4, 6, 8] I think of the parts of the slice as "start, stop, step", and an empty start *or* stop means "start/stop at the end of the sequence". *Which* end depends on what direction you're going. For instance, the above means "start at one end, stop at one end, step forward by twos". The "start" end is the beginning, the "stop" end is the end. Oh dear, I'm using the word "end" for two different meanings here. Let me disambiguate by using the word "edge" instead. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ^ ^ \- "front" edge \- "back" edge So A[::2] means "start at an edge, stop at an edge, step forward by 2". Since the step is forward, the slice will start at the front edge and stop at the back edge. > This works also for subslices: A[x:y:z] is equal to A[x:y][::z] > >>> A[1::2] > [1, 3, 5, 7, 9] Start at index 1, stop at an edge, step forward by 2. Since the step is forward, the slice will stop at the back edge. > With a negative value you can reverse a list: > >>> A[::-1] > [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] Start at an edge, stop at an edge, step backward by 1. Since the step is backward, the slice will start at the back edge and stop at the front edge. > But I don't understand the result for a subslice with a negative third > argument: > >>> A[1::-1] > [1, 0] Start at index 1, stop at an edge, step backward by 1. Since the step is backward, the slice will stop at the front edge. > Intuitively, I expected to get: > >>> A[1:][::-1] > [9, 8, 7, 6, 5, 4, 3, 2, 1] > > The numarray package has the same behavior, so I guess it's intentional. > >>> import numarray > >>> numarray.array(range(10))[1::-1] > array([1, 0]) > > Then what is the real semantic for this third argument? The semantics I illustrated above appear to work for all the cases I know of. Do you know of any counterexamples? -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From fperez528 at yahoo.com Wed Apr 9 17:13:02 2003 From: fperez528 at yahoo.com (Fernando Perez) Date: Wed, 09 Apr 2003 15:13:02 -0600 Subject: Wraparound problems with time.clock() on Linux Message-ID: Hi all, I wrote the following simple code to take some timing information along the way as some very cpu-intensive code executes: #cut----------------------------------------------------------------------- import time class Timer: """Stopwatch-like class to take timings during code execution. It is not meant to be an ultra-accurate tool, since it doesn't calibrate its own overhead. But it will work well for timing reasonably long-running codes.""" def __init__(self): """Return a new timer.""" self.clock = time.clock self.start = self.clock() self.times = [self.start] self.splits = [0] self.tagged_splits = [] def split(self,tag=None): """Take a split time reading.""" self.times.append(self.clock()) self.splits.append(self.times[-1]-self.times[-2]) if tag: self.tagged_splits.append((tag,self.splits[-1])) def split_print(self,tag=None): """Take a split and print it.""" self.split(tag) if tag is None: print "Last split timing: %s CPU seconds." % self.splits[-1] else: print "Split timing for <%s>: %s CPU seconds." % \ (tag,self.splits[-1]) def print_tagged_splits(self): """Print a formatted table of all tagged splits.""" print 'Summary of tagged splits (in CPU seconds)' print '-----------------------------------------' for tsplit in self.tagged_splits: print '%s: %s s' % tsplit def last_split(self): """Return the last split.""" return self.splits[-1] def total(self): """Return total time elapsed since timer's creation.""" return self.clock() - self.start #/cut---------------------------------------------------------------------- The problem I am having is that in certain long runs, I get negative values for the total() function. I was wondering if there are wraparound issues I should be aware of. Here is an example of the output from two different runs of my code: This one was ok: CPU total: 831.26 s Splits : build rho -> 683.73 s build sep Coul -> 0.24 s apply sep Coul -> 119.92 s build mra Coul -> 0.02 s apply mra Coul -> 19.21 s build plot arrays -> 8.11 s saving plots to disk -> 0.03 s This one, on the other hand, generated negative times. I know (from timestamps on files made by the code as it ran), that the code took about 50 minutes of wall time to actually execute. Since time.clock() is supposed to return floats, I wasn't expecting wraparound problems. CPU total: -1418.007296 s Splits : build rho -> -2211.787296 s build sep Coul -> 0.03 s apply sep Coul -> 683.05 s build mra Coul -> 0.18 s apply mra Coul -> 100.78 s build plot arrays -> 9.7 s saving plots to disk -> 0.0400000000001 s Any ideas? For reference, this is running on a RedHat 8.0 Intel box. Thanks for any input. cheers, f. From claird at lairds.com Mon Apr 14 16:28:05 2003 From: claird at lairds.com (Cameron Laird) Date: Mon, 14 Apr 2003 20:28:05 -0000 Subject: Calling Python Code Snippets within Python Application References: <236da4ed.0304140143.25abc577@posting.google.com> Message-ID: In article , Robin Munn wrote: . . . >Look at the eval() or execfile() built-ins: > > http://www.python.org/doc/current/lib/built-in-funcs.html > >Note that eval() evaluates an expression -- if you want to use eval() to >run chunks of Python code, you might have to wrap those chunks in a >function and eval() the result of calling that function. execfile() will >work if the code you want is in a file; if it's in a database, you might >have to write it to a temporary file and then execfile() that temporary >file. . . . ? When is it advantageous to write to a temporary file and apply execfile() rather than exec directly? -- Cameron Laird Business: http://www.Phaseit.net Personal: http://phaseit.net/claird/home.html From sholden at holdenweb.com Wed Apr 30 09:25:07 2003 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 30 Apr 2003 13:25:07 GMT Subject: importing modules with the same name but from different directories References: Message-ID: "Mirko Koenig" wrote in message news:b80pdp$81h$1 at news.tu-darmstadt.de... > On Mon, 21 Apr 2003 04:42:51 +0200, logistix wrote: > > > > >> -----Original Message----- > >> From: python-list-admin at python.org > >> [mailto:python-list-admin at python.org] On Behalf Of Mirko Koenig Sent: > >> Sunday, April 20, 2003 9:26 PM > >> To: python-list at python.org > >> Subject: importing modules with the same name but from different > >> directories > >> > >> I have a program consisting of many modules. Every modul has its own > >> directory in a directory called modul, eg. > >> > >> .../modul/modul1 > >> .../modul/modul2 > >> > >> In every modul directory is a diretory for the language files. These > >> files are used to display the modules label in different languages. eg. > >> > >> .../modules/module1/language/german.py > >> .../modules/module1/language/english.py > >> .../modules/module2/language/german.py > >> .../modules/module2/language/english.py > >> > >> My problem is: > >> If is start modul1 from within its modul directory ( .../modules/modul1 > >> ) And modul1 calls modul2, then modul2 doesn't load its own language > >> file. Instead it loads the langugae file of modul1. > > >> > > Add an __init__.py file to each directory in your project. This makes > > the directories packages. Then you can use a fully qualified path such > > as "import modules.modul1.language.english as module1_english". Note > > that you can't use the same name for different modules at runtime, so > > use "as xxx." to give them a more distinct name. > > Is it possible to to something like this: > from modules.modul1 import * > or > from modules.modul1.language.english import text as modul1_text > or > import modules.modul1 as modul1 and than get the languag file > Mirko: You seem to be able to want to do something like if running_in_german: import module1.language.german as mod12lang import module2.language.german as mod2lang elif running_in_English: import module1.language.english as mod12lang import module2.language.english as mod2lang else: sys.exit("Don't know which language to use") Note that dots in module names indicate "packaging": a package is a directory, which can contain a __init__.py file to perform certain special magic. Another thing to try: the import of mod1lang could be handled in module1 rather than in the main program, and then the main program can simply "from module1 import mod1lang", for example, to access variables and function and class names bound in that module. What you definitely *can't* do is this: m = "modulename_or_path" import m as something To emulate this non-available solution and actually execute an import you would need to use this: m = "modulename_or_path" exec "import %s as something" % m I'd advise against any solution that involves exec'ing or eval'ing unless there's really no alternative, which is not the case here. What you would need for this is the __import__() function, built in to the language and just waiting for you to take advantage of it. regards -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From hungjunglu at yahoo.com Sun Apr 27 12:35:08 2003 From: hungjunglu at yahoo.com (Hung Jung Lu) Date: 27 Apr 2003 09:35:08 -0700 Subject: win32api registry methods and exception handling problem Message-ID: <8ef9bea6.0304270835.96e779f@posting.google.com> Hi, The registry handling methods in win32api seem to have problems with the Python exception handling. It took me some time, but I have managed to isolate the problem to a simple program. But the problem is more severe in more complicated situations, and there it seems to happen with most (or all) registry methods (win32api.Reg...()). The methods of _winreg module do not exhibit this problem. For now, I am using _winreg. However, it would be nice if the problem could be tracked down inside the win32api's source code and be fixed. regards, Hung Jung Lu #---------------------------------------------------------------------- # OS used: Windows XP # # Python 2.1 # program works correctly: correct exception message displayed # # Python 2.2.2 (win32all build 152) # (a) In Pythonwin intractive window, you get # SystemError: error return without exception set # (b) When running with python.exe, it crashes # # Python 2.3b1 (win32all build 153) # (a) In Pythonwin intractive window, you get # SystemError: error return without exception set # (b) When running with python.exe, program exits silently, # which is not the correct behavior # # Comments: # (a) equivalent _winreg module methods do not have problem. # (b) problem seems to happen with most, or all, win32api.Reg...() # methods, not in this particular example, but in more # complicated programs (involving classes) # import win32con import win32api def reg_operation(): hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, r'Software\Spam') x = 3/0 # or a statement like: raise 'error' try: reg_operation() except: x = 5/0 # or a statement like: raise 'error' From johnroth at ameritech.net Wed Apr 16 20:07:49 2003 From: johnroth at ameritech.net (John Roth) Date: Wed, 16 Apr 2003 20:07:49 -0400 Subject: Standard way to express a date in a real number? References: <420ced91.0304141131.73a6206e@posting.google.com> <420ced91.0304152121.2af84a33@posting.google.com> <9t8na.27736$T34.825154@news2.tin.it> Message-ID: "Alex Martelli" wrote in message news:9t8na.27736$T34.825154 at news2.tin.it... > sdhyok wrote: > > > Tyler Eaves wrote in message > > news:... > >> Nicola Mingotti wrote: > >> > >> > import time > >> > t = time.time() > >> > # t is the number you asked for > >> > > >> > If you want to know more about this look at > >> > the "time" module . > >> > > >> > > >> > bye. > >> > >> The problem is that you can only represent dates from 1970 - > >> 2030-someting that way. > > > > So, this is not the solution I am seeking. > > Better module to handle wider range of time? > > In Python 2.3, module datetime may serve your needs: > > >>> datetime.date(2303,4,16).toordinal() > 840893 > >>> datetime.date(1303,4,16).toordinal() > 475651 Unfortunately, this appears to be based off of 1AD or some such. I usually want 4712BC as the base - in other words, the astronomical Julian date. > >>> > > Of course, dates before the Gregorian calendar's establishment > (which happened in different years in different nations...!) > will give somewhat arbitrary results, but apart from that you're > all right. Technically, it's called a proleptic Gregorian date, that is, a date created according to the Gregorian calendar rules before it was used historically. > The result is an integer, but it's not hard to turn > it into a float if that's what you desire for some reason or other. > > > Alex > From peter at engcorp.com Mon Apr 7 23:04:56 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 07 Apr 2003 23:04:56 -0400 Subject: cgi form handler question References: <3e90ff67$0$13167$5a62ac22@freenews.iinet.net.au> <3E9158CA.C53791E5@engcorp.com> <3d06fae9.0304070522.2f9e7059@posting.google.com> Message-ID: <3E923C58.4DAD8D8@engcorp.com> jmdeschamps wrote: > > Peter Hansen wrote in message news:<3E9158CA.C53791E5 at engcorp.com>... > > Ian Bicking wrote: > > > for name in form.keys(): > > > if not form[name].value: > > > print name > > > > The latter suggestion won't usually work, as the data sent > > from the browser does not even contain the names of the fields > > which are left empty. > > ...left empty, -unless you use the form > cgi.FieldStorage(keep_blank_values = 1) to get your form info as in > http://www.python.org/doc/current/lib/node297.html > > and as someone else might have said, 'Happy CGI-ing', D'oh! Did I get caught by assuming the behaviour I'd observed using cgi.FieldStorage() recently was actually caused by the browser instead of by cgi.py itself? Dang... sorry to mislead. -Peter From regnivon at netscape.net Mon Apr 21 15:32:11 2003 From: regnivon at netscape.net (scn) Date: 21 Apr 2003 12:32:11 -0700 Subject: coverting list back to string Message-ID: <3cf72d52.0304211132.799d8afb@posting.google.com> my code: import xreadlines input = open('c:/python22/programs/linetest.txt', 'r') # 3 lines of text output = open('c:/python22/programs/output.txt', 'w') for line in input.xreadlines(): remove = line.split() remove[0:1] = [] output.write(remove) output.close() input.close() my quest: i know that output.write(remove) is not correct. you cannot use the 'write' method on a list. is there a better way to convert the list to a string after the first element of the list has been removed and then output the strings to a file? i'm a newbie programmer and need guru help. thank you. From jerf at jerf.org Tue Apr 8 00:02:07 2003 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 08 Apr 2003 04:02:07 GMT Subject: Cross-reference 'import' in a class hierarchy References: Message-ID: On Mon, 07 Apr 2003 01:06:06 +0000, Ben Finney wrote: > These aren't in a state to be site packages; they're still undergoing > rapid architectural changes. Thus, using monthy.pth isn't an option > (unless you can tell me otherwise). > > Any guidance appreciated as I tread this unfamiliar ground. Good luck; I asked this question a while ago and the consensus is, depending on your point of view, "why the hell would you want to do that?" or "can't be done". It is interesting that all the Python programs I've seen that are broken up into files at all (and not just 100+KB hunks of text) are plopped into one directory. IMHO, this is the largest wart by far in Python when it comes to writing "real" programs that really shouldn't have every file dumped into the same directory. I also find the solution of putting references to the application in the Python directory or the other standard solutions completely unsatisfactory. It's one thing for a library to go live in "the main namespace", it's quite another for my application to do so; this is apparently the one namespace in Python that it is *acceptable* to pollute. For instance, my application has a file in the top-level named "gui.py", named that for the very good reason that it switches between the (currently) 2 GUI frameworks the program supports. Is it so inconceivable that some other application might want to use that name too without conflict? Applications aren't libraries and there should be somewhat better support for this sort of thing. On the simplest level, one could rise up the directories until one either hits root or some token file that says "Here, I'm an application!" and use that as the first dir in the search path. I'd PEP it but given that nobody else is uncomfortable polluting this part of the namespace it seems the odds of it going anywhere are slim. In the meantime, I've made do with the following boilerplate, dropped as needed in files as I'm going: import sys import os if __name__ != "__main__": # add parent dir to path f = __file__ f = os.path.normpath(os.path.dirname(f) + os.sep + os.pardir) if f not in sys.path: sys.path.append(f) else: sys.path.append("..") Repeat the lines as appropriate to add the grandparent, etc. depending on how deep the file is. 'import something_at_the_root_of_the_app' will then work as you expect, provided there aren't any name conflicts with libraries or internal to your app. Those do get hard to manage; I named a package "commands" without realizing that is actually an obscure Python std lib package. Note that as the Python library grows, along with the popularity of certain almost-standard libraries like PIL, this sort of thing is going to happen more often... In particular, I have found this helpful in putting all the unit tests in separate directories named "tests" under the things they are actually testing, as this allows the test modules to directly import the things they are testing, regardless of whether they've been packaged or are available from the bare "import" command, without polluting the directory itself with more files. (It's bad enough as it is with as much as a .py, a .pyc, a #.py#, and a .py~ for each Python file when using emacs to write Python.) From whisper at oz.net Tue Apr 15 14:14:02 2003 From: whisper at oz.net (David LeBlanc) Date: Tue, 15 Apr 2003 11:14:02 -0700 Subject: syntax highlighting file python 2.1 In-Reply-To: <6gPma.6270$hF.51358@news-server.bigpond.net.au> Message-ID: > -----Original Message----- > From: python-list-admin at python.org > [mailto:python-list-admin at python.org]On Behalf Of Neil Hodgson > Sent: Tuesday, April 15, 2003 1:19 > To: python-list at python.org > Subject: Re: syntax highlighting file python 2.1 > > > Luigi Monaco: > > > Basically I require a full list of methods, modules or a way how to > > extract this from a python release. Keywords etc. should > > suffice from e.g.: /usr/share/vim/vim61/syntax/python.vim. > > This may help, although it can take a long time: > http://www.scintilla.org/gen_python_api.zip > > Neil PyXR will do this too (and also slowly) http://members.bellatlantic.net/~olsongt/python/pyxr.html David LeBlanc Seattle, WA USA From aleax at aleax.it Mon Apr 28 10:07:27 2003 From: aleax at aleax.it (Alex Martelli) Date: Mon, 28 Apr 2003 14:07:27 GMT Subject: Coding style and Python versions (was Re: Another itertool function?) References: Message-ID: Aahz wrote: > In article , > Andrew Dalke wrote: >> >> i = i + 1 > > I'm a little curious why you didn't write this as > > i += 1 > > Any reason (i.e. still need to support 1.5.2) or just habit? If the > latter, why haven't you changed your habit? There is no special reason to "change that habit", e.g. not performance: [alex at lancelot src]$ python Lib/timeit.py 'i=0; i+=1' 1000000 loops, best of 3: 0.284 usec per loop [alex at lancelot src]$ python Lib/timeit.py 'i=0; i=i+1' 1000000 loops, best of 3: 0.281 usec per loop [alex at lancelot src]$ python Lib/timeit.py 'i=0; i=i+1' 1000000 loops, best of 3: 0.281 usec per loop [alex at lancelot src]$ python Lib/timeit.py 'i=0; i=i+1' 1000000 loops, best of 3: 0.284 usec per loop [alex at lancelot src]$ python Lib/timeit.py 'i=0; i+=1' 1000000 loops, best of 3: 0.282 usec per loop [alex at lancelot src]$ python Lib/timeit.py 'i=0; i+=1' 1000000 loops, best of 3: 0.278 usec per loop No statistically significant / measurable difference. The tiny difference in conciseness is hardly compelling one way or another, either. Alex From jepler at unpythonic.net Tue Apr 15 12:26:17 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 15 Apr 2003 11:26:17 -0500 Subject: file read : feature or bug ? In-Reply-To: <3e9c2eea$0$6528$afc38c87@sisyphus.news.be.easynet.net> References: <3e9c2eea$0$6528$afc38c87@sisyphus.news.be.easynet.net> Message-ID: <20030415162616.GB30739@unpythonic.net> When you're using text files, seek will not operate as you expect. The C standard defines that only offsets returned by ftell are legal arguments to fseek when working with a text file, and Python doesn't prevent you from shooting yourself in the foot here. Jeff From gh at ghaering.de Tue Apr 15 08:10:45 2003 From: gh at ghaering.de (Gerhard =?iso-8859-1?Q?H=E4ring?=) Date: 15 Apr 2003 12:10:45 GMT Subject: Inserting HTML files as strings in database References: Message-ID: vivek kumar wrote: > hi all, > I am trying to make a search engine in python. I want to save the html > files retrieved by the crawler into a Mysql database as strings > (MEDIUMTEXT). But the characters like ' " etc are giving problems while > inserting it as a string. [...] It's generally a bad idea to insert the values into the SQL string yourself. This, and quoting the values appropriately, is the job of the DB-API module: #v+ a_really_ugly_string = "".join([chr(x) for x in range(1,255)]) # cx is the connection object cu = cx.cursor() cursor.execute(""" INSERT INTO MYTABLE(FOO) VALUES (%s) """, (a_really_ugly_string,)) cu.commit() #v- For inserting binary data (i. e. data containing the null byte) you'll need a binary column type. -- Gerhard From tismer at tismer.com Sat Apr 5 10:59:03 2003 From: tismer at tismer.com (Christian Tismer) Date: Sat, 05 Apr 2003 17:59:03 +0200 Subject: Stackless python In-Reply-To: <221d8dbe.0304050531.107bc603@posting.google.com> References: <221d8dbe.0304050531.107bc603@posting.google.com> Message-ID: <3E8EFD47.7060804@tismer.com> srijit at yahoo.com wrote: > I am interested to try Stackless Python. I have downloaded python22.dll.zip. > How do I install this zip file? I already have standard python 2.2.2 installed. You either install python22.dll in a local folder. When you start Python from there, it will be stackless. If you want to install it permanently, rename the dll in windows/system32 and copy the new dll there. In the version you have, there is a stacklessmodule.pyd which should be in the local folder or be copied into /python22/DLLs. This is temporary, the new version which I'm about to upload tomorrow does not have that external file, since it is all moced into the core dll, for simplicity. > I also do not see any documentation like tutorials, > example programs, demos etc. There are a few test programs, if you download the CVS tree. There is no public release, yet, this is still pre-alpha stuff. You can get all internal documentation by >>> help(stackless) > Is it 100% compatible with standrad Python 2.2.2? Yes, it should be. If not, let me know. 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 exarkun at intarweb.us Wed Apr 30 11:36:24 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Wed, 30 Apr 2003 11:36:24 -0400 Subject: plugin system In-Reply-To: References: Message-ID: <20030430153624.GA22939@meson.dyndns.org> On Wed, Apr 30, 2003 at 04:56:22AM +0000, xam wrote: > I am interested in writing a plugin system where the main app is python but > it is capable of accepting helper "plugins" which can be either python or > C++. I guess I want some sort of an interface spec for the plugins that can > be implemented in either language. Which technologies should I research? Are > there other projects that I can refer to as a model - > http://twistedmatrix.com/documents/TwistedDocs/current/api/ Jp -- Seduced, shaggy Samson snored. She scissored short. Sorely shorn, Soon shackled slave, Samson sighed, Silently scheming, Sightlessly seeking Some savage, spectacular suicide. -- Stanislaw Lem, "Cyberiad" -- up 41 days, 11:04, 5 users, load average: 0.14, 0.11, 0.03 From oktaysafak at ixir.com Wed Apr 2 02:43:38 2003 From: oktaysafak at ixir.com (Oktay Safak) Date: Wed, 2 Apr 2003 10:43:38 +0300 Subject: unicode bug in turkish characters? Message-ID: <008901c2f8eb$95a02a60$0200a8c0@b> Hi everybody, I think there is a problem with the Turkish encoding in Python's unicode support. I have Python 2.3a instaled on win98/ME. I came across some strange behaviour while using the re module, and upon investigating the issue I have narrowed it down to the following (I set sys.setdefaultencoding("iso-8859-9") in sitecustomize py and use IDLE) : When I try to convert the character "i" to uppercase what comes out is "I" where it should have a dot on top of it instead. Also, when I try to convert the uppercase i with dot to lowercase, it comes out as itself where "i" should be the character produced. I'm unable to give IDLE window output because turkish characters are involved which I cannot reproduce here. I did some investigation with both iso-8859-9 and windows-1254 encodings and found that the ordinal values before and after togglin the case of chars are as follows: | original value | after case toggle | ------------------------------------------------- | 8859-9 | win-1254 | 8859-9 | win-1254 | -------------------------------------------------------------------- small i w/o dot | 253 | 253 | 73 | 253 | -------------------------------------------------------------------- small i | 105 | 105 | 73 | 73 | -------------------------------------------------------------------- Capital I | 73 | 73 | 105 | 105 | -------------------------------------------------------------------- Capital I with dot | 221 | 221 | 221 | 221 | THE CORRECT VALUES SHOULD INSTEAD BE: | original value | after case toggle | ------------------------------------------------- | 8859-9 | win-1254 | 8859-9 | win-1254 | -------------------------------------------------------------------- small i w/o dot | 253 | 253 | 73 | 73* | -------------------------------------------------------------------- small i | 105 | 105 | 221* | 221* | -------------------------------------------------------------------- Capital I | 73 | 73 | 253* | 253* | -------------------------------------------------------------------- Capital I with dot | 221 | 221 | 105* | 105* | as you see only one of the 8 conversions is correct. I have looked into the encodings directory and saw that the iso-8859-9 file contains: decoding_map.update({ 0x00d0: 0x011e, # LATIN CAPITAL LETTER G WITH BREVE 0x00dd: 0x0130, # LATIN CAPITAL LETTER I WITH DOT ABOVE ***1 0x00de: 0x015e, # LATIN CAPITAL LETTER S WITH CEDILLA 0x00f0: 0x011f, # LATIN SMALL LETTER G WITH BREVE 0x00fd: 0x0131, # LATIN SMALL LETTER DOTLESS I ***2 0x00fe: 0x015f, # LATIN SMALL LETTER S WITH CEDILLA }) the *** marked lines are relevant here. The mapping for these in decimal seem to be: 221:304 and 253:305 respectively. So why aren't these the values I get? I might be missing something but I have a feeling that this is a bug since the case toggle works perfectly with turkish characters that do not exist in ascii. With i and I though, which do exist in ascii, it's all messed up. Any ideas? From salvatore at wanadoo.fr Sat Apr 5 05:17:55 2003 From: salvatore at wanadoo.fr (Salvatore) Date: Sat, 05 Apr 2003 12:17:55 +0200 Subject: In memory File In-Reply-To: <3E8EABDB.9AA000A0@alcyone.com> References: <3E8EA197.3AE807EB@alcyone.com> <3E8EA9E4.60704@wanadoo.fr> <3E8EABDB.9AA000A0@alcyone.com> Message-ID: <3E8EAD53.2070608@wanadoo.fr> Erik Max Francis wrote: > Salvatore wrote: > > >>I wanted to redirect sys.stdout to StringIO object but il doesn't seem >>to work > > >>>>import StringIO >>>>import sys >>>>sys.stdout = StringIO.StringIO() >>>>print "Told you" >>>>print >> sys.stderr, sys.stdout.getvalue() > > Told you > I am a poor Python coder ;-) Thanks Erik From hwlgw at hotmail.com Tue Apr 15 03:16:49 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 15 Apr 2003 00:16:49 -0700 Subject: Pythonic way of web-programming References: <%5Oja.10776$7w2.9784@nwrddc01.gnilink.net> <23891c90.0304140221.20e9e7fb@posting.google.com> Message-ID: [Courageous] > At the risk of boldly tossing incidental mud up in the face of > the entirety of all Pythonistas, I really don't think our community > has enough cohesion or clout to put together a uniform .NET/Web Services > style package with standards-establishing authority. We're not Microsoft, > after all, with a cool $billion to dispose of at a sneeze. > > What you'll have to do instead is wait for the competitive feeding > frenzy to end and allow the technically superior platform to present > itself. This is both the bane and boon of open software in action, > IMO, and at a guess it very much applies here. Well said. Or written. Whatever. I wish english was my native language. I would like to add something. The major problem I face when I want to use Python for web applications or services, is that the host or internet provider just does not have Python installed, or they have the old Python 1.5, like even sourceforge does. Or no ``#!/usr/bin/env Python`` or something like that configured for CGI scripts. Running your own webserver is often just not allowed. I feel we should concentrate, whoever of us can do such a thing, on getting Python into *nix distros, especially the kind internet providers use. And talk to Apache so they change their default configuration script or something (I am not sure about the technicalities here, there is something like mod_python also but how about support?) so it will not only allow #!/bin/sh but also Python. And for the rest of use mere programmers, we can kick ass producing better tools for web environments. For example: I have not seen a good, easy to use, web application that works well with RDF. How about setting up a website with Python where you can input your RDF file and it displays the tree with nice colors and URLs and so forth? There are plenty possibilities using Python for things like this, but you have to show it, working examples, *on the web* or nobody will see it. I think CGI is the only standard that will last some time, maybe better concentrate on that. -- As in Protestant Europe, by contrast, where sects divided endlessly into smaller competing sects and no church dominated any other, all is different in the fragmented world of IBM. That realm is now a chaos of conflicting norms and standards that not even IBM can hope to control. You can buy a computer that works like an IBM machine but contains nothing made or sold by IBM itself. Renegades from IBM constantly set up rival firms and establish standards of their own. When IBM recently abandoned some of its original standards and decreed new ones, many of its rivals declared a puritan allegiance to IBM's original faith, and denounced the company as a divisive innovator. Still, the IBM world is united by its distrust of icons and imagery. IBM's screens are designed for language, not pictures. Graven images may be tolerated by the luxurious cults, but the true IBM faith relies on the austerity of the word. -- Edward Mendelson, "The New Republic", February 22, 1988 From mgerrans at mindspring.com Sat Apr 12 22:49:08 2003 From: mgerrans at mindspring.com (Matt Gerrans) Date: Sat, 12 Apr 2003 19:49:08 -0700 Subject: an ugly file-reading pattern References: Message-ID: Learning Python is an excellent book, but unfortunately quite out of date. It covers Python version 1.5, whereas 2.2.2 is the current release, with 2.3 in alpha. Anyway, the syntax to read lines from a file without loading the whole thing is now quite simple and clean: for line in file( filename ): ... do your thing ... or if you prefer open(): for line in open( filename ): ... do your thing ... From staschuk at telusplanet.net Mon Apr 28 00:29:53 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Sun, 27 Apr 2003 22:29:53 -0600 Subject: Using __repr__ or __str__ for own printable class? In-Reply-To: ; from tim.one@comcast.net on Sun, Apr 27, 2003 at 10:17:44PM -0400 References: <20030427183847.C28461@tibia.amotlpaa.bogus> Message-ID: <20030427222953.C23486@tibia.amotlpaa.bogus> Quoth Tim Peters: [...] > I beg to differ, sir! The people with the greatest power to change the docs > are those who actually submit thoughtful doc patches. On that basis, you're > the most powerful fellow I've seen this month . First, the Python docs... next, THE WORLD! MWA HA HA! COWER BEFORE ME, YOU PUNY WORMS! Ahem. I mean, er, thanks. -- Steven Taschuk Aral: "Confusion to the enemy, boy." staschuk at telusplanet.net Mark: "Turn-about is fair play, sir." -- _Mirror Dance_, Lois McMaster Bujold From aleax at aleax.it Sat Apr 12 11:16:35 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 12 Apr 2003 15:16:35 GMT Subject: readline clear buffer References: Message-ID: Skip Montanaro wrote: > Alex> Right: it seems that Python's readline.c does not expose > Alex> interfaces to rl_delete_text, rl_kill_text, or other GNU > Readline Alex> functions that would allow such behavior. > > GNU readline has a huge API (I count over 340 extern declarations in > readline/{readline.h,history.h}, the two programmer-visible #include > files). I believe the approach all along has been to expose just those > parts of the > API necessary for the current task at hand. I realize this means the > interface will be incomplete, but it's not clear that most of it is > necessary for common tasks. So, yes, submit a patch which includes > wrappers for the functions you're interested in. I think that's a rather sensible pragmatical approach to finding the right subset to expose out of a huge API (though proponents of the "waterfall", AKA "big design up front", sect, are no doubt loading up their flamethrowers -- if any lurk on c.l.py, that is;-). And I notice with pleasure that the OP is now testing out the small patch to expose text-deletion and plans to submit it, so the incremental approach to API exposure seems to be still working fine;-). Alex From beau at nyc-search.com Tue Apr 1 16:53:39 2003 From: beau at nyc-search.com (beau at nyc-search.com) Date: Tue, 01 Apr 2003 16:53:39 -0500 Subject: Python Programmers, NYC Message-ID: <3E8A0A63.3F682C06@nyc-search.com> Python Programmers, NYC http://www.nyc-search.com/jobs/python.html From bokr at oz.net Thu Apr 17 17:17:34 2003 From: bokr at oz.net (Bengt Richter) Date: 17 Apr 2003 21:17:34 GMT Subject: Tutorial - section 8.5 -- User Defined Execptions? References: <3E9D35FC.FCAD17C9@alcyone.com> <3E9EEB54.682751BC@alcyone.com> Message-ID: On Thu, 17 Apr 2003 10:58:44 -0700, Erik Max Francis wrote: >Bengt Richter wrote: > >> What other use is there (outside of strings and comments)? >> Have we purposely been set up for gaucheries? >> ;-) > >In shell-like languages, the backquotes are used to mean "Execute what's >in between the backquotes as a shell command, and then substitute the >(stdout) output of that command and continue, e.g.: > Yes, I'm aware. I thought we were talking about `...` in Python ;-) (I'm also aware that they're on Guido's regrets list http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.pdf ) I guess my smiley needed more oomph 8-<;^D Regards, Bengt Richter From erno-news at erno.iki.fi Fri Apr 18 20:31:52 2003 From: erno-news at erno.iki.fi (Erno Kuusela) Date: 19 Apr 2003 03:31:52 +0300 Subject: Python Thread Question References: Message-ID: In article , Jp Calderone writes: | Nope. Threading costs you context switches. A multi-threaded app using | blocking IO will appear "faster" than a single-thread app doing the same, | but both take longer to run than a single written app using non-blocking IO. in addition, enabling threading (creating the first theread) turns on all the locking machinery in the python interpreter. this causes everything to slow down somewhat. on my pc, running pystone in a thread goes about 50% slower than normally. -- erno From gh at ghaering.de Tue Apr 22 18:09:13 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 23 Apr 2003 00:09:13 +0200 Subject: Can someone send me the latest Gadfly? In-Reply-To: <0Ljpa.2547$%_3.2056417@newssrv26.news.prodigy.com> References: <200304220934.38013.scott_list@mischko.com> <0Ljpa.2547$%_3.2056417@newssrv26.news.prodigy.com> Message-ID: <3EA5BD89.10503@ghaering.de> drs wrote: > "Gerhard H?ring" wrote: >>Scott Chapman wrote: >> [where to find Gadfly download] >>>Can someone help out here? >> >>http://sourceforge.net/projects/gadfly >>http://sourceforge.net/project/showfiles.php?group_id=662 > > I am very confused ... You obviously did a reasonable amount of research to > find this, and you are also clearly a sophisticated internet user ... a > google search on "gadfly python" turned up the db as the second result, and > an informational page linking to the db as the first. what google searches > did you try? I just remembered seeing an announcement of Gadfly moving to Sourceforge with new maintainers here on this list. So I straightly went to http://sf.net/projects/gadfly/ :-) -- Gerhard From oktaysafak at ixir.com Wed Apr 23 16:46:37 2003 From: oktaysafak at ixir.com (oktaysafak at ixir.com) Date: Wed, 23 Apr 2003 22:46:37 +0200 Subject: In praise of PythonCard Message-ID: <20030423204637.MQHZ239.nairobi@[212.252.122.82]> > > Oktay Safak wrote: > > Very rude of you, Laotseu ;) > > Yes, I know, I shouldn't have mispelled 'smalltalk' !-) ^^^^ You definitely need a good spellchecker :-P From martin at v.loewis.de Wed Apr 30 14:31:25 2003 From: martin at v.loewis.de (Martin v. =?iso-8859-15?q?L=F6wis?=) Date: 30 Apr 2003 20:31:25 +0200 Subject: question on the compile built in function. Filename ignored? References: <7rSra.706428$S_4.744795@rwcrnsc53> Message-ID: Alex writes: > From the docs I would expect the line > > File "", line 1 > > to read > > File "abc", line 1 > > > What am I missing? You are right: this is what should have been printed. You have found a bug. Actually, you are not the first one to find this bug; it will be fixed in Python 2.3. Regards, Martin From peter at engcorp.com Sun Apr 27 20:04:58 2003 From: peter at engcorp.com (Peter Hansen) Date: Sun, 27 Apr 2003 20:04:58 -0400 Subject: Textbooks? References: <3EAC2962.2050609@soraia.com> Message-ID: <3EAC702A.A65C22B9@engcorp.com> Joe Francia wrote: > > The Deitels have a textbook called _Python How to Program_ that is aimed > at beginning programmers. I'm not sure how good/bad it is. Three out > of four reviewers on Amazon seem to like it (the fourth guy gave it one > star based on its lack of Perl coverage). At a PyGTA meeting three or four months ago someone showed up with a copy to give away. I believe it went home with one person only to come back the next month, to be given away again. I'm pretty sure it wasn't because he'd read it cover to cover. I'm not sure who got stuck with it last... (To be more direct: I opened it to skim, and my first comment was along the lines of "Gah!". I believe "Yeesh!" and "Ugh" were heard as well. To be fair, these comments were directed at the quality of the layout and the unreadable color scheme, not necessarily at the content, which I was unable to get near.) -Peter From aleax at aleax.it Sat Apr 19 18:11:35 2003 From: aleax at aleax.it (Alex Martelli) Date: Sat, 19 Apr 2003 22:11:35 GMT Subject: Sorting without transitivity References: Message-ID: Frank Niessink wrote: > Hi all, > > [It's been while since I've dealt with transitivity and stuff, so > I hope I got the terminology right] > > I have objects that are not transitivily ordered, e.g.: > > A > B > A == C > B == C > > Now I have a list [A, B, C] and I want to sort it. > The resulting list should have B before A, I don't care where > C is. However, the Python list.sort() method (Python 2.2.2 on cygwin) > doesn't put A and B in the right order. I think what you want is what's known as a *topological sort* -- a sort obtaining any ordering that respect certain given pairwise constraints that don't, however, define a complete order. > How can I get the desired behavior? Should I implement my own > sort algorithm? Any pointers? You can find topological sorts in Python on the net. E.g., http://starship.python.net/crew/aaron_watters/kjbuckets/tsort.py this one uses kjbuckets, but it's not hard to transliterate to forms using other representation for the constraints and other ways to store sets. Alex From sholden at holdenweb.com Tue Apr 15 09:50:24 2003 From: sholden at holdenweb.com (Steve Holden) Date: Tue, 15 Apr 2003 13:50:24 GMT Subject: Complexity of standard Python data structures References: Message-ID: "Chris Jones" wrote in message news:tdnk7dwlfda.fsf at shell01.TheWorld.com... > Tim Peters writes: > > > [Tim] > > > Note that it's not true that Python's list is really a vector/array -- > > > thelanguage doesn't define its implementation, and doesn't want to. > > > > [Marcus Alanen] > > > Hmm. So the Python language is more about specifying _what_ will > > > happen, instead of _how_, with no concern for actual speed or memory? > > > > The Python language reference manual, and the Python standard library > > reference manual, are like that, and that's par for the course for language > > specs: they specify syntax ("how is it spelled?") and semantics ("what does > > it mean?"). Everything else falls under pragmatics, often called "quality > > of implementation" issues. The STL is close to unique, outside the > > real-time world, in making promises related to performance. For the other > > side, I spent the first 15 years of my career working largely on optimizing > > Fortran compilers and runtime libraries: no user base was more concerned > > about speed than Fortran's, yet the Fortran standard didn't breathe a word > > about how fast or slow any construct or standard function might be, could > > be, or should be. Similarly, the IEEE-754 standard for floating-point > > arithmetic doesn't say anthing about speed either. Standards bodies are > > generally loathe to constrain implementations. > > > > Of course the Python language itself is distinct from (albeit related to) > > its implementations. People working on implementations are typically quite > > concerned about speed and memory. The pragmatic tradeoffs can (and do) vary > > across implementations, though (same as for C, C++, Fortran, Java, etc). > > People wanting to program should nail a copy of this posting above their > keyboard. READERS: Please DO NOT FOLLOW THIS ADVICE. Following these instructions, I printed the posting out and nailed it directly above my keyboard. As a result my laptop no longer works - apparently a TFT display doesn't take kindly to having nails driven through it, and now Dell are saying that since this isn't accidental damage I'm not covered by the extended warranty I purchased. Please therefore send me $650 so I can repair the damage I did by following your doubtless well-meant advice. just-having-fun-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ How lucky am I? http://www.google.com/search?q=Steve+Holden&btnI=1 Python Web Programming http://pydish.holdenweb.com/pwp/ From lozinski at jobmart.com Mon Apr 7 15:30:43 2003 From: lozinski at jobmart.com (lozinski at jobmart.com) Date: Mon, 7 Apr 2003 12:30:43 -0700 (PDT) Subject: Plone Developer Needed In-Reply-To: <20030407192803.29437.14104.Mailman@mail.python.org> Message-ID: <1030407123043.232AAC/X.lozinski@maya> A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 612 bytes Desc: not available URL: From hwlgw at hotmail.com Fri Apr 25 12:32:32 2003 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 25 Apr 2003 09:32:32 -0700 Subject: Vim Newbie ? Python Edit/Compile/Run cycle and integrating py help questions References: <3EA7EBD3.3010605@ghaering.de> Message-ID: [Hans Nowak] > I have been trying to edit Python source code with vim on Mac OS X. Most of > the settings in my .vimrc file (copied from Windows) work just fine, except for > one. I use Tab to indent and Shift-Tab to dedent (a line, not a block). Tab > behaves as usual, but Shift-Tab doesn't seem to work; it just behaves like I > pressed Tab. In gvim on windows and linux (untested on Mac, since I have no access to a Mac anywhere): Start block selection with the v key, or with v. And then of course the j key for line down and the l key for going right etc. To indent a line, or a selected block, use >>. To dedent it do <<. -- This life is a test. It is only a test. Had this been an actual life, you would have received further instructions as to what to do and where to go. From andrew.markebo at telia.com Sat Apr 5 12:55:25 2003 From: andrew.markebo at telia.com (Andrew Markebo) Date: Sat, 05 Apr 2003 17:55:25 GMT Subject: nntplib, huge xover object References: <443s8v8mehlrhapp0d6af7k0ps22k2tvii@4ax.com> Message-ID: / carroll at tjc.com wrote: | | Looking at nntplib.py, most of the logic to do this is already there: | xover calls longcmd to actually issue the command, and longcmd can | take an optional File parameter to which getlongresp (which actually | retrieves the response) will write its output, if present. Which format should the xover output be in the file? I mean it is a list of tuples or similar? How to squeeze that to a file? Have some separator being escaped? Or have I missed something? You seem to have gotten it working? /Andy -- The eye of the linker rests on the libs! From lists at ghaering.de Sun Apr 13 09:33:20 2003 From: lists at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 13 Apr 2003 15:33:20 +0200 Subject: win32 COM test question In-Reply-To: References: Message-ID: <3E996720.5000608@ghaering.de> Will Stuyvesant wrote: > [Roman Yakovenko] > >>http://www.hps1.demon.co.uk/users/andy/pyvb/spamsrv.htm >> >>And next time try to search for the answer with google ( python com >>visual basic ) > > As a side note, quoted from above URL: > > "Distribution is a problem - not everyone will want to know they have > python installed, and a on-step installation that puts it there > suitably hidden will be needed in time" py2exe and Installer both solve this problem. At least py2exe can package COM clients and servers and it can register a Windows service written in Python for you. -- Gerhard From msg_2222 at yahoo.com Mon Apr 7 15:44:14 2003 From: msg_2222 at yahoo.com (Rick Y) Date: Mon, 7 Apr 2003 12:44:14 -0700 (PDT) Subject: socket question(3) Message-ID: <20030407194414.52865.qmail@web20705.mail.yahoo.com> installed openssl package from sunfreeware. error: ./viewcvs-install Traceback (most recent call last): File "./viewcvs-install", line 35, in ? import compat File "./lib/compat.py", line 20, in ? import urllib File "/usr/local/lib/python2.1/urllib.py", line 26, in ? import socket File "/usr/local/lib/python2.1/socket.py", line 41, in ? from _socket import * ImportError: ld.so.1: python: fatal: libgcc_s.so.1: open failed: No such file or directory followed these steps: PATH=/usr/local/ssl/bin:${PATH} export PATH LD_LIBRARY_PATH=/usr/local/ssl/lib:${LD_LIBRARY_PATH} export LD_LIBRARY_PATH cd /usr/lib ln -s ../local/ssl/lib/libcrypto.a libcrypto.a ln -s ../local/ssl/lib/libcrypto.so.0.9.6 libcrypto.so.0.9.6 ln -s ../local/ssl/lib/libssl.a libssl.a ln -s ../local/ssl/lib/libssl.so.0.9.6 libssl.so.0.9.6 ln -s libssl.so.0 libssl.so ln -s libssl.so.0.9.6 libssl.so.0 cd /usr/bin ln -s ../local/ssl/bin/openssl openssl ln -s ../local/ssl/bin/c_rehash c_rehash cd /usr/include ln -s ../local/ssl/include/openssl openssl __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - File online, calculators, forms, and more http://tax.yahoo.com From cpl.19.ghum at spamgourmet.com Fri Apr 18 06:26:41 2003 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Fri, 18 Apr 2003 12:26:41 +0200 Subject: python and macro excel References: <5b8834c2.0304170138.12f1a393@posting.google.com> Message-ID: Hello Georges, > i want to integrate a macro in excel with python and execute it you allways have to get the win32all extenstion What exactly do you want to do? a) write a vba makro and execute it from Python? o = win32com.client.Dispatch("Excel.Application") o.Visible = 1 o.Workbooks.Add() # Double Check the actual code, changes sometimes o.Run("NameOfYourMakro) b) write a Python Program and execute it from VBA? recommendation: build a COM-Server in Python, use it from VBA. More difficult. Harald From pobrien at orbtech.com Sun Apr 6 14:27:56 2003 From: pobrien at orbtech.com (Patrick K. O'Brien) Date: 06 Apr 2003 13:27:56 -0500 Subject: Could Emacs be rewritten in Python? In-Reply-To: <16016.27005.335657.809556@montanaro.dyndns.org> References: <7xn0j3fsdu.fsf@ruckus.brouhaha.com> <16016.27005.335657.809556@montanaro.dyndns.org> Message-ID: Skip Montanaro writes: > Patrick> The Scintilla text control (written in C and wrapped in > Patrick> wxPython by a control called wxStyledTextCtrl) handles the > Patrick> on-screen representation and user-manipulation of the text. So > Patrick> that part is actually easy. Just read in a file, feed it to > Patrick> Scintilla, and go. The next step is wrapping all this in an > Patrick> Emacs-like framework. > > If Scintilla doesn't distinguish between Emacs's notion of buffers (a chunk > of text being edited) and windows (a view onto a buffer) you may find the > task harder than it would first appear. I don't think this will be an issue. I'm implementing my own buffer class that acts like an Emacs buffer, except that I delegate the actual rendering and user interface to Scintilla. Scintilla is used like the Emacs window, and I can have multiple Scintilla views into the same buffer and a change in one is reflected in the other. And like Emacs windows, each can have its own point into the same buffer. -- Patrick K. O'Brien Orbtech http://www.orbtech.com/web/pobrien ----------------------------------------------- "Your source for Python programming expertise." ----------------------------------------------- From aahz at pythoncraft.com Tue Apr 15 23:04:08 2003 From: aahz at pythoncraft.com (Aahz) Date: 15 Apr 2003 23:04:08 -0400 Subject: Python for VB6 programmers (was Re: Complexity of standard Python data structures) References: <18s6dy4mcsgjg$.y4vahh6w5lp3.dlg@40tude.net> Message-ID: In article , Marcus Alanen wrote: > >On the other hand, I've always wished for a document "language X for >people know language Y / programming in general / think they know". We >could skip all that "let's hold hands while I take you though the >mysteries of a dictionary" nonsense, and just concentrate on the issue >at hand: how does our knowledge from language X map to this new >language? What pitfalls do we have in the language at the moment >(e.g. python default arguments are in my humble opinion still >counter-intuitive) ? Right now, I'm trying to get some momentum moving on a book titled _Python for VB6 Programmers_. Anyone interested should subscribe to marketing-python. http://wingide.com/mailman/listinfo/marketing-python -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz, c.l.py, 2/4/2002 From selwyn at home.net.nz Tue Apr 22 06:25:13 2003 From: selwyn at home.net.nz (selwyn) Date: Tue, 22 Apr 2003 22:25:13 +1200 Subject: problem starting python interpreter in emacs (win98) In-Reply-To: References: Message-ID: <%D8pa.4364$AB5.586778@news02.tsnz.net> > Perhaps you need to add C:\Python22 to the PATH environment variable. Doh! Works like a charm. Thanks for your help :-) Selwyn. From opengeometry at yahoo.ca Wed Apr 9 03:35:54 2003 From: opengeometry at yahoo.ca (William Park) Date: 9 Apr 2003 07:35:54 GMT Subject: sorting strings written to files References: <2745895.1049870828@dbforums.com> Message-ID: onefatman wrote: > > Can someone help me? > > I have a small phone directory .dat file that has the entries > written to it as strings with three fields in each, separated by \t > and ended by \n. > > e.g. > phbook.write("Joe\tNobody\t62907243\n") > phbook.write("Daniel\tStevens\t62962328\n") > phbook.write("Ellen\tWay\t62910758\n") > phbook.write("Jason\tGreig\t62314587\n") > > it has a function that allows you to write new entries, but i need to > know how to sort them by first name, and then by last name when the > first names are the same. If it's already written to file, then man sort If it's still in Python, then list.sort() -- William Park, Open Geometry Consulting, Linux solution for data management and processing. From dan at grassi.org Tue Apr 1 16:34:36 2003 From: dan at grassi.org (Dan Grassi) Date: Tue, 1 Apr 2003 21:34:36 +0000 (UTC) Subject: How to obtain python file path Message-ID: <20030401163212631-0500@news.covad.net> I need to obtain the full path of the python.py file that the program is executing from wether imported or run as main. Sorry but I have looked and can't find the docs. TIA, Dan From achrist at easystreet.com Fri Apr 4 17:26:09 2003 From: achrist at easystreet.com (achrist at easystreet.com) Date: Fri, 04 Apr 2003 14:26:09 -0800 Subject: Converting text to html Message-ID: <3E8E0681.9005524D@easystreet.com> Is there any recommended code available to convert plain text into text that can go into an html document without breaking it? I think that I just have to do these three translations: < => < > => > & => & But I'm not sure if there are any others. I've got to do this quite a bit while the user is waiting, so it would be nice to have something that did it in a way that was not a lot slower than any of the alternatives. Surely someone must have cracked this nut sys.maxint times by now. TIA Al From s.thuriez at laposte.net Thu Apr 10 04:42:12 2003 From: s.thuriez at laposte.net (sebastien) Date: 10 Apr 2003 01:42:12 -0700 Subject: PCA principal component analysis References: Message-ID: Alexander Schmolck wrote in message news:... > s.thuriez at laposte.net (sebastien) writes: > > > Hi, > > > > Is there any PCA analysis tools for python ? > > What is the analysis tool supposed to do? > > Maybe this will do what you want, once you (downloaded and installed Numeric): > > # Warning: hackish and not properly tested ripped out bit of code ahead > # so no guarantees whatsoever > # Anyway, it should at lesat sort of give you the idea > # try pca(X); if that doesn't do what you want try pca(t(X)) > > from Numeric import take, dot, shape, argsort, where, sqrt, transpose as t > from LinearAlgebra import eigenvectors > > def pca(M): > "Perform PCA on M, return eigenvectors and eigenvalues, sorted." > T, N = shape(M) > # if there are less rows T than columns N, use > # snapshot method > if T < N: > C = dot(M, t(M)) > evals, evecsC = eigenvectors(C) > # HACK: make sure evals are all positive > evals = where(evals < 0, 0, evals) > evecs = 1./sqrt(evals) * dot(t(M), t(evecsC)) > else: > # calculate covariance matrix > K = 1./T * dot(t(M), M) > evals, evecs = eigenvectors(K) > # sort the eigenvalues and eigenvectors, decending order > order = (argsort(evals)[::-1]) > evecs = take(evecs, order, 1) > evals = take(evals, order) > return evals, t(evecs) > > > You can download Numeric and use it to compute the eigenvalues and > eigenvectors of an array. > > > > If it does, do you have any idea on how well it would scale ? > > It should scale fine. If you experience speed problems, configure Numeric 23 > with ATLAS support (you have to install ATLAS and LAPACK first, of course). > For large matrices, this should be *much* faster than handwritten C code that > doesn't use ATLAS. > > > > > I have already seen PyClimate (but it is not available for Windows > > which will be one of the target). Is there some LAPACK like packages ? > > Yes, Numeric and scipy. (www.numpy.org, www.scipy.org, I should think) > > 'as HI, Thanks for the program. I have tested it with a test matrix that I have and that I took from IDL help (Interactive data language). The matrix is : ((2,1,3), (4,2,3), (4,1,0), (2,3,3), (5,1,9)) The principal component given by IDL is ((0.87, -0.7, 0.69), (0.01, -0.64, -0.66), (0.49, 0.32, -0.30)) Runnnig the same matrix with the program that you have kindly provided gives : ((-0.58, -0.67, 0.45), (-0.23, -0.40, -0.88), (-0.77, -0.62, -0.074)) Do you know why is there such a difference ?? I did not have the time yet to test it against other program. Thanks. Sebastien. From tim.one at comcast.net Tue Apr 29 11:43:23 2003 From: tim.one at comcast.net (Tim Peters) Date: Tue, 29 Apr 2003 11:43:23 -0400 Subject: Tkinter exit problem in Win98 In-Reply-To: <20030429.095109.-177423.0.eltronic@juno.com> Message-ID: {MvL] >> That is the oldes Python-Bug, see www.python.org/sf/216289 >> Nobody has been able so far to study in detail what is causing >> the problem and how it could be fixed. [eltronic at juno.com] > is it still a problem in python2.3 with Tk8.4, anyone? It is in 2.3b1. I haven't had time to try another Tcl/Tk release since the last entry in the bug report, and-- alas --don't know whether I'll be able to make time for it before 2.3 final. As the bug report says, though, use pythonw.exe instead of python.exe, and there's no problem. From timr at probo.com Fri Apr 4 01:22:29 2003 From: timr at probo.com (Tim Roberts) Date: Thu, 03 Apr 2003 22:22:29 -0800 Subject: writing to windows memory References: <3E8C01CE.6070601@netscape.net> Message-ID: vector wrote: > >newbie: >pythonwin 2.2.2 >Id like to bind a button.widget that simply writes a one to windows >address 440h. any ideas on where to start.(the button stuf is trivial) i >need to know how to access the address space. What, exactly, do you think that is going to do? -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From eppstein at ics.uci.edu Tue Apr 1 11:50:42 2003 From: eppstein at ics.uci.edu (David Eppstein) Date: Tue, 01 Apr 2003 08:50:42 -0800 Subject: else: w/o except: - why not? References: Message-ID: In article , Michael Chermside wrote: > I think that a "bare except" is useful in only two ways. The first > is like a "finally" clause that's skipped if everything works. [...snip...] > The other situation is running "untrusted plug-in" code of some > sort. I have a bare except wrapped around the main event loop of some python gui code. It provides an opportunity to log the problem and give the user a chance to clean up instead of just immediately crashing. Doesn't seem to fit into either of your two uses, but I think it's a legit use. -- David Eppstein http://www.ics.uci.edu/~eppstein/ Univ. of California, Irvine, School of Information & Computer Science From dsada at asd.com Wed Apr 2 11:34:37 2003 From: dsada at asd.com (John Does) Date: Wed, 02 Apr 2003 16:34:37 GMT Subject: that python regex viewer is kodos.sf.net [case closed!] References: <3E8AC763.C89B8B03@engcorp.com> Message-ID: On Wed, 02 Apr 2003 06:20:03 +0000, Peter Hansen wrote: > http://kodos.sourceforge.net/ thanks! From peter at engcorp.com Wed Apr 16 15:53:16 2003 From: peter at engcorp.com (Peter Hansen) Date: Wed, 16 Apr 2003 15:53:16 -0400 Subject: Catching Save - newbie References: <3e9bd039_2@news.estpak.ee> <3e9d1cdd_2@news.estpak.ee> <3E9D5372.494AB8D9@engcorp.com> <7h3of36r3a2.fsf@pc150.maths.bris.ac.uk> <3E9D671A.C2D1CE4D@engcorp.com> <7h3fzoiqv82.fsf@pc150.maths.bris.ac.uk> <3E9D8B1B.24050D34@engcorp.com> <7h3brz6qmsc.fsf@pc150.maths.bris.ac.uk> Message-ID: <3E9DB4AC.E94829D9@engcorp.com> Michael Hudson wrote: > > And unless someone went to the bother of faking a poorly-scanned pdf > of Knuth's paper, the quotation and attribution I gave is correct. Oh, I quite believe that. I've seen it too... > It is entirely possible that Hoare said something like this *as well*, > of course. I don't have a reference, however, and have never seen > one. That is exactly what the pages I had found said. The wording wasn't quite the same, but the meaning was, and I vaguely recall that even Knuth attributed the sentiment to Hoare (but I'll have to do another search myself before I insist on that point at all). -Peter From do-not-spam-ben.hutchings at businesswebsoftware.com Thu Apr 10 10:31:21 2003 From: do-not-spam-ben.hutchings at businesswebsoftware.com (Ben Hutchings) Date: 10 Apr 2003 14:31:21 GMT Subject: Macros in Python? References: Message-ID: In article , Dominic wrote: > > > (defmacro with-root-privs (() &body body) > (let ((oldidsym (gensym))) > `(let ((,oldidsym (geteuid))) > (seteuid 0) > (unwind-protect > (progn , at body) > (seteuid ,oldidsym))))) > > Is there an easy way to produce similar code > in Python which gurantees that certain things > happen around some code? (Maybe by using > generators?) > > The normal approach would be to enclose everything > with try: finally: but this would scatter the > code all over. > > Is something like this feasible? > > def server(a,b): > if cond: > ... > else: > With_Root_Privs: > if x in user: > active.append(x) > (...) Python has nothing like Lisp macros, but you can generically wrap function calls by accepting and passing on arbitrary arguments with the * and ** operators: def with_root_privs(func, *args, **kwargs): save_euid = os.geteuid() os.seteuid(0) try: func(*args, **kwargs) finally: os.seteuid(save_euid) You can use the above like this: def activate_user(x): if x in user: active.append(x) ... with_root_privs(activate_user, x) Alternatively, you can curry the above function: def with_root_privs(func): def call(func, *args, **kwargs): save_euid = os.geteuid() os.seteuid(0) try: func(*args, **kwargs) finally: os.seteuid(save_euid) return lambda *args, **kwargs: call(func, *args, **kwargs) You can then write something like the following: def activate_user(x): if x in user: active.append(x) ... activate_user = with_root_privs(activate_user) ... activate_user(x) From aahz at pythoncraft.com Wed Apr 2 19:32:18 2003 From: aahz at pythoncraft.com (Aahz) Date: 2 Apr 2003 19:32:18 -0500 Subject: Shadowing builtins (was Re: a pyrex-inspired for-i-from-1-to-n...) References: <3E8B7D49.829034FF@engcorp.com> Message-ID: In article <3E8B7D49.829034FF at engcorp.com>, Peter Hansen wrote: > >I hope Greg's comments about being able to disable this are on the >mark, because otherwise this would be a clear case of a desire for >(unnecessary, IMHO) optimization being given higher priority than >maintaining one of Python's strongest advantages. Speed will *never* >be Python's strongest suit, but its dynamicism clearly is; let's not >bugger that up! Maybe I'm misunderstanding something, but I was under the impression that disabling the ability to munge another module's namespace was at least partly driven by the desire to enable secure code. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ This is Python. We don't care much about theory, except where it intersects with useful practice. --Aahz, c.l.py, 2/4/2002 From gh at ghaering.de Tue Apr 15 10:18:03 2003 From: gh at ghaering.de (Gerhard Haering) Date: Tue, 15 Apr 2003 16:18:03 +0200 Subject: any benchmark results for python? In-Reply-To: References: Message-ID: <3E9C149B.7070706@ghaering.de> J Li wrote: > I am looking for benchmark test results for python, in comparison to other > languages like Perl or Java or C++ [...] "There are lies, damn lies, and benchmarks." I'd recommend creating the benchmarks yourself for the particular use cases you have in mind. Be sure to exploit each language's features optimally lest you forge the results. If you're just looking for the bare results of using the *same* algorithm (no libraries, not using any fancy language features) of various language implementations, you can look at: The Great Computer Language Shootout http://www.bagley.org/~doug/shootout/ HTH, -- Gerhard From anthony at interlink.com.au Wed Apr 16 22:21:31 2003 From: anthony at interlink.com.au (Anthony Baxter) Date: Thu, 17 Apr 2003 12:21:31 +1000 Subject: compatibility problem In-Reply-To: <1f4c702e.0304161116.5b0f6565@posting.google.com> References: <1f4c702e.0304161116.5b0f6565@posting.google.com> Message-ID: <200304170221.h3H2LWY02764@localhost.localdomain> >>> Chad Scherrer wrote > So I'm wondering what I should look for to make this work under 2.2.2. The hashing algorithm and the ordering of heterogeneous types changed between 2.1 and 2.2. HTH, Anthony -- Anthony Baxter It's never too late to have a happy childhood. From markscottwright at hotmail.com Mon Apr 7 20:37:07 2003 From: markscottwright at hotmail.com (msw) Date: Tue, 08 Apr 2003 00:37:07 GMT Subject: How to protect python code ? In-Reply-To: References: <3E8BE455.4000904@novagrid.com> Message-ID: <3E921A4C.1020908@hotmail.com> Dave Brueck wrote: > On Mon, 7 Apr 2003, msw wrote: > > >>Jp Calderone wrote: >> >>>On Thu, Apr 03, 2003 at 09:35:49AM +0200, christophe grimault wrote: >>> >>>>Before trying my own solutions, I wonder if someone already has a solution >>>>to this. We have been programming a quite large application in python and >>>>it contains many original algorithm and other things. The application will >>>>be sent to customers in a few month and since it is a commercial app, we >>>>need some protection against copy (illegal copies) and we need to make >>>>sure that critical parts of the code cannot be viewed and studied. >>>> >> >>I'm really interested in this as well, and I think that it's an >>important issue for python. Unfortunately, as I'm sure you've >>discovered by now, it's a question that comp.lang.python is >>constitionally incapable of answering. The only answers you will get in >>this group are: >> >>1. intellectual property law is sufficient >>2. no protection scheme is perfect > > > Not true - check the archives. In the past people, including myself, have > posted the general steps to do to "protect" the code. It's not worth the > effort in most cases, IMO, but answers *have* been given. If so, I was unable to find it, and I think this thread proves my point. I count half a dozen responses to my post, not one of which provided any detail into protecting source code. However, they all go into great detail, at varying levels of insult, about how I shouldn't be asking the question in the first place. I have consulted the archives and the signal/noise ratio is similar. No offense, but this post is a case in point (although more respectful than most) - a few vague sentences about how to accomplish this followed by several paragraphs implying that I don't understand the product requirements. The software I write falls under the category of those that need to have the source code hidden from customers - for many reasons, not least of which is "because the marketing department says so". Our customers are unlikely to go after "movl $0x0007, %ax" with a hex editor, but are almost certain to mess with code that looks like "licenseCount = 5". My frustration with this question is that it seems to offend the c.l.p. readership to such a degress that they collectively decide to drown out any meaningful discussion on the matter. >>I think it ought to be relatively easy to distribute a hacked version of >>the python interpreter with your application that substitutes the >>standard "import" code with code that first looks for .pys files (or, >>what the hell, .tcl - let's not make this any easier) that are >>des-encrypted .py files. > > > It *is* relatively easy to do this - there are various ways to overload > imports, import from libraries, add new extensions and import handlers, > and you don't need a "hacked" interpreter - the simplest example of > running Python from C code will do. That was what I was suggesting - distributing myapp.exe along with python.dll, where myapp.exe installed a different __import__ that looked for files with a particular extention that were scrambled or encrypted. Which then raises the question of how I determine dependencies for setup.py, etc. msw From amk at amk.ca Wed Apr 23 13:09:37 2003 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 23 Apr 2003 12:09:37 -0500 Subject: *Newbie Question* --> Is it viable to distribute Python apps over the Internet? References: <25a672ee.0304210914.1cc2049c@posting.google.com> <3ea434fd$0$180$a1866201@newsreader.visi.com> Message-ID: On 22 Apr 2003 07:25:54 -0700, Graham Fawcett wrote: > I guess the moral of the story is, "contribute some time to > PyPI/Distutils development." Or, befriend a PyPI/Distutils developer > and send him food and get-out-of-work-free tickets. ;-) Contribute time, not money. Money does not make interested developers materialize, and money doesn't help figure out what to do. The great problem is that no one is particularly interested in improving Python's packaging, not even to the extent of offering opinions on concrete proposals or trying out code. (Things that might help: join the Catalog-SIG and try a system that someone else has built. Comment on existing proposals like PEPs 262 and 314. Review the existing code and offer patches.) --amk (www.amk.ca) TAMORA: O cruel, irreligious piety! -- _Titus Andronicus_, I, i From aahz at pythoncraft.com Sat Apr 26 00:55:12 2003 From: aahz at pythoncraft.com (Aahz) Date: 26 Apr 2003 00:55:12 -0400 Subject: How to write RTF from Python? References: <3EA97D61.3CC9FE74@easystreet.com> Message-ID: In article <3EA97D61.3CC9FE74 at easystreet.com>, wrote: > >Any suggestions of the shortest path from a Python program to RTF >output? RTF seems to be the best (reasonable combination of features >and compatability) common denominator for exporting data so that >(windows) users can bring it into their own word processing program, >whatever that may be. (Any problem with that?) Another idea: how about PDF? I don't know if the formatting gets preserved at all if you cut'n'paste, though. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "In many ways, it's a dull language, borrowing solid old concepts from many other languages & styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it." --Tim Peters on Python, 16 Sep 93 From jepler at unpythonic.net Thu Apr 17 15:24:00 2003 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 17 Apr 2003 14:24:00 -0500 Subject: "pythonic" In-Reply-To: References: Message-ID: <20030417192400.GE30789@unpythonic.net> On Thu, Apr 17, 2003 at 03:39:44PM +0000, Courageous wrote: > > >I do not know if this ignorance, laziness, or a meme, but I would like > >to know if there a real definition of "pythonic". Anyone? > > First you have to understand the word "unpythonic". > > This is kind of like the word "communist". You know? During the > 50's, your life was over if you were labeled a "communist"? > Guido, Tim, and team sit on a the Technical Committee for Un[ythonic > Activities. > > Be afraid, be very afraid. uh oh. Jeff Epler From sholden at holdenweb.com Wed Apr 16 09:17:49 2003 From: sholden at holdenweb.com (Steve Holden) Date: Wed, 16 Apr 2003 13:17:49 GMT Subject: Why functional Python matters References: Message-ID: <1Kcna.110587$It5.3946@news2.central.cox.net> "Dave Benjamin" wrote in message news:slrnb9pt1o.iin.ramen at lackingtalent.com... > In article , Courageous wrote: > > Anonymous functions are occasionally useful, as in Java's anonymous > > class expressions, really used as a poor man's lambda of sorts. I've > > seen this overused, though, that's for sure. > > How frequently a feature is useful depends on the problem domain. Java's > anonymous classes are a poor substitute because they carry so much baggage. > For comparison, here's an implementation and usage of map in Java: > > static interface Functor {Object call(Object[] args);} > > static Object[] map(Functor func, Object[] array) { > Object[] result = new Object[array.length]; > for (int i = 0; i < array.length; i++) { > result[i] = func.call(new Object[] {array[i]}); > } > return result; > } > > public static void main(String args[]) { > System.out.println(Arrays.asList(map( > new Functor() { > public Object call(Object[] args) { > return args[0] + ", world!"; > } > }, new String[] {"Hello", "Goodbye"} > ))); > } > > And the same usage in Python: > > >>> print map(lambda x: x + ', world!', ['Hello', 'Goodbye']) > ['Hello, world!', 'Goodbye, world!'] > > This is why Java is IMHO unfit for common functional tasks where Python > shines with elegance. As to whether or not anonymous functions can be > overused, I think any feature can be overused. Classes, for one. In fact, in > my day to day work, I find the two of similar usefulness, but maybe it's > just because of the way I program. =) > I *still* say that Java is object-oriented COBOL. People tend to take offence when I say it, but that example makes the point well. There's so much crud in the typical Java application, most of which could probably be macro-generated from a much more concise "super-source". regards -- Steve Holden http://www.holdenweb.com/ How lucky am I? http://www.google.com/search?q=Steve+Holden&btnI=1 Python Web Programming http://pydish.holdenweb.com/pwp/ From duncan-news at grisby.org Mon Apr 7 15:32:37 2003 From: duncan-news at grisby.org (Duncan Grisby) Date: Mon, 07 Apr 2003 19:32:37 +0000 Subject: Pictures from the Python UK conference Message-ID: <5f0b6$3e91d255$516049d2$2705@nf1.news-service.com> Hi, I took lots of digital pictures at the Python UK conference. In case you're interested, you can see them here: http://www.grisby.org/Photos/128/ Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From srijit at yahoo.com Sun Apr 13 14:58:36 2003 From: srijit at yahoo.com (srijit at yahoo.com) Date: 13 Apr 2003 11:58:36 -0700 Subject: Protected Methods and Python Message-ID: <221d8dbe.0304131058.1ecd1c3c@posting.google.com> I do not see a concept of Protected Methods in Python 2.2 like C++ and Ruby. Is this a serious limitation for Object Oriented Programing with Python? Or may be it is possible to emulated Protected Methods in Python. I look forward to some discussion by OOP experts. Regards, Srijit From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Sun Apr 27 09:05:29 2003 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Sun, 27 Apr 2003 15:05:29 +0200 Subject: problems using magic "" socket address on different platforms Message-ID: <3eabd599$0$49102$e4fe514c@news.xs4all.nl> Hello I'm trying to use UDP broadcasting but there are some weird things going on regarding Python's magic "" address (which is the INADDR_BROADCAST address). Using the following piece of Python code to send UDP broadcast messages: ---- from socket import * sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) sock.sendto("Het Bericht", ("", 2000) ) print "done" ---- This works fine. The problems are in the server code: ---- from socket import * import select import sys sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) sock.bind( ("", 2000) ) while 1: (rs,ws,es)=select.select([sock],[],[],1) if sock in rs: (data, addr) = sock.recvfrom(9999) print "Got data: {%s}" % data print "from:",addr else: print ".", sys.stdout.flush() ---- When running this on Linux, everything works as expected. When running the server code on Windows, Python fails to bind the socket on the magic "" address: socket.error: (10049, "Can't assign requested address") I've had reports of users that the same problem is present on Mac OS X. Because I don't have access to other platforms than Windows (NT) and Linux, I am wondering what the results are on other systems such as Solaris, *BSD... --Irmen de Jong PS The really weird part is that a piece of C code that directly uses the BSD socket API *also* fails on windows with the same error (bind: Cannot assign requested address, when trying to bind the socket on the INADDR_BROADCAST address). The exact same piece of C code runs fine on Linux. Used GCC in both cases. If you're interested in this code let me know, I thought it was too big to post here. PPS To get my code to work on windows, I had to use the magic "" address (INADDR_ANY). But I don't think that's right, "" should work, shouldn't it? From abpillai at lycos.com Mon Apr 14 05:48:20 2003 From: abpillai at lycos.com (Anand B Pillai) Date: 14 Apr 2003 02:48:20 -0700 Subject: Python Jobs Message-ID: Can somebody give me a python job ? I am quite bored of my current job and I love python programming. I need a change desperately but I am not getting it. I am ready to relocate out of my country to U.S/U.K for the job. If somebody thinks he has a job, my profile is avaialable to them for review. Mail me at this email address. Or visit my webpage http://members.fortunecity.com/anandpillai. I dont want to write further, but I am quite desperate for a shift from C/C++. Thank You. Anand From cswiger at mac.com Thu Apr 10 20:32:56 2003 From: cswiger at mac.com (Chuck Swiger) Date: Thu, 10 Apr 2003 20:32:56 -0400 Subject: popen(), sendmail: Success? In-Reply-To: References: <3e95d63f.2635484@news.muenster.de> Message-ID: <3E960D38.6020601@mac.com> In article <3e95d63f.2635484 at news.muenster.de>, Martin Bless wrote: > To send mails from Python here's the example my provider provides: > This http://faq.puretec.de/skripte/python/3.html > > The relevant lines are these: > > sendmail = os.popen("/usr/lib/sendmail -t", "w") > sendmail.write(msg) > sendmail.close() > > This works just fine. But is it enough? How do I know the operation > succeeded? If you plan on sending any significant amount of mail, it is recommended that your code talk SMTP to port 25 and pipeline all of the messages you need to send in one continuous stream. If you fork a sendmail subprocess for each message you send, that will create a wastefully huge amount of system load. This has a nice side-effect: your code becomes more portable since you can point to a SMTP server anywhere that is willing to relay your messages, not just one on localhost. Nor does the local host have to have /usr/lib/sendmail, meaning your code will run under Windows or elsewhere non-Unixlike. With regard to error handling, sendmail will generate an error return value; adding the "-v" flag to your sendmail invocation will show the details of the SMTP or LMTP transaction if you want to see what's going on for debugging purposes. I'd assume there is an smtp module that would let you see the success or error code and messages from doing SMTP, as well. Good luck, -Chuck PS: Note that handing the mail off does not guarantee that the email will actually be read by the intended receipient: if that is part of your meaning of "the operation succeeded", you might want to generate messages which request the user to mail a password/token back or click an URL to confirm that the email went through. See the Mailman mailing list program (www.list.org) for examples of "good email handling" practices. From godoy at metalab.unc.edu Tue Apr 8 18:01:13 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Tue, 08 Apr 2003 19:01:13 -0300 Subject: Best way to make a weighted sum References: <867ka46awj.fsf@ieee.org> Message-ID: <86r88c3aza.fsf@ieee.org> Lulu of the Lotus-Eaters writes: > Jorge Godoy wrote previously: > | def CalculaSoma(self): > | ie = self.ie > | iter = len(ie) > | for i in ie: > | produto = i * self.pesos[iter] > | self.soma = self.soma + produto > | iter = iter - 1 > |I don't know if I got it in the most pythonic way in my code. > > Looks fine. You could be somewhat more concise with: > > from operator import mul, add > amts, weights = pesos.keys(), pesos.items() > sum = reduce(add, map(mul, amts, weights))/reduce(add, weights) > > I'll leave it to a native speaker to translate my var names to > Portuguese. > > Yours, Lulu... Thanks. This is also the kind of thing I was looking for. The reduce() and zip() functions are very interesting. And the operator module was already being used in other parts of the code, so why not here, in this class? :-) -- Godoy. "... The name of the song is called 'Haddocks' Eyes'!" "Oh, that's the name of the song, is it?" Alice said, trying to feel interested. "No, you don't understand," the Knight said, looking a little vexed. "That's what the name is called. The name really is, 'The Aged Aged Man.'" "Then I ought to have said "That's what the song is called'?" Alice corrected herself. "No, you oughtn't: that's quite another thing! The song is called 'Ways and Means': but that's only what it is called you know!" "Well, what is the song then?" said Alice, who was by this time completely bewildered. "I was coming to that," the Knight said. "The song really is "A-sitting on a Gate": and the tune's my own invention." -- Lewis Carroll, "Through the Looking Glass" From aleax at aleax.it Tue Apr 29 08:11:21 2003 From: aleax at aleax.it (Alex Martelli) Date: Tue, 29 Apr 2003 12:11:21 GMT Subject: Determining the volume ID for a file/drive? References: Message-ID: carroll at tjc.com wrote: > Is there any way to determine the volume serial number for a disk, > given the filename (or drive, since I can determine the drive from the > filename with os.path.splitdrive(os.path.abspath(file))? > > My environment is Windows & Python 2.2.2, and I don't need for my code > to be portable. Quick and dirty...: import os x = os.popen('C:\\') x.readline(); x.readline() vsn = x.readline().strip()[-9:] x.close() Perhaps too dirty. If you want to do it via a Win32 API call, you need to determine what call is it (e.g. via MSDN) and then use win32all or ctypes to go and call it. But parsing dir's output is quite a bit quicker to program;-). Alex From vjb at vuit.com Tue Apr 29 11:47:47 2003 From: vjb at vuit.com (Vince Buonassisi) Date: Tue, 29 Apr 2003 08:47:47 -0700 Subject: import problem Message-ID: hi, i am having problems importing a module in my python script. i have the following two import statements in the script: from WVWService.util import XMLUtil from WVWService.test import HTTPClient the first import works just fine. but, the second one i get the error "ImportError: No module named test". i have checked for mispellings; i have checked to see if the directory test exists; i have checked the system path by printing out sys.path from w/i the script to see if the directory path is in sys.path (/home/vjb/workspace/wvwBase3/src/wvw). i don't understand why the first import works and the second one does not since the directories util and test reside in the same directory path. i am using python 2.2.2 on redhat 8.0. any help would be appreciated. thanks, vince From hllee678 at hotmail.com Mon Apr 21 08:03:08 2003 From: hllee678 at hotmail.com (=?big5?B?p/UgvuWswg==?=) Date: Mon, 21 Apr 2003 20:03:08 +0800 Subject: (no subject) Message-ID: Hi, I have a problem about M2Crypto. I am using M2Crypto to write the SSL server and client. My server was based on Medusa. The client built a SSL connection to server, and then created a new thread to receive the response from server. The code of client: rfile=sock.makefile('rb',-1) #sock is the ssl connection between server and client try: data = rfile.read(100) if not data: print "no data, maybe try to close connection" except: print "exception, maybe try to close connection" When the server shutdown and close the SSL connection between server and client, the client receiving thread raised a windows exception on rfile.read procedure: Unhandled exception in python.exe (PYTHON21.DLL): 0xC0000005: Access Violation The code of server: sock.shutdown(2) # socket is the ssl connection between server and client sock.close() Please help me if you know how to solve this problem. Thank you very much! _________________________________________________________________ ??????? MSN Messenger???????????????????????? ???? http://messenger.msn.com.tw/ From spam at magnetic-ink.dk Tue Apr 1 03:39:43 2003 From: spam at magnetic-ink.dk (Klaus Alexander Seistrup) Date: Tue, 1 Apr 2003 08:39:43 +0000 (UTC) Subject: Comments References: <435d40e0.0304010014.503f9f8f@posting.google.com> Message-ID: Chris wrote: > I would like to request that Python support multi-line > comments (e.g. /* */ in C). You could always enclose comments in triple-quotes: #v+ comment = """ Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, qu? ab illo inventore veritatis et quasi architecto beat? vit? dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam qua?rat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molesti? consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? """ #v- // Klaus -- ><> unselfish actions pay back better From yaipa at yahoo.com Sat Apr 19 14:48:35 2003 From: yaipa at yahoo.com (yaipa h.) Date: 19 Apr 2003 11:48:35 -0700 Subject: Parent references: hot or not? References: Message-ID: <6e07b825.0304191048.3fe5976d@posting.google.com> Dylan, Might be worth the look... Multiple dispatch . Generalizing polymorphism with multimethods by David Mertz, Ph.D. (mertz at gnosis.cx) link, http://www-106.ibm.com/developerworks/linux/library/l-pydisp.html ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Dylan Reinhardt wrote in message news:... > Hi all, > > I'm working on a project where I have multiple instances of a container > class that each hold a large number of another class. > > I need the "contained" object to be able to make use of methods and > attributes in its container. Inheritance won't do the trick since the > things I need to refer to will be pretty dynamic. > > A very minimal example of what I'm doing: > > --------------- > > class Container: > def __init__(self): > self.items = {} > > def add_item(self, item_name): > self.items[item_name] = Item(self) > > some_attr = 'spam' > > > class Item: > def __init__(self, parent): > self.parent = parent > > def some_method(self): > return self.parent.some_attr > > --------------- > > This seems to be working well, but I want to check my assumptions. > > If I'm understanding correctly: > > 1. Any Item's self.parent is only a *reference* to its parent. > 2. Holding a reference to a parent isn't some kind of recursive paradox. > 3. As I add Items, Container size will grow linearly, not exponentially > 4. It will be impossible to fully delete a non-empty Container. > > I think those are valid assumptions, but would appreciate any > confirmation, contradiction, or insight anyone cares to offer. > > Also, if there's some other consideration or reason why holding a > reference to one's parent is a Bad Idea, I'd love to hear about it. > > Thanks in advance, > > Dylan From Bill.Scherer at verizonwireless.com Tue Apr 8 13:18:02 2003 From: Bill.Scherer at verizonwireless.com (Scherer, Bill) Date: Tue, 8 Apr 2003 13:18:02 -0400 (EDT) Subject: ANN: SQLObject 0.3 In-Reply-To: <1049822101.734.40.camel@lothlorien> Message-ID: On 8 Apr 2003, Ian Bicking wrote: > On Tue, 2003-04-08 at 09:13, Scherer, Bill wrote: > > On 7 Apr 2003, Ian Bicking wrote: > > > > > SQLObject 0.3 has been release: > > > http://sqlobject.org > > > > Is support for Oracle planned? > > Sure, someone just has to add it (I don't have Oracle). It should be > quite easy. Cool. I'll give it a go and let you know. > > Ian > -- Bill.Scherer at Verizon Wireless RHCE 807101044903581 From marcus at infa.abo.fi Mon Apr 14 16:27:48 2003 From: marcus at infa.abo.fi (Marcus Alanen) Date: 14 Apr 2003 22:27:48 +0200 Subject: Complexity of standard Python data structures References: Message-ID: On Mon, 14 Apr 2003 14:04:57 -0400, Tim Peters wrote: >If you want to clear a list, > > del list[:] > >is the usual way to spell it; > > list[:] = [] OK, that has slipped past me, thanks for clarifying. And it'll save the bandwidth of one mail :) >Note that it's not true that Python's list is really a vector/array -- the >language doesn't define its implementation, and doesn't want to. It is true Hmm. So the Python language is more about specifying _what_ will happen, instead of _how_, with no concern for actual speed or memory? Marcus From peter at engcorp.com Mon Apr 21 07:52:11 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 21 Apr 2003 07:52:11 -0400 Subject: Mail and text extraction References: <3EA34DAE.EC67C1E3@engcorp.com> Message-ID: <3EA3DB6B.DAC620BD@engcorp.com> Dino Levy wrote: > > On Mon, 21 Apr 2003 03:47:26 +0200, Peter Hansen wrote: > > > > Why not download the whole message, then scan it after downloading? You > > provide no good reason, so far, for why you wouldn't just do this much > > simpler step. Keep the design simple, modular, clean, and you can do > > most of what you want with simple, modular, existing solutions in > > standard modules. Why wouldn't you do that? > > > > -Peter > > Well yes, that's antoher way of doing it, but I wanted to make it done in > one breath, like connecting and immediately parsing the text, but it's > obviously not achievable:) Oh, it's quite achievable that way. It's just the wrong way to do it. Mixing in the various operations like that is a form of optimization, and since nothing's actually working yet it's clearly premature, and therefore not good. :-) > I don't want MIME, I really need POP3 connections... > Ok, thanks anyway MIME and POP3 are orthogonal. MIME is an encoding, POP3 is a transport protocol (or something). You can have one, or the other, or both, or neither... By the way, the "quite achievable" part above simply means you could easily build this capability into custom software. The "wrong way" just means that would likely be a large waste of time, given that the individual pieces already exist in standard modules, quite well tested and debugged. Just combine them in appropriate ways and keep life simple. -Peter From fredrik at pythonware.com Fri Apr 25 13:51:41 2003 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 25 Apr 2003 19:51:41 +0200 Subject: What means exactly "Memory error"? References: Message-ID: Albert Hofkamp wrote: > Do you need all data DOMmed at once? > You may be able to have one DOM tree at a time, dropping and reloading > everytime you switch file. an alternative is to use an incremental tree builder, and process the subtrees as they arrive. here's an example, using my elementtree module: from elementtree import ElementTree class MyBuilder(ElementTree.TreeBuilder): def end(self, tag): elem = ElementTree.TreeBuilder.end(self, tag) if elem.tag == "SCENE": # process(elem) in some way, and write it out # ElementTree.ElementTree(elem).write(sys.output) elem.clear() # nuke it parser = ElementTree.XMLTreeBuilder() parser._target = MyBuilder() # plug in a custom builder! tree = ElementTree.parse(filename, parser) I've tested this with a 10 megabyte XML file created by concatenating Jon Bosak's Hamlet XML file over and over again, and wrapping it all in a single document element. the resulting file contains 720 scenes (about 15k each, in average). the above script requires about 4.5 megabytes to run to completion, and about 2 minutes processing time (on a really slow machine). if I comment out the elem.clear() call, the script requires about 75 mega- bytes, in about 15 minutes (13 of which were spent on swapping; I ran the test on a machine with 96 megabytes RAM and really slow disks... ;-) for more information on element trees, see: http://effbot.org/zone/element-index.htm http://www.xml.com/pub/a/2003/02/12/py-xml.html From cpitaar at yahoo.com.ar Wed Apr 30 08:23:27 2003 From: cpitaar at yahoo.com.ar (Carlos P.) Date: 30 Apr 2003 05:23:27 -0700 Subject: Raising objects References: <453d10b2.0304290750.222fb453@posting.google.com> Message-ID: <453d10b2.0304300423.224abe55@posting.google.com> > restriction will be removed -- in particular, because I do not know > of "use cases" where the ability to raise new-style classes or instances > thereof would be a major boon to an application. Maybe you have some...? In fact, I have no one. I've just written a nice metaclass Metaclass which automatically generates instance/static properties/methods from getters/setter/methods according to naming conventions, and naive stuff like that. I intended to use class Object (a new style class with metaclass Metaclass) as a base class for my application. The point of using it with exceptions is only to be consistent and, before your answer, it was natural to try to derive an exception from ObjectException (a subclass of Exception and Object). Nothing sooo important, just would be nice if possible. Thank you. From jidanni at dman.ddts.net Tue Apr 15 01:59:54 2003 From: jidanni at dman.ddts.net (Dan Jacobson) Date: Tue, 15 Apr 2003 13:59:54 +0800 Subject: do python's nifty indentation rules spell the death of one-liners? Message-ID: <87he90b8rp.fsf@jidanni.org> I need to use one liners every day, especially in Makefiles. I thus need to know how to make any kind of python program into a big long one liner. However, right out of the starting gates I run into $ python -c 'print 2;for i in (1,4):print i' File "", line 1 print 2;for i in (1,4):print i ^ SyntaxError: invalid syntax Help. BTW tell me what to do in all the other cases when ";" can't be a replacement for newline. I.e. does python's nifty indentation rules spell the death of one-liners? BTW, how do I import a module from the command line when using -c? Is there an option switch for importing modules? This makes no output and returns no error value to the shell: $ python -c 'import math' -c 'for i in range(200,500,50): print i,360/2/math.pi*math.asin(i/1238.4)' If I found a bug, report it for me. -- http://jidanni.org/ Taiwan(04)25854780 From dsavitsk at e-coli.net Fri Apr 25 18:18:03 2003 From: dsavitsk at e-coli.net (dsavitsk) Date: Fri, 25 Apr 2003 22:18:03 GMT Subject: How to write RTF from Python? References: <3EA97D61.3CC9FE74@easystreet.com> Message-ID: wrote in message news:3EA97D61.3CC9FE74 at easystreet.com... > Any suggestions of the shortest path from a Python program to RTF > output? RTF seems to be the best (reasonable combination of > features and compatability) common denominator for exporting > data so that (windows) users can bring it into their own word > processing program, whatever that may be. (Any problem with > that?) > > Requirements are about like this: > > 1. Don't need an edit control, just want to write a file, but if > I have to open an edit window, I can. > > 2. Don't want to do too much fancy. Text, headings, bulleted > lists, maybe some variations in font size. > > 3. Development platform is WinNT, target platform is any reasonably > recent Windows machine (eg either anything newer than Win95 release 1 > or Win98 or better). Your requirements suggest to me that html is the best common denominator, and it's easier to write. -d From andrew-pythonlist at puzzling.org Sun Apr 27 04:36:16 2003 From: andrew-pythonlist at puzzling.org (Andrew Bennetts) Date: Sun, 27 Apr 2003 18:36:16 +1000 Subject: Forgetting "()" when calling methods In-Reply-To: References: <698f09f8.0304262115.386c2571@posting.google.com> <3EAB6A14.707AD826@alcyone.com> Message-ID: <20030427083616.GP26530@frobozz.local> On Sun, Apr 27, 2003 at 07:54:28AM +0000, Alex Martelli wrote: > Erik Max Francis wrote: > > > Jeremy Fincher wrote: > > > >> Perhaps the answer is to remove the __nonzero__ method on > >> functions/methods. Logically, what purpose does it serve? > > > > # f holds a callable object or None > > if f: > > f(...) > > > > I think "if f is None:" and even more "if callable(f):" are > better ways to express this test -- explicit is better than > implicit. However, if this (inferior) expression is indeed Taken to extremes, "explicit is better than implicit" suggests we should be using a statically typed language.... ;) Fortunately, The Zen of Python has plenty of mildly contradictory statements, which helps in defending one's viewpoint :) -Andrew. From max at alcyone.com Fri Apr 25 05:57:16 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 25 Apr 2003 02:57:16 -0700 Subject: Char to ASCII and back ? References: Message-ID: <3EA9067C.199071E0@alcyone.com> Jean-Paul Roy wrote: > How do you transform a char (or a one-char string) into the integer > ascii code and back ? Say to code a message. You want ord and chr, respectively: >>> ord('A') 65 >>> chr(65) 'A' > The string type is not mutable in Python. Is there something like the > StringBuffer class in Python whose instances would be mutable ? You almost certainly want a variant of the StringIO class, either in the StringIO (Python-only) or cStringIO (optimized C): >>> import StringIO >>> output = StringIO.StringIO() >>> output.write("Hello, world.\n") >>> output.getvalue() 'Hello, world.\n' >>> input = StringIO.StringIO("Goodbye, world.\n") >>> input.read() 'Goodbye, world.\n' -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ The actor is not quite a human being -- but then, who is? \__/ George Sanders Bosskey.net: Unreal Tournament 2003 / http://www.bosskey.net/ut2k3/ A personal guide to Unreal Tournament 2003. From jkraska at san.rr.com Tue Apr 15 22:55:46 2003 From: jkraska at san.rr.com (Courageous) Date: Wed, 16 Apr 2003 02:55:46 GMT Subject: Speed of string += string References: <18s6dy4mcsgjg$.y4vahh6w5lp3.dlg@40tude.net> Message-ID: >>But is that /guaranteed/ (as it is with STL), or does it just happen to >>be that way with the current implementation (however unlikely it is to >>change)? >Both, sort of. Python uses dicts internally; you can rely on any >changes to achieve roughly equivalent or better performance guarantees. Yeah, but dictionaries are only /guaranteed/ to scale O(N). 'Course, I recall that a fairly good mathematician or two seems to think that amortized times are fine; these /tend/ to scale O(1). It doesn't hurt at all that Python's dictionary implementation has been tuned and tested more than just about any dictionary implementation in any production environment anywhere*. :) My interpretation of his question makes me wonder how he came to believe that Guido and Tim are on a standards committee, dictating how the host of various and sundry Python compiler developers will design Python implementations. Or perhaps he fears that someone will steal Python from us and do something evil, like replace dict with a red-black tree. :-) performed-an-extensive-analysis-twenty-years-from-now-and-mailed- it-backwards-through-time-ly yrs* C// From gangli at msn.com Tue Apr 8 11:54:05 2003 From: gangli at msn.com (gang li) Date: 8 Apr 2003 08:54:05 -0700 Subject: [ANN?] Boston PIGs References: Message-ID: <9dfc16ab.0304080754.459eace3@posting.google.com> It is greate idea. I am in Boston area, and defintly like to attend a meeting once a month. Jack Diederich wrote in message news:... > After six months of subscribing to c.l.py I haven't seen any activity that > specifically targets Boston. As implied, that is where I am. If there was a > caucus I would attend a monthly Python Interest Group. Heck, if arstechnica > can pull fifty people a couple times a year it can't be all that hard. > > Would anyone be interested in attending a regular Boston Python meeting? > > Possible names abound, > BAPIG (Boston Area Python Interest Group) > BPIGs (Boston Python Interest Group)s > BPUG (feh) > BeePee (phonetical) > > -jack From peter at engcorp.com Tue Apr 1 08:47:40 2003 From: peter at engcorp.com (Peter Hansen) Date: Tue, 01 Apr 2003 08:47:40 -0500 Subject: spawning a separate process References: Message-ID: <3E89987C.5B133AED@engcorp.com> Mark Light wrote: > > I have a python program from which I wish to spawn an os.system call > (a bash script) that may take several minutes to run - whilst the rest of > the script carries on. I have tried using bits of code from books - but it > never seem to work quite right In addition to P?draig's response, here's another possibility: import threading class RunInBackground(threading.Thread): def __init__(self, command): threading.Thread.__init__(self) self.command = command self.start() self.done = False def run(self): import os os.system(self.command) self.done = True Then do something like: bgThread = RunInBackground('/bin/bash mycommand') Using the popen approach is no doubt better if you don't have "special needs", but this might make it easier for you to extend the functionality if you decide you need more than what you originally asked for. -Peter From staschuk at telusplanet.net Wed Apr 16 16:50:11 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Wed, 16 Apr 2003 14:50:11 -0600 Subject: A better unittest In-Reply-To: <1EadnQb6ZY_RDwCjXTWcog@comcast.com>; from tjreedy@udel.edu on Wed, Apr 16, 2003 at 01:36:03PM -0400 References: <3ckier9a.fsf@python.net> <1EadnQb6ZY_RDwCjXTWcog@comcast.com> Message-ID: <20030416145011.E4266@tibia.amotlpaa.bogus> Quoth Terry Reedy: [...] > I like having the actual values too. It should make debugging an > unexpected failure easier. But what if each value is more that a few > bytes? Example (from my future plans): two lists of all permutations > of range(8), one produced by an obvious recursion and the other by a > much less obvious iteration. Now and then I replace self.assertEquals(longlist1, longlist2) with map(self.assertEquals, longlist1, longlist2) It's not quite ideal; in some cases it would be nice to see the index of the mismatch too, for example. -- Steven Taschuk staschuk at telusplanet.net "Its force is immeasurable. Even Computer cannot determine it." -- _Space: 1999_ episode "Black Sun" From aleax at aleax.it Wed Apr 23 18:07:26 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 23 Apr 2003 22:07:26 GMT Subject: python language: infimum and supremum of integers References: <5jadeg285s.fsf@xoxy.net> Message-ID: Charlie Reiman wrote: > Alex Martelli writes: > >> >> > >> For your algorithm, why not just, for example: >> >> class Infimum: >> def __cmp__(self, other): return -1 >> infimum = Infimum() >> >> class Supremum: >> def __cmp__(self, other): return 1 >> supremum = Supremum() >> >> as coded these have obvious anomalies, e.g. infimum < infimum -- but >> those are easy to remove if they give problems to your algorithm. > > > Are there any dangers in something like this: > > a = [1, infimum, infimum] > a.sort() Quite possibly -- so IF your algorithms sorts lists, then the "easy to remove" anomalies should be removed. > Should the __cmp__ methods return 0 for equality (identity, in this > case)? If you need sorting, yes -- "return (other is not self) and -1" will suffice. But, should you never need to compare infimum to itself, then the precaution, cheap as it may be, won't pay for itself. You pays your money and you takes your choices. Alex From syver-en+usenet at online.no Sun Apr 6 08:35:22 2003 From: syver-en+usenet at online.no (Syver Enstad) Date: 06 Apr 2003 14:35:22 +0200 Subject: I'm new to programming References: Message-ID: Casey Jones writes: > Inspiration would be appreciated. video games, sound or graphics? Try pygame http://www.pygame.org -- Vennlig hilsen Syver Enstad From exarkun at intarweb.us Tue Apr 8 01:12:55 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Tue, 8 Apr 2003 01:12:55 -0400 Subject: Cross-reference 'import' in a class hierarchy In-Reply-To: References: <3E90D2DB.1A799612@alcyone.com> <7h3llymio0q.fsf@pc150.maths.bris.ac.uk> Message-ID: <20030408051255.GA1934@meson.dyndns.org> On Tue, Apr 08, 2003 at 04:55:09AM +0000, Ben Finney wrote: > On Tue, 08 Apr 2003 15:44:10 +1200, Greg Ewing (using news.cis.dfn.de) wrote: > > It's been suggested before (and I happen to agree) that Python should > > provide a general way of making *relative* references to modules or > > packages. > > I continue to be amazed that there's simply no way to say > > import "../foo/ook.py" > > as should be possible to implement any well-architected class hierarchy. It's simple. Code should not depend directly on code higher than it in the package hierarchy. If it does (and it isn't one of a few extremely rare cases), it is misdesigned. Code shallow in the hierarchy should manage required references to objects required by code deep in the hierarchy by passing them around explicitly. Any other solution is just bunk. Jp -- http://catandgirl.com/view.cgi?90 -- up 19 days, 1:01, 3 users, load average: 0.00, 0.02, 0.00 From tim at bladerman.com Fri Apr 4 07:53:57 2003 From: tim at bladerman.com (Tim Gahnström /Bladerman) Date: Fri, 04 Apr 2003 12:53:57 GMT Subject: Interactive loop with InteractiveInterpreter Message-ID: I am trying to make an interactive interpreter for python source code. It is all fun and games with Interactiveinterpreter.runcode() as long as it is simple statements like print "hello" print "world" Then I can feed it one line at the time and probably highlight the actuall line in the editor but when it comes to a loop I must feed runcode the whole statement, the whole loop. for i in list: print i The above can be feed to runcode but I want to step trough the list and se each printing operation not all at once. Is it possible to step through a loop at all? With interactive interpreter? I can't seem to find an easy solution, I guess InteractiveConsole won't do it either. Is it maybe better to do it in a completley different way? Any ideas or suggestions are welcome. Thanks Tim From marcus at infa.abo.fi Thu Apr 17 11:45:45 2003 From: marcus at infa.abo.fi (Marcus Alanen) Date: 17 Apr 2003 17:45:45 +0200 Subject: Complexity of standard Python data structures (Re: Speed of string += string) References: <18s6dy4mcsgjg$.y4vahh6w5lp3.dlg@40tude.net> <2DFma.19063$T34.605833@news2.tin.it> Message-ID: On Mon, 14 Apr 2003 21:21:02 GMT, Alex Martelli wrote: >It basically seems to me that you're basing your expectations >of Python docs, and those of C docs, on very different, unfair >standards -- i.e., perhaps subconsciously, singling Python and >its docs out for criticism by standards you don't apply to C... ok, you are right, I was being unfair. On the other hand, given the amount of questions regarding big-O notation & string += string at the moment on c.l.p, perhaps there should be a note -- a "warning" sounds a bit extreme? Also in the docs of C functions, of course! Sometimes, unix man pages have usage examples. Perhaps there should be "anti-usage" examples as well? :) >Wrong, actually. E.g., what happens when you loop doing alist.append >N times depends NOT just on alist being "a vector/array", but also, >and crucially so!!!, on the overallocation strategy (size vs capacity >in std:: vector terms). If you think that strategy is "obvious >from that one single sentence" you're sorely mistaken -- as is shown >by the fact that Python's strategy in that regard has historically >changed reasonably recently (almost nobody noticed, except a few >big-O purists who sleep easier at night knowing append IS now >amortized O(1) in theory, too, not just in practice;-0). And what ok, that's correct as well, I generalized far too much. Curiously, people do seem to start explaining the python list as e.g. "a C++ vector", or "a contiguous array of heterogeneous elements". I do understand that Python people don't want to make any guarantees, although describing some implementation might make it easier for people to learn (or migrate to) Python. >> - programming is about meeting requirements >> - those requirements usually involve correctness to a certain >> degree, _but_ also memory usage, speed, user interface functionality, >> error handling, modularity, documentation, extendability. >order in which you list the "also" requirements is rather weird >with respect to most code a typical application programmers >develops in the course of his or her career;-). Just scramble the order to suit your or the typical application programmer's tastes. ;) >Still, this discussion helped me -- thanks. Basically, you're >saying you found the Python docs you used to be no better than >those for other languages, or, at least, not better by enough >to satisfy your specific interests -- an early focus on HOW >things are being done rather than on WHAT EXACTLY is being done, >implementation rather than interface, so to speak. So, from >my current, incomplete understanding, I think this is a rather >"niche", marginal issue. I didn't mean to start any crusade to change Python docs. If you consider it a niche, that's just fine with me. Marcus From kp at kyborg.dk Tue Apr 8 10:43:23 2003 From: kp at kyborg.dk (Kim Petersen) Date: Tue, 08 Apr 2003 16:43:23 +0200 Subject: Could Emacs be rewritten in Python? References: <3E9040CF.2040606@removethis.free.fr> <6ee58e07.0304061722.2472b3d0@posting.google.com> <3E9175A5.1060607@kyborg.dk> Message-ID: <3E92E00B.6000708@kyborg.dk> > (defun foo() > (message "when foo is called folding is: %s" case-fold-search)) > (defun bar() > (message "when bar is called folding is: %s" case-fold-search) > (let ((case-fold-search t)) > (foo)) > (message "now folding is: %s again" case-fold-search)) > (bar) hmmm - occured to me that you might mean that case-fold-search was a global variable first - then local.... but that wouldn't matter to this since we would need to do lookup in locals first _then_ in globals (as expected) -- Med Venlig Hilsen / Regards Kim Petersen - Kyborg A/S IT - Innovationshuset Havneparken 2 7100 Vejle Tlf. +4576408183 || Fax. +4576408188 From news at snakefarm.org Tue Apr 8 17:23:30 2003 From: news at snakefarm.org (Carsten Gaebler) Date: 8 Apr 2003 21:23:30 GMT Subject: How to split string in equally long parts References: Message-ID: Heiko Henkelmann wrote: > I need to split a string into an array of equally long substrings, like > e.g.: > > '1234567890' -> ['12', '34','56','78','90'] > > What is the most efficient way to do this? I don't know how efficient it is but this is what came to my mind: import re filter(None, re.split('(.{2})', '1234567890')) cg. From marklumsden at comcast.net Wed Apr 30 10:53:29 2003 From: marklumsden at comcast.net (Mark Lumsden) Date: 30 Apr 2003 07:53:29 -0700 Subject: win32com and makepy problem with LabVIEW Message-ID: <8653a280.0304300653.72ce712@posting.google.com> Hi, I'm having some problems using makepy and win32com to talk to LabVIEW with python. I have a number of methods in LabVIEW that require "By Ref" variable types and therefore I need to use the early binding provided from makepy. So I run makpy on the LabVIEW server and it generates the code correctly. However, whenever I try to initiate a session (using win32com.client.Dispatch), it doesn't seem to enable early binding. Forcing early binding from gencache.EnsureModule generates a 'Library not registered' error. In addition, when I run 'makepy -i' I get the following output: >>> Warning - could not load registered typelib '{9A872073-0A06-11D1-90B7-00A024CE2744}' LabVIEW 6.1 Type Library {9A872073-0A06-11D1-90B7-00A024CE2744}, lcid=0, major=5, minor=2 >>> # Use these commands in Python code to auto generate .py support >>> from win32com.client import gencache >>> gencache.EnsureModule('{9A872073-0A06-11D1-90B7-00A024CE2744}', 0, 5, 2) I believe the Warning in the first line above is at the root of the problem. I can work around this problem - if I rename the file 9A872073-0A06-11D1-90B7-00A024CE2744x0x5x2.py generated from makepy to labview.py and then load this file directly. i.e.: import labview test=labview.Application() Then the early-binding works and everything is fine. I can live with this solution but I'd be happier knowing what the problem is. Thanks, Mark From hal_wine at yahoo.com Fri Apr 4 19:40:31 2003 From: hal_wine at yahoo.com (Hal Wine) Date: Fri, 04 Apr 2003 16:40:31 -0800 Subject: Invalid format character in string In-Reply-To: References: Message-ID: <3E8E25FF.5060600@yahoo.com> Nikolai Kirsebom wrote: > Hi, > The problems arise where the HTML editor used (to produce the file in > the first place) has put various expressions of %; and %>. These are > HTML codings the creator of the HTML file does not really know about. > As an example, I've just told them (the users creating the HTML file) > that they should write the text "%(name)s" where they want the name > generated and "%(age)s" where they want the age generated. Then my > script is run for a set of person objects producing a set of HTML > files with the correct names and corresponding ages. Try replacing those sequences with entries that you add to your dictionary to map it back to the original: html_in = html_in.replace('%;', '%(_SEMI)s' ) \ .replace( '%>;', '%(_SEMI_GT)s') dict.update({'_SEMI':'%;', '_SEMI_GT':'%>;'}) html_out = html_in % dict --Hal From fidtz at clara.co.uk Fri Apr 25 10:31:49 2003 From: fidtz at clara.co.uk (Fidtz) Date: 25 Apr 2003 07:31:49 -0700 Subject: Reading a non-standard floating point format Message-ID: <24944f78.0304250631.1778654e@posting.google.com> I'm trying to do a database extraction program. Part of this is reading a large number of files with a 48bit floating point format that I think from the definition and searching on google, is unlike any on any other system (at least current ones anyway). While I think I can see the way to do this with various bit-grubbing techniques, the potential for error is massive, esp considering my non comp-sci background. Does anyone know of a library in python or even (fairly) easily wrappable C that might let me specify the format in a more high level way? Dominic From Bill.Scherer at verizonwireless.com Tue Apr 8 10:13:30 2003 From: Bill.Scherer at verizonwireless.com (Scherer, Bill) Date: Tue, 8 Apr 2003 10:13:30 -0400 (EDT) Subject: ANN: SQLObject 0.3 In-Reply-To: <1049776366.759.96.camel@lothlorien> Message-ID: On 7 Apr 2003, Ian Bicking wrote: > SQLObject 0.3 has been release: > http://sqlobject.org Is support for Oracle planned? > > Changes > ------- > > * Automatic table creation based off class. > * Create classes from database. > * Dynamically add and remove columns to live classes and databases. > * anydbm-based backend (queryable database without SQL). > * Better caching. > * Some bugs fixed. > > What is it? > ----------- > > SQLObject is an object-relational mapper. It allows you to translate > RDBMS table rows into Python objects, and manipulate those objects to > transparently manipulate the database. > > SQLObject emphasizes convenience. It's easy to learn and easy to use, > and doesn't require too much typing or use of any tools outside of your > editor and your Python source. > > > -- Bill.Scherer at Verizon Wireless RHCE 807101044903581 From grante at visi.com Mon Apr 21 14:14:22 2003 From: grante at visi.com (Grant Edwards) Date: 21 Apr 2003 18:14:22 GMT Subject: *Newbie Question* --> Is it viable to distribute Python apps over the Internet? References: <25a672ee.0304210914.1cc2049c@posting.google.com> Message-ID: <3ea434fd$0$180$a1866201@newsreader.visi.com> In article , Jp Calderone wrote: >> I'm blabbering! Anyway, my problem is this. I tried to compile >> a simple Hello World program into something runnable on >> non-python computers, and it came out being 7MB in size. Is >> there something I'm doing wrong? Just so you know, I do know >> somewhat what I'm doing. I know that it's incorporating all of >> the GUI. So is there a way to not incoporate all of the gui, >> and still have a functional program? I'm thinkin in the 800k >> range for a simple program? The reason I ask is because I'm >> thinking of porting something I made in VB to Python before I >> develop it any further. > > Though 7MB is slightly larger than the numbers I've seen, it is > in the right ballpark. > > It's easy to see why. You're distributing an entire runtime > environment, instead of just your application. When you write > VB code, you're only distributing your application. Has anybody tried distributing their Python app w/o bundled Python but with a wrapper/isntaller that will download and install Python if it isn't installed? I'm currently distributing a very simple wxWindows app bundled with Python and wxWindows (so the download is pretty huge). For customers that already have Python and wxWindows, it seems like a waste. I've now idea how many customers (if any) already do have Python. I suspect very few do, so it's sort of a moot point. -- Grant Edwards grante Yow! CHUBBY CHECKER just at had a CHICKEN SANDWICH in visi.com downtown DULUTH! From grante at visi.com Fri Apr 25 17:44:44 2003 From: grante at visi.com (Grant Edwards) Date: 25 Apr 2003 21:44:44 GMT Subject: GUI libs References: <3ea947e1$0$198$a1866201@newsreader.visi.com> Message-ID: <3ea9ac4c$0$179$a1866201@newsreader.visi.com> In article , Fredrik Lundh wrote: > Grant Edwards wrote: > >> Tkinter is indeed a pretty good place to start -- just try not >> to think about the fact that you're pulling in a Tcl interpreter >> also. ;) > > I do find it a bit worrying that every time I start a Python > program, it pulls in a C runtime library. Guess I have to do > something about that... But those C runtime library routines aren't redundant. they're providing functionality that Python doesn't implement. OTOH, having both Tcl and Python interpreters seems a bit redundant. I have used Scheme with Tk bindings, and that didn't use Tcl. The Scheme interpreter was bound directly to the Tk widgets. That results in several advantages to the application programmer, but disadvantages to the binding maintainer. I completely understand why the designers of Tkinter chose to do it the way they did -- and I probably would have done the same thing. -- Grant Edwards grante Yow! While I'm in at LEVITTOWN I thought I'd visi.com like to see the NUCLEAR FAMILY!! From afriere at yahoo.co.uk Tue Apr 15 03:32:26 2003 From: afriere at yahoo.co.uk (Asun Friere) Date: 15 Apr 2003 00:32:26 -0700 Subject: A python server References: <15f445fb.0304140751.170d410e@posting.google.com> Message-ID: <38ec68a6.0304142332.4a901e14@posting.google.com> santacruz at southern.edu (dansan) wrote in message news:<15f445fb.0304140751.170d410e at posting.google.com>... > Hello all! > > I have read and re-read the PY Sockets HOWTO, and I guess I'm still in > the dark about how to do some stuff. > > I'm trying to write a little server that will allow connections via > telnet-like clients to play a board game. Rather than using low-level sockets, you might want to have a look at 'telnetlib' in the standard library. From ramen at lackingtalent.com Tue Apr 1 10:54:50 2003 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 01 Apr 2003 15:54:50 -0000 Subject: Slicing in Python 2.3a2 References: Message-ID: In article , S?bastien Keim wrote: > I have some troubles to understand how work slicing in python 2.3. > In my examples, I will use the following list: > >>> A = range(10) > > ... > > But I don't understand the result for a subslice with a negative third > argument: > >>> A[1::-1] > [1, 0] > Intuitively, I expected to get: > >>> A[1:][::-1] > [9, 8, 7, 6, 5, 4, 3, 2, 1] You can get this with A[:0:-1]. > The numarray package has the same behavior, so I guess it's intentional. > >>> import numarray > >>> numarray.array(range(10))[1::-1] > array([1, 0]) > > Then what is the real semantic for this third argument? I think it makes sense if you think in terms of "start", "stop", and "step". The step amount represents the value that is added to the implicit counter with each iteration. I think that the confusion actually comes from the defaults for start and stop if they are not supplied. It seems from your example (and the [::-1] form) that the defaults for start and stop are swapped if the step is negative. HTH, Dave From rmunn at pobox.com Mon Apr 21 13:47:03 2003 From: rmunn at pobox.com (Robin Munn) Date: Mon, 21 Apr 2003 17:47:03 GMT Subject: "pythonic" References: Message-ID: soporte_cali wrote: > I am quite new to python so please forgive me if my question is too > newby. I am running a phyton exe file, linux red hat, it is an indexing > system that takes a flat file and index it. the py program once runned > is giving me this: > > ./index.py:57: SyntaxWarning: import * only allowed at module level > def createIndex(dbname,idtokenNum=1,keySize=10,idtokenChar=' '): > error: unknown library " " does not exit > Library nameoflibrary.py Does not exist > > so where should I place the name of this library? I mean is there any > special place to put it? libnames? well thanks in advance.. That doesn't look like any Python error message *I'm* familiar with... Is this the actual error message, or your own paraphrase? If it's the latter, plase copy and paste the actual error message. It would also be helpful if you could show the code that is causing the error. Not the entire file, of course, but maybe the line that's causing the error plus the surrounding code (say, the function that line appears in). -- Robin Munn http://www.rmunn.com/ PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838 From staschuk at telusplanet.net Tue Apr 29 12:18:42 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Tue, 29 Apr 2003 10:18:42 -0600 Subject: Question about accessing class-attributes. In-Reply-To: <7h3y91tiszi.fsf@pc150.maths.bris.ac.uk>; from mwh@python.net on Tue, Apr 29, 2003 at 08:54:54AM +0000 References: <2259b0e2.0304250413.4be8ee45@posting.google.com> <7h3bryulp3e.fsf@pc150.maths.bris.ac.uk> <7h37k9ilm5v.fsf@pc150.maths.bris.ac.uk> <2259b0e2.0304251030.30fd1f94@posting.google.com> <7h3y91tiszi.fsf@pc150.maths.bris.ac.uk> Message-ID: <20030429101842.A338@tibia.amotlpaa.bogus> Quoth Michael Hudson: > mis6 at pitt.edu (Michele Simionato) writes: [...] > > 2) why you say this makes classes unhashable ? > > Well, I thought it would. I was wrong: [...] > Then you get this kind of weirdness: > > />> class C(type): > |.. def __eq__(self, other): > |.. return 1 > \__ Can't the instances of this metaclass be made sensible for use in dicts simply with def __hash__(self): return hash(C) for example? (To ensure that if x == y then hash(x) == hash(y), as desired.) Or does this do weird things in a metaclass context? (Ignoring issues arising from the brokenness of the __eq__: class foo(object): __metaclass__ = C foo() == 3 # true! hash(foo()) == hash(3) # probably false and like cases.) -- Steven Taschuk staschuk at telusplanet.net "Its force is immeasurable. Even Computer cannot determine it." -- _Space: 1999_ episode "Black Sun" From andy at reportlab.com Thu Apr 17 16:16:26 2003 From: andy at reportlab.com (Andy Robinson) Date: Thu, 17 Apr 2003 21:16:26 +0100 Subject: Python and Schools References: Message-ID: >> Or, if my memory isn't failing me: >> >> sarr = Array("the", "quick", ... "dog") >> > >Indeed, though that's new to me (never used VB, just the scripting version). >Now let's create a dictionary-of-objects equivalent using the >DictionaryOfObjects() function ;-) I think VB actually started to borrow Python ideas and features a few years back. The Collection classes got a lot friendlier, foreach loops over collections.. Years ago someone here said that Python won't take over the world but its good ideas would end up in other languages... - Andy Robinson From max at alcyone.com Mon Apr 14 01:59:14 2003 From: max at alcyone.com (Erik Max Francis) Date: Sun, 13 Apr 2003 22:59:14 -0700 Subject: Using __repr__ or __str__ for own printable class? References: Message-ID: <3E9A4E32.F179FDDC@alcyone.com> "Greg Ewing (using news.cis.dfn.de)" wrote: > I don't find those guidelines particularly useful except > in fairly special cases. More generally, the rule of thumb > I use is that __str__ is for the "normal" output of the > program, whatever that might be, whereas __repr__ is for > debugging output. Same here. Usually I define __str__ to be something short and meaningful, and __repr__ to be something like def __repr__(self): return "<%s @ 0x%x (%s)>" % \ (self.__class__.__name__, id(self), str(self)) That way it helps to see things like: >>> Course(lowEarthOrbit, lowMarsOrbit).transfers() [, , ] -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Freedom is a road seldom travelled by the multitudes \__/ Public Enemy ZOE / http://www.alcyone.com/pyos/zoe/ A simple Python OpenGL rendering engine. From dino_levy at mindlessSPAM.com Sun Apr 20 19:19:57 2003 From: dino_levy at mindlessSPAM.com (Dino Levy) Date: Mon, 21 Apr 2003 01:19:57 +0200 Subject: Mail and text extraction Message-ID: I have the following problem: I'm trying to make a script which will connect to POP3 server, print number of mails, print their size and subject, and then will ask the user which mail should be downloaded... So far so good, but I have problem: I also want to implement the option for my script to search for a previously determined pattern and then download the text with the pattern. I know I sound weird and am not clearly explaining the problem, but this is a short example... You get a mail with a subject Monthly payment, and it's fairly large but all you want to do is to download ( or see ) whether you have been given a raise. The mail looks like this: Agnell company -Worker Payment Joe Doe 500$ Mary Smith 550$ Karen Bay 495$ -New Employee: Peter Maley some text... -Raises: some text And all you want to do is to connect to your POP3 server, and download the section called Raises ( for example, two or three lines after the title ), so all you want to do is to download those few lines containing your text... ( ONLY those lines, not the whole e-mail ) I know my explanation is lame and clumsy and my english is poor, but please help me if you understand what I'm talking about and if you have the solution... Thanks From exarkun at intarweb.us Sat Apr 5 13:21:22 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Sat, 5 Apr 2003 13:21:22 -0500 Subject: Why use a GUI framework? In-Reply-To: <1g5u8vc1k8t97jg8vsm2gi81sfnu7cm1hf@4ax.com> References: <1g5u8vc1k8t97jg8vsm2gi81sfnu7cm1hf@4ax.com> Message-ID: <20030405182122.GA23069@meson.dyndns.org> On Sat, Apr 05, 2003 at 07:47:05PM +0200, Jane Doe wrote: > Hi, > > I know a bit more about the multiple options available to > build a GUI-based application (Windows, in our case), but I haven't > found information on the point of using another tool since the > win32all extension is available to use the native Win32 widgets. > > Do wxWindows et al. just make it easier, or is it a must-use for > people who wish to write OS-independant Python applications? > > If win32all is good enough, does anybody have a good tutorial on using > this add-on to build GUIs? If portability to non-Windows platforms is not important to you, win32all is probably good enough. The other GUI toolkits make it -possible-, not easier, to write OS-independant Python applications. Jp -- A sad spectacle. If they be inhabited, what a scope for misery and folly. If they be not inhabited, what a waste of space. -- Thomas Carlyle, looking at the stars -- up 16 days, 14:00, 7 users, load average: 1.25, 1.31, 1.27 From robin at alldunn.com Tue Apr 15 20:00:35 2003 From: robin at alldunn.com (Robin Dunn) Date: Wed, 16 Apr 2003 00:00:35 GMT Subject: Using property in classic class may not work In-Reply-To: <3E9C99E9.9000201@eb2.net.au> References: <3E9C99E9.9000201@eb2.net.au> Message-ID: <3E9C9D1B.2000303@alldunn.com> I have it on my ToDo list for figuring out how what exactly the problem is (I have a general idea) and fixing it. Not sure when I'll get to it though, hopefully soon... --Robin Neil Hodgson wrote: > [With some editing to isolate the points] > > [Neil Hodgson] > The class in question is derived from a wxWindows class, so I can't > make it derive just from object. The "What's New in Python 2.2" > document only mentions property wrt new-style clases. > > [A. Lloyd Flanagan] > However, the last time I tried to subclass from both wxFrame and > object, wxPython freaked out (that's a technical term for "I don't > remember what happened, but boy, it sure didn't work"). > Not sure about the latest version of wxPython, though -- there's > binaries for python 2.3 out by now. I'll have to try it again.. > > [Alex Martelli] > If wxPython keeps freaking, you may have to give up on properties > if you HAVE to inherit its classes (can't just wrap with automatic > delegation) and go back to "good old" (yeah right) __setattr__. Or, > gently pressure wxPython's maintainers to have them move to > new-style classes... whatever aspects of old-style classes they > may be taking for granted at present, migrating to new-style can > hardly be a major job, in my experience. > > [Me again] > Robin may feel constrained to keep wxPython compatible with multiple > Python major versions. > Here is the "freaking out" with wxPython+wxGTK 2.4.0.7 on Python 2.2 > caused by adding 'object' as a second base class to the most derived > frame class, that is, the class that has the property: > > Traceback (most recent call last): > File "DemonTerm.py", line 1343, in ? > app = DemonTermApp(sys.argv) > File "DemonTerm.py", line 1290, in __init__ > wxApp.__init__(self, 0) > File > "/usr/local/ActivePython-2.2/lib/python2.2/site-packages/wxPython/wx.py", > line 1802, in __init__ > _wxStart(self.OnInit) > File "DemonTerm.py", line 1327, in OnInit > self.frame = DemonFrame(BasicScreenDefs) > File "DemonTerm.py", line 577, in __init__ > TerminalGUI.TerminalFrame.__init__(self, screenDefs) > File "TerminalGUI.py", line 762, in __init__ > style=wxDEFAULT_FRAME_STYLE | wxNO_FULL_REPAINT_ON_RESIZE) > File > "/usr/local/ActivePython-2.2/lib/python2.2/site-packages/wxPython/frames.py", > line 150, in __init__ > self._setOORInfo(self) > File > "/usr/local/ActivePython-2.2/lib/python2.2/site-packages/wxPython/windows.py", > line 60, in _setOORInfo > val = apply(windowsc.wxEvtHandler__setOORInfo,(self,) + _args, _kwargs) > TypeError: Type error in argument 1 of wxEvtHandler__setOORInfo. > Expected _wxEvtHandler_p. > > OOR is wxPythonese for 'Original Object Return' but I don't know what > that really means. > > Neil > > From sholden at holdenweb.com Sat Apr 19 09:52:57 2003 From: sholden at holdenweb.com (Steve Holden) Date: Sat, 19 Apr 2003 13:52:57 GMT Subject: Pair of prescription sunglasses left at PyCon sprint References: Message-ID: "Christopher Armstrong" wrote in message news:mailman.1050709532.4784.python-list at python.org... > I found a pair of prescription sunglasses on the table where the > Twisted gang was sprinting. If anyone can claim them, send me an > address to ship them to. Sorry for not posting about this earlier, I > had forgotten about them and they just turned up. > There's a lost property bit in the Wiki somewhere, maybe you should also add to that? -- -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/pwp/ From unix at unix.com Fri Apr 11 02:26:14 2003 From: unix at unix.com (Gilles) Date: 11 Apr 2003 01:26:14 -0500 Subject: pyserial newbie questions References: <8tfla.154$N5.27502@mencken.net.nih.gov> Message-ID: <110420030823304299%unix@unix.com> In article <8tfla.154$N5.27502 at mencken.net.nih.gov>, Mike wrote: Hello all, Fank Zheng sent me this sample via email, and it works great. import serial import time s = serial.Serial(300) #here u can set timeout command = '\x00'*20 s.write(command) #the return value of write(..) is the actual size written. time.sleep(0.01) s.write('HELLO') recv = s.read(5) #if u don't set timeout, here will stop until get 5 bytes from the serial port if recv == 'READY': #do something Thanks again Frank :) Gilles > "Gilles" wrote in message > news:gilles.celli-943DC4.10083810042003 at webmail.restena.lu... > > Hello folks, > > > > Since I am very new to Python I have the following question: > > > > I try to write a program in Python (on RHat 8.0 Linux) with the > > "pyserial" module which communicates to a device via RS232 serial cable. > > > > The program should do: > > > > 1. Set Com port to 300,n,8,1 > > 2. Send 20 NULL characters Chr(0) > > 3. Wait 10 ms ( may vary in your case) > > 4. Send a string "HELLO" > > 5. Wait to receive ?READY? string from device > > 6. If above string OK SEND ?START? > > > > I figured out how to set the port, send the 20 NULL characters :) > > > > But I have no idea how to "wait for 10ms", send the HELLO string and > > read the READY string... > > > > Anyone has a clue or source code sample ? > > > > Thanks a lot. > > > > Gilles > > I don't know if this is the answer you're looking for but you can use the > sleep(secs) function in the time module. > > > import time > > time.sleep(.01) # sleep 10 ms > ... > > > From mertz at gnosis.cx Mon Apr 28 12:13:40 2003 From: mertz at gnosis.cx (Lulu of the Lotus-Eaters) Date: Mon, 28 Apr 2003 12:13:40 -0400 Subject: More rants on a bad sort In-Reply-To: References: <698f09f8.0304262115.386c2571@posting.google.com> <3EAB6A14.707AD826@alcyone.com> <7ULqa.9804$3M4.264757@news1.tin.it> Message-ID: <0MVr+kKkXUES092yn@gnosis.cx> |> [u'x', 'x', chr(255)].sort() |> ['x', chr(255), u'x'].sort() |> [1j, '1', 1].sort() |> [1, 1j, '1'].sort() |I must admit I was surprised that 3 of these failed to sort, since I'd |guessed that you would have selected 2 that worked and 2 that failed. So my |question is, did one of the last two actually work on your system? It was a trick question in that respect too. But the problem is that I honestly do not even UNDERSTAND why .sort() does what it does here. If we start from the premise that some things are comparable, and other things are not, then we can observe that: >>> u'x' < 'x', 'x' < chr(255) (0, 1) But >>> u'x' < chr(255) Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII decoding error: ordinal not in range(128) The sorting algorithm winds up only performing allowed comparisons in: [u'x', 'x', chr(255)].sort() Well... OK. We have a similar story with complex numbers: >>> '1' < 1, 1j < '1' (0, 1) >>> 1 < 1j Traceback (most recent call last): File "", line 1, in ? TypeError: cannot compare complex numbers using <, <=, >, >= Given all that, is it POSSIBLE to construct a list containing a string, int, and complex, that will not crash on a sort? I don't know! I couldn't find one--and I THINK the relative order of complex and strings precludes it... but actually proving this one way or another is decidedly non-obvious. 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 pobrien at orbtech.com Sun Apr 6 21:53:41 2003 From: pobrien at orbtech.com (Patrick K. O'Brien) Date: 06 Apr 2003 20:53:41 -0500 Subject: Could Emacs be rewritten in Python? References: <3E9040CF.2040606@removethis.free.fr> <6ee58e07.0304061722.2472b3d0@posting.google.com> Message-ID: llothar at web.de (Lothar Scholz) writes: > > "comparable in power." The reason is that there is a ton of elisp > > code out there, including most of Emacs itself, that could be > > translated to work with PyAlaMode. My goal isn't to be able to > > convert in a completely automated fashion, but close enough to be > > attractive to both an elisp programmer and a Python programmer. > > Sorry, have you ever written a elisp program, something that is larger > then > 100 lines. I can't think about a way to provide this in python without > writting a lisp like interpreter. Remember that the scope of elisp > variables for example are not lexical. This is something very hard to > emulate in python. > I would really suggest to look at the structure of keyhandling, > keymaps and buffers. And then forget about lisp and design a good > python editor. No, the only elisp I've dealt with has been trivial changes to .emacs and similar files. I don't want to write a lisp-like interpreter. All I *really* want to support are the Emacs concepts, not the actual code, especially if there is no simple way to automatically translate elisp into Python. I've been assuming there is an advantage to making the PyAlaMode API conceptually similar to the Emacs API. Maybe there isn't and I'm giving the Emacs API more credit than it deserves. Is it enough to support the following: * default Emacs keybindings * ability to remap keybindings * multiple buffers and multiple windows * multiple modes * keyboard friendliness (no need for a mouse) * minibuffer-style control of environment If not, what's missing and what's the definition of a "good editor" written in Python? Should it allow customizations and extensions, like Emacs, but be a completely new and Pythonic API? -- Patrick K. O'Brien Orbtech http://www.orbtech.com/web/pobrien ----------------------------------------------- "Your source for Python programming expertise." ----------------------------------------------- From jacek.generowicz at cern.ch Thu Apr 17 11:16:05 2003 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Apr 2003 17:16:05 +0200 Subject: Why functional Python matters References: <3E9C9A91.8090209@removethis.free.fr> <3E9DE024.3020807@removethis.free.fr> <3E9EB3E9.1040208@removethis.free.fr> <87k7dt5m3j.fsf@interim.henrik-motakef.de> <1azna.115402$It5.22896@news2.central.cox.net> Message-ID: "Steve Holden" writes: > While Guido is known to regret the inclusion of lambda in Python But he regrets the inclusion of a crippled lambda, rather than the inclusion of support for anonymous functions (IIRC). From Patrick.Carabin at sciencesnaturelles.be Tue Apr 15 05:21:28 2003 From: Patrick.Carabin at sciencesnaturelles.be (Patrick Carabin) Date: Tue, 15 Apr 2003 11:21:28 +0200 Subject: files: direct access - NOT sequential Message-ID: <03041511212800.01079@pc20_118> i search a means to get " direct access " inside files, eg mixing read & write operaions for the same file example: given a file with contents : "qwerty" , positionning on the "w", and writing a "N" , so the file becomes "qNerty" How can i achieve this in Python ? TIA, Patrick Carabin Patrick.Carabin at sciencesnaturelles.be Patrick.Carabin at NatuurWetenschappen.be . Institut Royal des Sciences Naturelles de Belgique http://www.SciencesNaturelles.be/ Koninklijk Belgisch Instituut voor Natuurwetenschappen http://www.NatuurWetenschappen.be/ ?Le bonheur n'est pas au bout du chemin, le bonheur est le chemin.? ?Het geluk is niet op het einde van de weg, het geluk is de weg.? Dala? Lama. From max at alcyone.com Sat Apr 12 04:55:47 2003 From: max at alcyone.com (Erik Max Francis) Date: Sat, 12 Apr 2003 01:55:47 -0700 Subject: intern'ed strings and deepcopy() References: <3E972D34.6B829FCC@alcyone.com> <3E97584A.5E7FD112@alcyone.com> <3E97D324.8000009@v.loewis.de> Message-ID: <3E97D493.659A567B@alcyone.com> "Martin v. L?wis" wrote: > When Eric Max said "its identity is unimportant", he really > meant "it's unimportant whether they are interned, and their > identity is preserved in deepcopy" :-) See, a little money under the table never hurts. Now I don't even have to defend myself :-). -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ Who's not sat tense before his own heart's curtain? \__/ Rainer Maria Rilke Bosskey.net: Unreal Tournament 2003 / http://www.bosskey.net/ut2k3/ A personal guide to Unreal Tournament 2003. From drew at astro.pas.rochester.edu Thu Apr 3 22:17:19 2003 From: drew at astro.pas.rochester.edu (Drew Moore) Date: 3 Apr 2003 19:17:19 -0800 Subject: Overloadable Assignment PEP References: <9383481e.0304012011.78f05548@posting.google.com> <3e8c083b$0$10386$edfadb0f@dread11.news.tele.dk> <9383481e.0304030705.524cf0fa@posting.google.com> Message-ID: <9383481e.0304031917.1d0100bf@posting.google.com> Jp Calderone wrote in message news:... > > class Conductor(object): > def set_voltage(self, value): > # Twiddle whatever needs to be twiddled > def get_voltage(self): > # Lookup whatever the voltage is > return it > voltage = property(get_voltage, set_voltage) > > c = Conductor() > c.voltage = 3 > > This is more along the lines of what you'd really do, anyway, right? > After all, if "voltage" is simply a global, then your program or library > will be forever tied to controlling a single item across which an emf can > be put. Not very scalable, right? > > Jp > > -- > Lowery's Law: > If it jams -- force it. If it breaks, it needed replacing anyway. Well, not exactly what I had in mind.. how bout this? class dacvoltage() : def __init__(self,dacnum,volt=0.0,dacfunc=maindac) : self.dacnum = dacnum self.volt = volt self.writedac=dacfunc self.writedac(self.dacnum,self.volt) def __assign__(self,other) : # todo: add code to check type of other.. # if it is another dacvoltage object, # return other, not self... # this will rebind the name! try: self.writedac(self.dacnum,other) # might barf. self.volt=other # didn't barf? remember what was assigned. except: # complain bitterly here if writedac barfs. return self # retain identity.. # instantiate some dac voltage objects for the first time.. # (or re-instantiate old ones, if above todo gets done..) vdduc = dacvoltage(1, -4.0) vreset = dacvoltage(2, -3.0) vbias = dacvoltage(0,dacfunc=auxdac) # bias dac uses special converter.. vbias = 2.5 # etc etc... # do some stuff at these voltages.. # modify the voltages, in a very simple, readable syntax. vdduc = -3.8 # try a reduced supply vreset = -3.2 # and increased reset drive... vbias = 2.3 # and decreas the bias a little.. # do some more stuff with new voltages, etc etc... Drew From exarkun at intarweb.us Thu Apr 17 09:33:16 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 17 Apr 2003 09:33:16 -0400 Subject: inheriting variables In-Reply-To: References: Message-ID: <20030417133316.GB25373@meson.dyndns.org> On Thu, Apr 17, 2003 at 10:34:08AM +0000, Haran Shivanan wrote: > This seems like a fairly straight forward thing but I'm not sure about how > to implement it. > I have a base class from which I'm deriving several new classes: > class A: > mem_a=0 > mem_b=1 > class B(A):pass > > I want B to inherit mem_a and mem_b from A without my having to explicit do > something like: > > self.mem_a = 0 > > in the constructor for class B. class A: a = 0 b = 1 class B(A): pass b = B() print b.a, b.b Isn't this the behavior you desire? If not, could you clarify your question? 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 -- up 28 days, 9:02, 5 users, load average: 0.04, 0.03, 0.00 From paul at boddie.net Mon Apr 14 06:21:46 2003 From: paul at boddie.net (Paul Boddie) Date: 14 Apr 2003 03:21:46 -0700 Subject: Pythonic way of web-programming References: <%5Oja.10776$7w2.9784@nwrddc01.gnilink.net> Message-ID: <23891c90.0304140221.20e9e7fb@posting.google.com> Ian Bicking wrote in message news:... > [WebKit on Twisted] > Using the Twisted CGI code, it would be a quick change to make it > dispatch to a thread instead of a process (as with CGI). One of the main concerns about making Twisted the "Pythonic standard" is that people who demand a non-threaded, non-CGI handler model for scalability reasons (and this did come up recently on comp.lang.python, so it is a valid concern) are very likely to fall outside the resulting audience. Unfortunately, especially given the success of mod_python and other process-forking frameworks, that could amount to a lot of people. > I'm still thinking about the strategy around it, which is why I haven't > actually tried implementing it. As an experiment it's not that > interesting to me, but maybe it could be more than that. Well, I've been experimenting with implementing a small framework on top of WebKit and mod_python (with Zope being another likely candidate), and it has to be said that some frameworks share enough similarity and do provide enough flexibility to make "super-frameworks" possible. Moreover, with developments like POSH... http://poshmodule.sourceforge.net ...it might even be possible for such "super-frameworks" to paper over the fundamental but desirable differences between the underlying frameworks. For example, some people might want a threaded model, whilst others might prefer a process-forking model together with similarly convenient data sharing semantics. As for the issue of standard APIs, I believe that such APIs really only serve a useful purpose as being something to build on that is widely agreed upon, recognised and stable; they don't necessarily serve the purpose of being something developers really want to write to directly. For example, Java Servlets have arguably served as a foundation for more high-level toolkits, whereas writing directly to the Servlet API is something that the most productive developers stopped doing years ago. Paul P.S. The Web frameworks shootout paper is most informative and serves as an interesting guide as to the most accessible frameworks that could be subverted (or "leveraged" depending on your mindset) by such "super-frameworks". From dave at pythonapocrypha.com Fri Apr 18 00:37:44 2003 From: dave at pythonapocrypha.com (Dave Brueck) Date: Thu, 17 Apr 2003 21:37:44 -0700 (PDT) Subject: Mem "leak" w/ long-running network apps? Message-ID: I've spent the last few weeks trying to track down a memory leak in a long-running network app (an HTTP proxy for large-ish objects) and am trying to find out if anyone else has encountered something similar. I narrowed the problem down to the receiving side of the proxy, and today in socketmodule.c I noticed that when you call sock.recv(n) a string of size n is created and then resized after the recv to the actual size of the data received. There's nothing wrong with that in and of itself, but when I replaced it with the function below to do receives the ever-growing memory problem went away (so now instead of calling sock.recv(amnt) I do a specialmodule.recv(sock, amnt)). The function merely uses a static buffer and then creates a Python string of just the size needed - the resize is what got eliminated. I initially encountered the problem on Python 2.1.3 but then moved to 2.2.2 to use the gc module enhancements. My questions are: (1) has anybody else run into a similar problem before? This may not be very common because the app is a little unusual in that it's long-running, handles hundreds of concurrent connections, each connection is usually for a large (tens to hundreds of megabytes) object, the data is all proxied rather than being served off disk or generated by the app, and both the upstream and downstream connections are generally fast (aggregate throughput for the server is usually in the 100-200 Mbps range for a P3 900. (2) Any ideas on why using the normal socket.recv resulted in ever-growing memory use? I've spent ages using the gc module and other tools to track down objects that should have been freed, cyclic references, etc., and don't see any problems there and I don't think the memory is really being leaked (in the C sense). Could it be a heavily fragmented heap or something like that? I'd notice that after my tests ran for a long time I'd stop them and memory usage would drop down after awhile by a few megabytes, and upon starting my tests again (without restarting my app) mem usage would drop down some more but not all the way down and then it would gradually grow again to a new high-water mark, so that overnight my process had hundreds of MB of RAM. With my recv-replacement I'm holding steady at about 30 MB, which is normal. (3) Does anyone see any glaring errors in my function below? Seems to work well enough. :) Anyway, I don't think there's a bug in Python, and my function is certainly not patch-worthy because it really works just for my use, and now that my problem is gone it's mostly out of curiosity that I'm trying to better understand why my problem is gone, but I'd appreciate any insight or hints. Thanks, Dave Here's the function. I can get away with using a single large buffer for all my receives because while the server is a mixture of threading and poll-based, all the I/O happens sequentially in one thread against sockets that are known to be ready for I/O. #define MAX_RECV_SIZE 1048576 static char RECV_BUFF[MAX_RECV_SIZE]; static PyObject * recv_wrapper(PyObject *self, PyObject *args) { PyObject *py_sock; PyObject *py_str; int sock; /* Output socket */ int len, n; if (!PyArg_ParseTuple(args, "Oi:recv", &py_sock, &len)) return NULL; if (len < 0) { PyErr_SetString(PyExc_ValueError, "negative buffersize in recv"); return NULL; } if (len > MAX_RECV_SIZE-1) { PyErr_SetString(PyExc_ValueError, "buffersize too large in recv"); return NULL; } sock = PyObject_AsFileDescriptor(py_sock); Py_BEGIN_ALLOW_THREADS; n = recv(sock, RECV_BUFF, len, 0); Py_END_ALLOW_THREADS; if (n == -1) return PyErr_SetFromErrno(RecvError); py_str = PyString_FromStringAndSize(RECV_BUFF, n); if (py_str == NULL) return NULL; return py_str; } From blunck at gst.com Wed Apr 16 10:54:06 2003 From: blunck at gst.com (Christopher Blunck) Date: Wed, 16 Apr 2003 10:54:06 -0400 Subject: How many of you are Extreme Programmers? In-Reply-To: References: Message-ID: <20030416145406.GA19919@homer.gst.com> On Wed, Apr 16, 2003 at 09:36:14AM -0500, sismex01 at hebmex.com wrote: > Many of us have used XP techniques without actually knowing > that our methodology was labelled as "XP", it comes natural > in the scope of our tools and goals. Absolutely! Which is why I believe that many of us in the Python community follow many of the principals of "XP" without knowing it. > I don't know; "OOP", "XP", "Structured Programming", etc.. are > all monickers, buzzwords, fads, which come and go; they come > into existance when some mass-market-oriented technical book > writer says "Hey, this programmer is successful, let's see > what he's doing"; once done, the writer creates some catchy > name for this guy's techniques, and sells his book. > > I really dislike market speak, as you can tell. :-) Me too. What's discouraging is that it often takes books, buzzwords, and fads to get the attention of higher-ups. Developing software is not all that difficult - it's always so confusing why people make software development more complex than it actually is. -c -- 10:50am up 20:02, 1 user, load average: 0.87, 0.91, 0.91 From jkn at nicorp.f9.co.uk Wed Apr 2 09:17:23 2003 From: jkn at nicorp.f9.co.uk (Jon Nicoll) Date: 2 Apr 2003 06:17:23 -0800 Subject: slurping yahoogroups postings with Python, like yahoo2mbox? Message-ID: <8351bb33.0304020617.61007d5f@posting.google.com> hi there Does anyone know of a python equivalent (or near-equivalent, that I can fiddle with) of the Perl module yahoo2mbox? This 'slurps' Yahoogroups postings into an mbox format. Thanks for any pointers Jon N From grante at visi.com Wed Apr 30 10:54:24 2003 From: grante at visi.com (Grant Edwards) Date: 30 Apr 2003 14:54:24 GMT Subject: How to call built in function 'open' from inside object that has 'open' method? References: Message-ID: <3eafe3a0$0$184$a1866201@newsreader.visi.com> In article , Aahz wrote: >>> More details on reasons. I have met this problem trying to write a >>> simple script use ActiveScripting inside IE. I am trying "file = >>> open(...) but because context window object has 'open' method that >>> just opens window it is called first. >> >>Unless you're typing "file = self.open(...)", the class you're in has >>nothing to do with it. > > Not quite true; what happens with > > class C: > def open(self, name): > f = open(name) When I do it, it calls the builtin open(). What happens when you do it? ----------------------testit.py---------------------- class C: def __init__(self): print "C.init()" print open print self.open def open(self,fname): print "C.open(%s)" % fname print open print self.open return open(fname) c = C() f = c.open("foo") print f --------------------------------------------- $ python2 testit.py C.init() > C.open(foo) > -- Grant Edwards grante Yow! What GOOD is a at CARDBOARD suitcase ANYWAY? visi.com From elechak at bigfoot.com Mon Apr 21 22:05:38 2003 From: elechak at bigfoot.com (Erik Lechak) Date: 21 Apr 2003 19:05:38 -0700 Subject: methods and vars in zope objects Message-ID: Hello all, I have been beating my head against zope for a few days now. I am writing python scripts, and I can't seem to find what methods and member variables go along with the various zope objects. I would like to be able to use dir(obj), obj.__class__ or type(obj) like I do when I am using python everywhere else. But It won't let me. The documentation is lengthy; I read throught it, and I must have missed it. I am looking at the code now ... but it's just raising my blood pressure. Is there a simple script, document, manual, or button that will list the methods and member vars available to a certain object? Something like dir(). Thanks, Erik Lechak From max at alcyone.com Fri Apr 11 20:05:57 2003 From: max at alcyone.com (Erik Max Francis) Date: Fri, 11 Apr 2003 17:05:57 -0700 Subject: module for doing unix "find"-like things? References: <7LDla.1483$Pq2.135830754@newssvr14.news.prodigy.com> Message-ID: <3E975865.3D85A4E7@alcyone.com> "A. Lloyd Flanagan" wrote: > If such a module doesn't exist I might write one. A friendlier (more > pythonic?) interface to os.stat() would be an obvious starting point. The added bonus is that it wouldn't be that hard. Definitely sounds like something worth doing. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ It is human nature to think wisely and act foolishly. \__/ Anatole France Bosskey.net: Quake III Arena / http://www.bosskey.net/q3a/ A personal guide to Quake III Arena. From beliavsky at aol.com Tue Apr 15 08:58:30 2003 From: beliavsky at aol.com (beliavsky at aol.com) Date: 15 Apr 2003 05:58:30 -0700 Subject: book on Python for Fortran programmers Message-ID: <3064b51d.0304150458.595afc30@posting.google.com> Python has been suggested by several posters to comp.lang.fortran as a scripting language worth learning. What are some good book(s) and web site(s) to get an experienced Fortran 95 programmer started in Python? From mads at troest.NEVERMORE.dk Tue Apr 8 14:08:58 2003 From: mads at troest.NEVERMORE.dk (Mads Orbesen Troest) Date: Tue, 8 Apr 2003 20:08:58 +0200 Subject: Loading a class the name of which is only known runtime References: <13n0q1sc6o6oh$.hfa48a72df4n.dlg@40tude.net> <3BDka.4759$Du.16741@newsc.telia.net> Message-ID: <1ruvtw54py90d.1sob8ay5wclmb.dlg@40tude.net> On Tue, 08 Apr 2003 17:24:15 GMT, Tim Gahnstr?m /Bladerman wrote: Hi Tim, and thanks for your response. > If this is what ou are asking for it is certanly possible. > > if test: > import modul1 > a=class1() Actually, what I am looking for is more alone the lines of: moduleToImport = "SomeModule" # <- Retrieved as CGI argument classToInstantiate = "SomeClass" # <- Retrieved as CGI argument import moduleToImport someInstance = classToInstantiate() Of course, the above does not work. But is there any way to achieve what I outline here? Regards, /\/\\ads Orbesen Troest From peter at engcorp.com Mon Apr 28 23:17:49 2003 From: peter at engcorp.com (Peter Hansen) Date: Mon, 28 Apr 2003 23:17:49 -0400 Subject: Python code -> to C code References: Message-ID: <3EADEEDD.7B740C6C@engcorp.com> Garrison Tsang wrote: > > I just signed up and this is my first post. > > Knowing nothing about Python at the moment, I need to convert a python-code > into compatible c-code. I recall that were some program/utility that does > the transformation for you. I doubt it. Maybe it would be helpful if you explained why you think you need to convert the Python program into C? Does it not run fast enough? Does it have to interface with something else that is in C? Does it have to run on a platform on which Python is not supported? If you haven't got a really good reason, you might be better off leaving the code in Python. If you think it's an issue that you don't know how to program in Python yet, believe me, you'll become more proficient, faster, with Python than you are with C in a very short time. -Peter From ark at research.att.com Fri Apr 4 16:33:34 2003 From: ark at research.att.com (Andrew Koenig) Date: Fri, 4 Apr 2003 16:33:34 -0500 (EST) Subject: output buffering--am I missing something obvious? In-Reply-To: <16013.63756.223973.484125@montanaro.dyndns.org> (message from Skip Montanaro on Fri, 4 Apr 2003 15:28:44 -0600) References: <16013.63756.223973.484125@montanaro.dyndns.org> Message-ID: <200304042133.h34LXYt02986@europa.research.att.com> Skip> I tried using 1.5.2 (!) on a Solaris 8 machine (it's what comes on the Skip> Software Companion CD for Sol8) I get the same results: >>>> import sys >>>> sys.stdout.write("foo") foo> sys.stdout.flush() >>>> sys.stdout.write("bar\n") Skip> bar Skip> Bit rot somewhere? It certainly shouldn't do that. In a follow-up message, I suggested that interactive input tossed unwritten output. I'm now not so sure it's that simple, because if I do this: >>> sys.stdout.write("foooooooooooooooooo"); sys.stdout.flush() it appears to write the argument string *and then to backspace over it*, erasing the characters from view. Very odd. From mads at troest.NEVERMORE.dk Tue Apr 8 15:11:31 2003 From: mads at troest.NEVERMORE.dk (Mads Orbesen Troest) Date: Tue, 8 Apr 2003 21:11:31 +0200 Subject: Loading a class the name of which is only known runtime References: <13n0q1sc6o6oh$.hfa48a72df4n.dlg@40tude.net> <3BDka.4759$Du.16741@newsc.telia.net> <1ruvtw54py90d.1sob8ay5wclmb.dlg@40tude.net> Message-ID: On Tue, 8 Apr 2003 21:01:56 +0200, Bjarke Dahl Ebert wrote: Hi Bjarke; > Have a look at the builtin function __import__. > themodule = __import__(themodulename) > theclass = getattr(themodule, theclassname) > a = theclass() Thanks for your suggestion, this seems like just what I am after! > Of course, there are all kinds of security issues with doing __import__ and > getattr like this in a CGI script... Well, you're right of course, but I actually don't plan to allow arbitrary imports from the CGI parameter (although I know my post to Tim suggested that). What I am doing is having a central python script registered as handler for some file extensions in Apache, and I have pages implemented as python classes. What I want to do is for the central python handler to "dispatch" the page (class) given as argument. Now, if I restrict all these page objects to reside in a fixed package, and only allow for import of that package, I should think that the security issue (arbitraty module import) goes away, as only page-objects inside the page-package can be specified. At any rate, thank you very much for your feedback! Regards, /\/\\ads Orbesen Troest From news at snakefarm.org Tue Apr 8 12:30:37 2003 From: news at snakefarm.org (Carsten Gaebler) Date: 8 Apr 2003 16:30:37 GMT Subject: fdopen() question References: Message-ID: Carsten Gaebler wrote: > > Traceback (most recent call last): > File "./listener.py", line 27, in ? > f = os.fdopen(fd, 'r') > OSError: [Errno 9] Bad file descriptor > > What am I missing? > Seems I have to open the file in 'w+' mode to make it work. cg. From exarkun at intarweb.us Thu Apr 10 17:58:29 2003 From: exarkun at intarweb.us (Jp Calderone) Date: Thu, 10 Apr 2003 17:58:29 -0400 Subject: Python compared toJava In-Reply-To: <20030410172428.GA4764@isis.gerrietts.net> References: <20030410172428.GA4764@isis.gerrietts.net> Message-ID: <20030410215829.GA24402@meson.dyndns.org> On Thu, Apr 10, 2003 at 10:24:28AM -0700, Geoff Gerrietts wrote: > Quoting Blaktyger (blaktyger at hotmail.com): > > Hi! > > > > I recently read that the Python interpreter is like the Java Virtual Machine. > > Is that true? > > It's hard to tell exactly what you mean by this, but since you seem to > have received an unusually high proportion of flip or catty responses, > I'll try to reply. > > A Java program runs inside the context of the JVM. A Python program > runs inside the context of the Python interpreter. In this way they > are similar: the actual process observed in the operating system's > process table will be the JVM or interpreter, not the program itself. Runtime context is a property of exactly that - the runtime. You're describing CPython, it seems, which, while the canonical Python runtime, is not the only Python runtime (given reasonable bounds for what one considers "Python"). See Jython, for example, where the answered to the OP's question would be "No, it is not *like* the Java Virtual Machine, it *is* the Java Virtual Machine". Consider also a future in which a smart person has written a native compiler. The language can remain the same while the runtime environment changes. Don't confuse properties of one with properties of the other. > [snip - more good information about CPython] Jp -- Examinations are formidable even to the best prepared, for even the greatest fool may ask more the the wisest man can answer. -- C.C. Colton -- up 21 days, 17:01, 8 users, load average: 2.05, 2.10, 2.07 From gh at ghaering.de Mon Apr 28 22:40:06 2003 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 29 Apr 2003 04:40:06 +0200 Subject: POD vs. reST for standalone writing? In-Reply-To: <7gd6j6kpq0.fsf@pikespeak.metacarta.com> References: <7gd6j6kpq0.fsf@pikespeak.metacarta.com> Message-ID: <3EADE606.5080209@ghaering.de> eichin at metacarta.com wrote: > So, after a recent bad experience with LyX and version skew, I was > looking at alternatives for software end-user and administrator > documentation. The constraints are pretty simple: > > * produce good html and PDF > ** via linux tools, and highly preferably free ones > * be editable on multiple platforms > ** linux first, but also, osx, windows > * support "literal computer output" and screen shot > [...] I'd give OpenOffice a try. I haven't tried the HTML export much. PDF export exists in the 1.1 beta. -- Gerhard From aleax at aleax.it Wed Apr 16 06:24:13 2003 From: aleax at aleax.it (Alex Martelli) Date: Wed, 16 Apr 2003 10:24:13 GMT Subject: encapsulation checking features References: <3e9b1298@cs.colorado.edu> <3e9ca7a5@cs.colorado.edu> Message-ID: Eric Scharff wrote: > Thanks for the reference to PyChecker, I'll have to check it out. > > I've not read enough python code to know how people traditionally treat > "instance variables that ought to be public" and "instance variables that > ought to be private" (other than prepending underscores, which I never > liked). Whether you like it or not, it *IS* exactly the Pythonic approach -- if you don't prepend an underscore to the name, you're conventionally saying that name IS part of the public interface to the module or class -- how it's IMPLEMENTED in the future is up to you, but client code is entitled to rely on the existence of SOME implementation. >> But I really don't see the problem here. If you want myVar.x to >> call an accessor, you make x into a property of myVar's class, >> period. Absolutely no need to design trivial do-nothing accessors >> either -- you can perfectly well have all client code access all >> instance variables you want, and if and then such "variables" >> need to be "computed on the fly" or have special effects when >> set, then you make them into properties, hey presto. > > I come from a Smalltalk background, which implicitly treats all direct > variable references as private to a class, requiring do-nothing accessors. > The advantage of these in Smalltalk is that I find it makes refactoring > easier - you can ask Smalltalk to tell you everywhere where the "myVar:" > setter is called. I could grep all of my python code for ".myVar =" but > that technique is slightly less accurate. Python is full of features that will make it nearly impossible (not just "slightly less accurate") to statically identify "all places where X is performed". For example, consider identifying "all places where function F is called" (no matter whether it's a method, etc). Grepping for "F(" isn't just "slightly less accurate", it's simply broken, because it will miss all the occurrences of e.g. mylist.append(F) in some place in the code with some other places then having e.g mylist[chooser()]() If your main purpose in life is easily and statically finding "all places where X is performed", then Python is one of the worst languages you could possibly choose -- most aspects of its power, such as "everything is first-class", dynamism, etc, etc militate _against_ allowing easy and accurate static analysis. Even if one was willing to bear the burden of zillion of silly empty deuced boilerplate accessors everywhere (which I wouldn't be: the fact that Python lets me do without boilerplate is one of the crucial ways it enhances my productivity), Python STILL wouldn't let you satisfy your heart's desire in this. E.g. even if you did use bedraggled setMyVar and getMyVar semantically-redundant accessors everywhere, STILL in order to easily find all calls to them you'd have to impose LOTS more limitations and discipline on client-code -- no sticking such methods in lists and dicts, no passing boundmethods as callback arguments to other components, and so on, and so forth. I don't think that trying to code Smalltalk in Python is a winning idea, in general -- any more than trying to code Fortran in C, or any other such combination. "If you want Smalltalk, you know where to find it", to paraphrase Ritchie [some claim it's a legend that Ritchie ever said this, but the concept is surely germane;-)]. If you find that your overall productivity gets _damaged_ by using Python Pythonically (for example because you so strongly dislike some of Python's rules and conventions -- such as the leading-underscore idea -- that you refuse to use them, or spend your time and energy loathing what you're coding rather than coding it;-), then it's quite possible that you should instead try Ruby, or Smalltalk variants (Squeak?), or other languages yet. Personally, I think MOST programmers will easily be able to adapt, but I've seen some counterexamples where somebody was *SO* utterly attached to idioms and approaches of some other language (Perl being the one I observed most often) that, no matter what, they kept "trying to code Perl [or other X] in Python" and ended up with a net loss in terms of productivity *AND FUN* (I think it's important to have FUN programming -- if you spend your time and energy *fighting* your tools because you hate the way they work, it's unlikely that you're having fun, unless, perhaps you have a peculiarly pugnacious personality...;-). >>> These are great features to have, but it'd be nice to have warnings to >>> discourage their use at times. > >> I can see that for the "ensure all instance variables exist at >> the end of __init__". I can't see that, given the existence of >> properties, for "no access to instance attributes from outside >> of methods". Perhaps you can clarify what advantage the latter >> would provide, that properties just can't...? > > Here's an example: I implemented a simulation of something using python > objects that represent objects in the simulation. In my rapid > prototyping, > the objects had two "aspects", the simulation and the visualization. > Every object had a tkItem instance variable that the object used to > configure > using Tkinter. Now, I want to create an easy way to enable and disable > the > views, or have more flexible views. Turning off the visualization means > finding all the references to tkItems and changing their structure. > > Yes, it was badly written to start, but it made sense at the time. :) Now > I want to get as much built-in help for refactoring as possible. I'm not sure I entirely follow -- you're talking about restructuring the CLIENT code of your simulation? Where said client code is entirely under your control? You just can't do it by static analysis, not reliably for all usage patterns that client-code may have used -- but if the client code is entirely under your control, why wouldn't just grepping for the attributename you need to refactor around be entirely satisfactory? If you've used peculiar ways of access, such as getattr with runtime-computer string expressions, you'll need a bit more work, of course, but how do you think any static analysis tool might help you with those...? Alex From ckea25d02 at sneakemail.com Wed Apr 2 18:12:10 2003 From: ckea25d02 at sneakemail.com (Greg Ewing (using news.cis.dfn.de)) Date: Thu, 03 Apr 2003 11:12:10 +1200 Subject: Comments In-Reply-To: References: <435d40e0.0304010014.503f9f8f@posting.google.com> <435d40e0.0304011457.56e32bd0@posting.google.com> <435d40e0.0304021052.736293b3@posting.google.com> Message-ID: Carsten Gaebler wrote: > But multi-line strings are evil, too. At least when they occur in an > indented block and leading whitespace is not allowed in the string > your're building Last time I pondered this issue, I decided that the correct way to fix this would be to have a statement like string my_string: | The string can contain any characters and |have multiple lines and leading whitespace, |and its indentation level is made clear by |the leading | characters. Teaching the tokenizer to understand this could be an interesting exercise, however... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From staschuk at telusplanet.net Mon Apr 7 23:05:31 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Mon, 7 Apr 2003 21:05:31 -0600 Subject: how to test when correct output is "random"? In-Reply-To: ; from ckea25d02@sneakemail.com on Mon, Apr 07, 2003 at 02:57:40PM +1200 References: <20030404215312.GE7895@unpythonic.net> Message-ID: <20030407210531.A4539@tibia.amotlpaa.bogus> Quoth Greg Ewing (using news.cis.dfn.de): > Steven Taschuk wrote: > > Consider two implementations of this function: > > def permute(seq): > > """Returns a copy of seq, randomly permuted.""" > > # ... > > In that kind of situation, what you should probably > be checking is not that a particular permutation is > produced, but just that the output is *some* permutation > of the input. Indeed. I think I mentioned this idea under the heading "sanity checks" later in my post. I introduced permute() (which is not the OP's example, note) to illustrate why I don't like the idea of mocking the PRNG and testing for specific output. > You may also want to call it a few times and check > that it returns a different permutation each time. Though note that such a test can produce false negatives. [...] > If you're worried that the output might pass those > tests but still not be random enough, then you're > into statistical testing, as Mr. Tasch suggested. Am I Mr. Tasch? If so, whose post do you think you're quoting above and, I infer, responding to? I am puzzled. -- Steven Taschuk staschuk at telusplanet.net "[T]rue greatness is when your name is like ampere, watt, and fourier -- when it's spelled with a lower case letter." -- R.W. Hamming From max at alcyone.com Tue Apr 22 18:27:34 2003 From: max at alcyone.com (Erik Max Francis) Date: Tue, 22 Apr 2003 15:27:34 -0700 Subject: True/False References: <3EA5B173.9420324C@alcyone.com> Message-ID: <3EA5C1D6.A0F30D9A@alcyone.com> Skip Montanaro wrote: > This is why you should avoid version dependencies in your code > wherever > possible. ;-) (Not casting aspersions toward Erik or David. It's just > that > you're bound to make mistakes with this sort of minutiae.) Indeed. This is why I, too, use and recommended the old try: ... except NameError: ... mechanism. -- Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/ __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE / \ There are defeats more triumphant than victories. \__/ Montaigne Discord / http://www.alcyone.com/pyos/discord/ Convert dates from Gregorian to Discordian. From jkraska at san.rr.com Sat Apr 12 22:30:20 2003 From: jkraska at san.rr.com (Courageous) Date: Sun, 13 Apr 2003 02:30:20 GMT Subject: exceptions == errors? References: Message-ID: <2tih9vgrb1qcmaum842qjmc2ocgkfq87ri@4ax.com> >> And, of course, "catch" is spelled "except" in Python :-) > >One of the very, VERY few places where I'd prefer the C++ choice I would have, too. Water under the bridge. Perhaps sometime between now and the next Hundred Years Language, someone will "fix" it. :-) C// From puccio_13 at yahoo.it Wed Apr 16 10:37:02 2003 From: puccio_13 at yahoo.it (Alessio Pace) Date: Wed, 16 Apr 2003 16:37:02 +0200 Subject: reading Unix mailbox References: Message-ID: Skip Montanaro wrote: > Alessio> I am using Python2.3 alpha and I thought there was something > Alessio> updated to iterate over the messages of a mailbox in mbox > Alessio> format, but the next() method still return a deprecated > RFC822 Alessio> message object reference, am I wrong? Is there a way > to read Alessio> mailboxes in mbox format but iterating over > MIMEMessages? > > Try: > > from spambayes import mboxutils > mbox = mboxutils.getmbox("somefile") > for msg in mbox: > do_stuff(msg) > > Skip But that requires to have spambayes, doesn't it? -- bye Alessio Pace From evan at 4-am.com Wed Apr 16 23:06:58 2003 From: evan at 4-am.com (Evan Simpson) Date: Wed, 16 Apr 2003 22:06:58 -0500 Subject: do python's nifty indentation rules spell the death of one-liners? In-Reply-To: <1050544015.99640.1@iris.uk.clara.net> References: <87he90b8rp.fsf@jidanni.org> <1050544015.99640.1@iris.uk.clara.net> Message-ID: Garry Knight wrote: > Maybe I didn't completely understand what the OP meant, but this isn't a > one-liner. It's a five-liner. python -c """exec('''print 2$$for i in (1,4):$$ print i$$'''.replace('$$','\n'))""" Yech, evan @ 4-am From staschuk at telusplanet.net Thu Apr 17 15:31:10 2003 From: staschuk at telusplanet.net (Steven Taschuk) Date: Thu, 17 Apr 2003 13:31:10 -0600 Subject: Stackless 3.0 alpha 1 at blinding speed In-Reply-To: <3E9E3040.5040409@tismer.com>; from tismer@tismer.com on Thu, Apr 17, 2003 at 06:40:32AM +0200 References: <3E9E3040.5040409@tismer.com> Message-ID: <20030417133110.F7968@tibia.amotlpaa.bogus> Quoth Christian Tismer: [...] > At the same time, I dismissed all of my Stackless 1.0 code, which was > continuation-based, an absolute no-no in Guido's eyes. [...] Is there a short way to say why Guido didn't want continuations? Or should I go digging in the archives? -- Steven Taschuk staschuk at telusplanet.net Receive them ignorant; dispatch them confused. (Weschler's Teaching Motto) From andrew at acooke.org Mon Apr 28 17:15:06 2003 From: andrew at acooke.org (andrew cooke) Date: Mon, 28 Apr 2003 17:15:06 -0400 (CLT) Subject: Slice confusion : a[n:p] is a list exclude the last element p (thus spoke Dijkstra) In-Reply-To: References: Message-ID: <3925.200.27.214.82.1051564506.squirrel@127.0.0.1> Andrew Koenig said: > Incidentally, Dijkstra's argument about ``natural numbers'' translates > directly into an argument about pointers in C, which permits a pointer > to any element of an array, or to a position immediately past the last > element of an array, but does not allow a pointer to a position before > the beginning of an array. otoh, pointers are annoyingly different to iterators (at least in java - don't know about c++) which start before (you need to call next() to get the first item). this has the advantage of allowing iterators over empty sets (when hasNext() is false immediately), but it's fiddly converting between the two approaches. sorry, this is not really python related (well, i guess it also applies to the new iterator/coroutine stuff if you use them explicitly) andrew -- http://www.acooke.org/andrew From news at datatailors.xs4all.nl Tue Apr 15 11:21:45 2003 From: news at datatailors.xs4all.nl (Peter van Kampen) Date: Tue, 15 Apr 2003 17:21:45 +0200 Subject: Python and Schools References: Message-ID: In article , Alex Martelli wrote: > Aahz wrote: > >> In article , >> Paul Watson wrote: >>> >>>We need to teach students correct design priciples to build something >>>greater than what already exists. We will never get very far if we >>>require everyone to start with a quark or atom. Yes, of course we need >>>some people who design silicon and create microcode. They will learn >>>the low-level details what they need to know as they need it. Knowing >>>great design and organization principles will enable them to make the >>>most of it. >> >> While there's some truth to that, try explaining why the following code >> is a Bad Idea to someone who has no basic understanding of CS: >> >> s = '' >> for i in range(1000000): >> s += str(i) > > I will gladly accept the challenge, if we can agree on the details to > determine whether I've won or lost the bet. What I require is somebody > with real, earnest *interest* in *understanding* this stuff -- I'll > gladly undertake to supply all necessary *background*, but I have no > idea on how to awake real interest in somebody whose motivation for > learning is just "serving time" or some vague hope of getting a good > paying job (and that would be just as much of a problem, whether the > subject was "CS", "programming", or "artichoke farming techniques"). I would gladly volunteer to be that somebody, although I realize it won't happen (Practicallity beats geograpy ;-)) But I think you'll be surprised about the number of people who *would* want to understand the basics without necessarily (re-)entering university for a CS-course. Let me tell you my background, perhaps it can serve as an example. I am a programmer by accident. I love the pleasure of 'creating' when writing programs/scripts/whatever. I studied English literature but I have toyed with computers over the years, mostly as a means to store/retrieve stuff my brain (sadly) keeps forgetting (that's why I have always been interested in databases). Thanks to BASIC I learned on a Commodore 64 and dBase I learned on my parents computer, back in the 1980's I found myself faced with the opportunity/neccesity (as I said, totally by accident) to develop an MS-Access-application in 1999 (a long story I won't bother you with). After that was finished I was rather hooked (again after almost 10 years of hardly touching a computer, couldn't afford on either). Once I learned to connect databases to the internet I could make a living out of it (my re-discovery of the computer coincided with the .com-hype), but I could not afford to keep up with Microsofts relentless 'upgrading' so I have gradually moved to linux over the past 2 years. Now I do mostly php/mysql-stuff and try to learn python. I do not understand discussions about O(N) en O(N^2) and would be very interested to learn such things. I have bought 'Python in a Nutshell' and I love it how you explain about tokens, identifiers, keywords and so on. Very few (if at all) 'general purpose' textbooks take the trouble to explain stuff like that. > If the interest is there, and enough Python background to understand > exactly what this program snippet DOES, then in about one or two > hours of face to face instruction I can give a model that will allow > the student to predict this snippet's disastrous performance and > compare it to the expected performance for, e.g., > > s = ''.join([str(i) for in in range(1000000)]) > > It's not rocket science (that's _another_ thread...;-) -- at this > level, it's really simple arithmetic, a decent mental model of "an > abstract underlying machine", AND an interest in understanding this. So +1 for an article/book. I think you could write another best-seller explaining this and similar basic things most CS-students take for granted while there are many more users of python (and many other high-level languages) who use it just to get their jobs done... PterK -- Peter van Kampen pterk -- at -- datatailors.com From greg at brondo.com Mon Apr 7 11:00:01 2003 From: greg at brondo.com (Greg Brondo) Date: Mon, 07 Apr 2003 15:00:01 GMT Subject: Zope large PDF question In-Reply-To: References: Message-ID: David Currie wrote: > Hi everyone. > > I am having some problems serving large(ish) PDF files from Zope. > Basically, Acrobat Reader seems to hang trying to open a PDF directly > from a Zope server when used as an IE plugin. Downloading the file > with right-click/save-as works fine, opening the file in the plugin > when it is stored on an Apache server on the same machine and opening > the file from the same place also works without any problems. So it > looks like the Reader plugin does not play well with Zope. Does > anyone have any ideas on why this could be happening? Does Zope have > problems transferring large files under some circumstances? > > Any ideas/fixes would be much appreciated. :) > > Thanks. > > David Currie Actually, you're probably hitting the same bug I did with IE. It's documented in MS's knowledge base. Try this: In acrobat under General Prefs you should be able to set acrobat to NOT open the document in IE. Instead, it will open in a standalone acrobat. Try that and see if it fixes the problem. Greg B. From rstephens at vectron.com Tue Apr 29 20:03:40 2003 From: rstephens at vectron.com (Ron Stephens) Date: 29 Apr 2003 17:03:40 -0700 Subject: Python Tutorials References: <15451.8030105@earthlink.net> Message-ID: Nick Vargish